/* This file is part of Telegram Desktop, the official desktop application for the Telegram messaging service. For license and copyright information please follow this link: https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once #include "api/api_common.h" #include "base/timer.h" #include "base/flat_map.h" #include "base/flat_set.h" #include "mtproto/sender.h" #include "data/stickers/data_stickers_set.h" #include "data/data_messages.h" class TaskQueue; struct MessageGroupId; struct SendingAlbum; enum class SendMediaType; struct FileLoadTo; struct ChatRestrictionsInfo; namespace Main { class Session; } // namespace Main namespace Data { struct UpdatedFileReferences; class WallPaper; struct ResolvedForwardDraft; } // namespace Data namespace InlineBots { class Result; } // namespace InlineBots namespace Storage { enum class SharedMediaType : signed char; class DownloadMtprotoTask; class Account; } // namespace Storage namespace Dialogs { class Key; } // namespace Dialogs namespace Ui { struct PreparedList; } // namespace Ui namespace Api { class Updates; class Authorizations; class AttachedStickers; class BlockedPeers; class CloudPassword; class SelfDestruct; class SensitiveContent; class GlobalPrivacy; class UserPrivacy; class InviteLinks; class ViewsManager; namespace details { inline QString ToString(const QString &value) { return value; } inline QString ToString(int32 value) { return QString::number(value); } inline QString ToString(uint64 value) { return QString::number(value); } template inline QString ToString(ChatIdType value) { return QString::number(value.bare); } inline QString ToString(PeerId value) { return QString::number(value.value); } } // namespace details template < typename ...Types, typename = std::enable_if_t<(sizeof...(Types) > 0)>> QString RequestKey(Types &&...values) { const auto strings = { details::ToString(values)... }; if (strings.size() == 1) { return *strings.begin(); } auto result = QString(); result.reserve( ranges::accumulate(strings, 0, ranges::plus(), &QString::size)); for (const auto &string : strings) { result.append(string); } return result; } } // namespace Api class ApiWrap final : public MTP::Sender { public: using SendAction = Api::SendAction; using MessageToSend = Api::MessageToSend; explicit ApiWrap(not_null session); ~ApiWrap(); [[nodiscard]] Main::Session &session() const; [[nodiscard]] Storage::Account &local() const; [[nodiscard]] Api::Updates &updates() const; void applyUpdates( const MTPUpdates &updates, uint64 sentMessageRandomId = 0); int applyAffectedHistory( PeerData *peer, // May be nullptr, like for deletePhoneCallHistory. const MTPmessages_AffectedHistory &result); void registerModifyRequest(const QString &key, mtpRequestId requestId); void clearModifyRequest(const QString &key); void applyNotifySettings( MTPInputNotifyPeer peer, const MTPPeerNotifySettings &settings); void saveCurrentDraftToCloud(); void savePinnedOrder(Data::Folder *folder); void toggleHistoryArchived( not_null history, bool archived, Fn callback); using RequestMessageDataCallback = Fn; void requestMessageData( ChannelData *channel, MsgId msgId, RequestMessageDataCallback callback); QString exportDirectMessageLink( not_null item, bool inRepliesContext); void requestContacts(); void requestDialogs(Data::Folder *folder = nullptr); void requestPinnedDialogs(Data::Folder *folder = nullptr); void requestMoreBlockedByDateDialogs(); void requestMoreDialogsIfNeeded(); rpl::producer dialogsLoadMayBlockByDate() const; rpl::producer dialogsLoadBlockedByDate() const; void requestWallPaper( const QString &slug, Fn done, Fn fail); void requestFullPeer(not_null peer); void requestPeer(not_null peer); void requestPeers(const QList &peers); void requestPeerSettings(not_null peer); void requestLastParticipants(not_null channel); void requestBots(not_null channel); void requestAdmins(not_null channel); void requestParticipantsCountDelayed(not_null channel); using UpdatedFileReferences = Data::UpdatedFileReferences; using FileReferencesHandler = FnMut; void refreshFileReference( Data::FileOrigin origin, FileReferencesHandler &&handler); void refreshFileReference( Data::FileOrigin origin, not_null task, int requestId, const QByteArray ¤t); void requestChangelog( const QString &sinceVersion, Fn callback); void refreshTopPromotion(); void requestDeepLinkInfo( const QString &path, Fn callback); void requestTermsUpdate(); void acceptTerms(bytes::const_span termsId); void checkChatInvite( const QString &hash, FnMut done, Fn fail); void importChatInvite(const QString &hash); void requestChannelMembersForAdd( not_null channel, Fn callback); void processFullPeer( not_null peer, const MTPmessages_ChatFull &result); void processFullPeer( not_null user, const MTPUserFull &result); void migrateChat( not_null chat, FnMut)> done, Fn fail = nullptr); void markMediaRead(const base::flat_set> &items); void markMediaRead(not_null item); void requestSelfParticipant(not_null channel); void kickParticipant( not_null chat, not_null participant); void kickParticipant( not_null channel, not_null participant, ChatRestrictionsInfo currentRights); void unblockParticipant( not_null channel, not_null participant); void deleteAllFromUser( not_null channel, not_null from); void requestWebPageDelayed(WebPageData *page); void clearWebPageRequest(WebPageData *page); void clearWebPageRequests(); void scheduleStickerSetRequest(uint64 setId, uint64 access); void requestStickerSets(); void saveStickerSets( const Data::StickersSetsOrder &localOrder, const Data::StickersSetsOrder &localRemoved, bool setsMasks); void updateStickers(); void updateMasks(); void requestRecentStickersForce(bool attached = false); void setGroupStickerSet( not_null megagroup, const StickerSetIdentifier &set); std::vector> *stickersByEmoji( not_null emoji); void joinChannel(not_null channel); void leaveChannel(not_null channel); void requestNotifySettings(const MTPInputNotifyPeer &peer); void updateNotifySettingsDelayed(not_null peer); void saveDraftToCloudDelayed(not_null history); static int OnlineTillFromStatus( const MTPUserStatus &status, int currentOnlineTill); void clearHistory(not_null peer, bool revoke); void deleteConversation(not_null peer, bool revoke); base::Observable &fullPeerUpdated() { return _fullPeerUpdated; } bool isQuitPrevent(); void jumpToDate(Dialogs::Key chat, const QDate &date); void preloadEnoughUnreadMentions(not_null history); void checkForUnreadMentions( const base::flat_set &possiblyReadMentions, ChannelData *channel = nullptr); using SliceType = Data::LoadDirection; void requestSharedMedia( not_null peer, Storage::SharedMediaType type, MsgId messageId, SliceType slice); void requestSharedMediaCount( not_null peer, Storage::SharedMediaType type); void requestUserPhotos( not_null user, PhotoId afterId); void readFeaturedSetDelayed(uint64 setId); void parseChannelParticipants( not_null channel, const MTPchannels_ChannelParticipants &result, Fn &list)> callbackList, Fn callbackNotModified = nullptr); void parseRecentChannelParticipants( not_null channel, const MTPchannels_ChannelParticipants &result, Fn &list)> callbackList = nullptr, Fn callbackNotModified = nullptr); void addChatParticipants( not_null peer, const std::vector> &users, Fn done = nullptr); rpl::producer sendActions() const { return _sendActions.events(); } void sendAction(const SendAction &action); void finishForwarding(const SendAction &action); void forwardMessages( Data::ResolvedForwardDraft &&draft, const SendAction &action, FnMut &&successCallback = nullptr); void shareContact( const QString &phone, const QString &firstName, const QString &lastName, const SendAction &action); void shareContact(not_null user, const SendAction &action); void applyAffectedMessages( not_null peer, const MTPmessages_AffectedMessages &result); void sendVoiceMessage( QByteArray result, VoiceWaveform waveform, int duration, const SendAction &action); void sendFiles( Ui::PreparedList &&list, SendMediaType type, TextWithTags &&caption, std::shared_ptr album, const SendAction &action); void sendFile( const QByteArray &fileContent, SendMediaType type, const SendAction &action); void editMedia( Ui::PreparedList &&list, SendMediaType type, TextWithTags &&caption, const SendAction &action); void sendUploadedPhoto( FullMsgId localId, const MTPInputFile &file, Api::SendOptions options, std::vector attachedStickers); void sendUploadedDocument( FullMsgId localId, const MTPInputFile &file, const std::optional &thumb, Api::SendOptions options, std::vector attachedStickers); void cancelLocalItem(not_null item); void sendMessage(MessageToSend &&message); void sendBotStart(not_null bot, PeerData *chat = nullptr); void sendInlineResult( not_null bot, not_null data, const SendAction &action); void sendMessageFail( const MTP::Error &error, not_null peer, uint64 randomId = 0, FullMsgId itemId = FullMsgId()); void uploadPeerPhoto(not_null peer, QImage &&image); void clearPeerPhoto(not_null photo); void reloadContactSignupSilent(); rpl::producer contactSignupSilent() const; std::optional contactSignupSilentCurrent() const; void saveContactSignupSilent(bool silent); void saveSelfBio(const QString &text, FnMut done); [[nodiscard]] Api::Authorizations &authorizations(); [[nodiscard]] Api::AttachedStickers &attachedStickers(); [[nodiscard]] Api::BlockedPeers &blockedPeers(); [[nodiscard]] Api::CloudPassword &cloudPassword(); [[nodiscard]] Api::SelfDestruct &selfDestruct(); [[nodiscard]] Api::SensitiveContent &sensitiveContent(); [[nodiscard]] Api::GlobalPrivacy &globalPrivacy(); [[nodiscard]] Api::UserPrivacy &userPrivacy(); [[nodiscard]] Api::InviteLinks &inviteLinks(); [[nodiscard]] Api::ViewsManager &views(); void createPoll( const PollData &data, const SendAction &action, Fn done, Fn fail); void sendPollVotes( FullMsgId itemId, const std::vector &options); void closePoll(not_null item); void reloadPollResults(not_null item); void updatePrivacyLastSeens(); private: struct MessageDataRequest { using Callbacks = std::vector; mtpRequestId requestId = 0; Callbacks callbacks; }; using MessageDataRequests = base::flat_map; using SharedMediaType = Storage::SharedMediaType; struct StickersByEmoji { std::vector> list; uint64 hash = 0; crl::time received = 0; }; struct DialogsLoadState { TimeId offsetDate = 0; MsgId offsetId = 0; PeerData *offsetPeer = nullptr; mtpRequestId requestId = 0; bool listReceived = false; mtpRequestId pinnedRequestId = 0; bool pinnedReceived = false; }; void setupSupportMode(); void refreshDialogsLoadBlocked(); void updateDialogsOffset( Data::Folder *folder, const QVector &dialogs, const QVector &messages); void requestMoreDialogs(Data::Folder *folder); DialogsLoadState *dialogsLoadState(Data::Folder *folder); void dialogsLoadFinish(Data::Folder *folder); void checkQuitPreventFinished(); void saveDraftsToCloud(); void resolveMessageDatas(); void finalizeMessageDataRequest( ChannelData *channel, mtpRequestId requestId); [[nodiscard]] QVector collectMessageIds( const MessageDataRequests &requests); [[nodiscard]] MessageDataRequests *messageDataRequests( ChannelData *channel, bool onlyExisting = false); void gotChatFull( not_null peer, const MTPmessages_ChatFull &result, mtpRequestId req); void gotUserFull( not_null user, const MTPUserFull &result, mtpRequestId req); void applyLastParticipantsList( not_null channel, int availableCount, const QVector &list); void applyBotsList( not_null channel, int availableCount, const QVector &list); void resolveWebPages(); void gotWebPages( ChannelData *channel, const MTPmessages_Messages &result, mtpRequestId req); void gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result); void requestStickers(TimeId now); void requestMasks(TimeId now); void requestRecentStickers(TimeId now, bool attached = false); void requestRecentStickersWithHash(uint64 hash, bool attached = false); void requestFavedStickers(TimeId now); void requestFeaturedStickers(TimeId now); void requestSavedGifs(TimeId now); void readFeaturedSets(); void refreshChannelAdmins( not_null channel, const QVector &participants); void jumpToHistoryDate(not_null peer, const QDate &date); template void requestMessageAfterDate( not_null peer, const QDate &date, Callback &&callback); void sharedMediaDone( not_null peer, SharedMediaType type, MsgId messageId, SliceType slice, const MTPmessages_Messages &result); void userPhotosDone( not_null user, PhotoId photoId, const MTPphotos_Photos &result); void sendSharedContact( const QString &phone, const QString &firstName, const QString &lastName, UserId userId, const SendAction &action); void deleteHistory( not_null peer, bool justClear, bool revoke); void applyAffectedMessages(const MTPmessages_AffectedMessages &result); void deleteAllFromUserSend( not_null channel, not_null from); void uploadAlbumMedia( not_null item, const MessageGroupId &groupId, const MTPInputMedia &media); void sendAlbumWithUploaded( not_null item, const MessageGroupId &groupId, const MTPInputMedia &media); void sendAlbumWithCancelled( not_null item, const MessageGroupId &groupId); void sendAlbumIfReady(not_null album); void sendMedia( not_null item, const MTPInputMedia &media, Api::SendOptions options); void sendMediaWithRandomId( not_null item, const MTPInputMedia &media, Api::SendOptions options, uint64 randomId); FileLoadTo fileLoadTaskOptions(const SendAction &action) const; void getTopPromotionDelayed(TimeId now, TimeId next); void topPromotionDone(const MTPhelp_PromoData &proxy); void sendNotifySettingsUpdates(); template void requestFileReference( Data::FileOrigin origin, FileReferencesHandler &&handler, Request &&data); void photoUploadReady(const FullMsgId &msgId, const MTPInputFile &file); void migrateDone( not_null peer, not_null channel); void migrateFail(not_null peer, const MTP::Error &error); not_null _session; base::flat_map _modifyRequests; MessageDataRequests _messageDataRequests; base::flat_map< ChannelData*, MessageDataRequests> _channelMessageDataRequests; SingleQueuedInvokation _messageDataResolveDelayed; using PeerRequests = QMap; PeerRequests _fullPeerRequests; PeerRequests _peerRequests; base::flat_set> _requestedPeerSettings; PeerRequests _participantsRequests; PeerRequests _botsRequests; PeerRequests _adminsRequests; base::DelayedCallTimer _participantsCountRequestTimer; ChannelData *_channelMembersForAdd = nullptr; mtpRequestId _channelMembersForAddRequestId = 0; Fn _channelMembersForAddCallback; base::flat_map< not_null, std::pair>> _historyArchivedRequests; using KickRequest = std::pair< not_null, not_null>; base::flat_map _kickRequests; base::flat_set> _selfParticipantRequests; QMap _webPagesPending; base::Timer _webPagesTimer; QMap > _stickerSetRequests; QMap _channelAmInRequests; base::flat_map _notifySettingRequests; base::flat_map, mtpRequestId> _draftsSaveRequestIds; base::Timer _draftsSaveTimer; base::flat_set _stickerSetDisenableRequests; base::flat_set _maskSetDisenableRequests; mtpRequestId _masksReorderRequestId = 0; mtpRequestId _stickersReorderRequestId = 0; mtpRequestId _stickersClearRecentRequestId = 0; mtpRequestId _stickersClearRecentAttachedRequestId = 0; mtpRequestId _stickersUpdateRequest = 0; mtpRequestId _masksUpdateRequest = 0; mtpRequestId _recentStickersUpdateRequest = 0; mtpRequestId _recentAttachedStickersUpdateRequest = 0; mtpRequestId _favedStickersUpdateRequest = 0; mtpRequestId _featuredStickersUpdateRequest = 0; mtpRequestId _savedGifsUpdateRequest = 0; base::Timer _featuredSetsReadTimer; base::flat_set _featuredSetsRead; base::flat_map, StickersByEmoji> _stickersByEmoji; mtpRequestId _contactsRequestId = 0; mtpRequestId _contactsStatusesRequestId = 0; base::flat_map, mtpRequestId> _unreadMentionsRequests; base::flat_set, SharedMediaType, MsgId, SliceType>> _sharedMediaRequests; base::flat_map, mtpRequestId> _userPhotosRequests; std::unique_ptr _dialogsLoadState; TimeId _dialogsLoadTill = 0; rpl::variable _dialogsLoadMayBlockByDate = false; rpl::variable _dialogsLoadBlockedByDate = false; base::flat_map< not_null, DialogsLoadState> _foldersLoadState; rpl::event_stream _sendActions; std::unique_ptr _fileLoader; base::flat_map> _sendingAlbums; base::Observable _fullPeerUpdated; mtpRequestId _topPromotionRequestId = 0; std::pair _topPromotionKey; TimeId _topPromotionNextRequestTime = TimeId(0); base::Timer _topPromotionTimer; base::flat_set> _updateNotifySettingsPeers; base::Timer _updateNotifySettingsTimer; std::map< Data::FileOrigin, std::vector> _fileReferenceHandlers; mtpRequestId _deepLinkInfoRequestId = 0; crl::time _termsUpdateSendAt = 0; mtpRequestId _termsUpdateRequestId = 0; mtpRequestId _checkInviteRequestId = 0; FnMut _checkInviteDone; Fn _checkInviteFail; struct MigrateCallbacks { FnMut)> done; Fn fail; }; base::flat_map< not_null, std::vector> _migrateCallbacks; std::vector> _supportContactCallbacks; base::flat_map> _peerPhotoUploads; mtpRequestId _saveBioRequestId = 0; FnMut _saveBioDone; QString _saveBioText; const std::unique_ptr _authorizations; const std::unique_ptr _attachedStickers; const std::unique_ptr _blockedPeers; const std::unique_ptr _cloudPassword; const std::unique_ptr _selfDestruct; const std::unique_ptr _sensitiveContent; const std::unique_ptr _globalPrivacy; const std::unique_ptr _userPrivacy; const std::unique_ptr _inviteLinks; const std::unique_ptr _views; base::flat_map _pollVotesRequestIds; base::flat_map _pollCloseRequestIds; base::flat_map _pollReloadRequestIds; mtpRequestId _wallPaperRequestId = 0; QString _wallPaperSlug; Fn _wallPaperDone; Fn _wallPaperFail; mtpRequestId _contactSignupSilentRequestId = 0; std::optional _contactSignupSilent; rpl::event_stream _contactSignupSilentChanges; base::flat_map _unlikelyMessageLinks; };