From 0ad7dcaef9fec4a9771ecb784e2bce1a2c4f31b6 Mon Sep 17 00:00:00 2001 From: John Preston Date: Thu, 11 Jun 2020 20:09:46 +0400 Subject: [PATCH] Remove MTP::MainInstance() global access point. --- Telegram/SourceFiles/api/api_updates.cpp | 2 +- Telegram/SourceFiles/api/api_updates.h | 2 +- Telegram/SourceFiles/apiwrap.cpp | 6 +- .../SourceFiles/boxes/add_contact_box.cpp | 128 ++--- Telegram/SourceFiles/boxes/add_contact_box.h | 24 +- Telegram/SourceFiles/boxes/background_box.cpp | 2 +- Telegram/SourceFiles/boxes/calendar_box.cpp | 3 +- .../SourceFiles/boxes/change_phone_box.cpp | 93 ++- Telegram/SourceFiles/boxes/confirm_box.cpp | 33 +- Telegram/SourceFiles/boxes/confirm_box.h | 14 +- .../SourceFiles/boxes/confirm_phone_box.cpp | 71 ++- .../SourceFiles/boxes/confirm_phone_box.h | 29 +- Telegram/SourceFiles/boxes/connection_box.cpp | 7 +- .../SourceFiles/boxes/edit_caption_box.cpp | 38 +- Telegram/SourceFiles/boxes/edit_caption_box.h | 13 +- Telegram/SourceFiles/boxes/passcode_box.cpp | 90 ++- Telegram/SourceFiles/boxes/passcode_box.h | 17 +- .../boxes/peer_list_controllers.cpp | 2 +- .../boxes/peers/add_participants_box.cpp | 4 +- .../boxes/peers/edit_participants_box.cpp | 4 +- .../boxes/peers/edit_peer_info_box.cpp | 2 +- .../boxes/peers/edit_peer_type_box.cpp | 2 +- Telegram/SourceFiles/boxes/rate_call_box.cpp | 2 +- Telegram/SourceFiles/boxes/report_box.cpp | 44 +- Telegram/SourceFiles/boxes/report_box.h | 9 +- Telegram/SourceFiles/boxes/sessions_box.cpp | 3 +- Telegram/SourceFiles/boxes/share_box.cpp | 29 +- Telegram/SourceFiles/boxes/share_box.h | 9 +- .../SourceFiles/boxes/sticker_set_box.cpp | 2 +- Telegram/SourceFiles/boxes/sticker_set_box.h | 4 +- Telegram/SourceFiles/boxes/stickers_box.cpp | 60 +- Telegram/SourceFiles/boxes/stickers_box.h | 15 +- Telegram/SourceFiles/boxes/username_box.cpp | 54 +- Telegram/SourceFiles/boxes/username_box.h | 13 +- .../calls/calls_box_controller.cpp | 3 +- Telegram/SourceFiles/calls/calls_call.cpp | 2 +- Telegram/SourceFiles/calls/calls_instance.cpp | 2 +- .../chat_helpers/gifs_list_widget.cpp | 3 +- .../chat_helpers/stickers_dice_pack.cpp | 1 + .../chat_helpers/stickers_list_widget.cpp | 2 +- .../SourceFiles/core/local_url_handlers.cpp | 2 +- Telegram/SourceFiles/data/data_session.cpp | 8 +- .../data/stickers/data_stickers.cpp | 12 +- .../dialogs/dialogs_inner_widget.h | 8 +- .../SourceFiles/dialogs/dialogs_widget.cpp | 141 ++--- Telegram/SourceFiles/dialogs/dialogs_widget.h | 12 +- .../SourceFiles/export/export_api_wrap.cpp | 4 +- Telegram/SourceFiles/export/export_api_wrap.h | 2 +- .../SourceFiles/export/export_controller.cpp | 10 +- .../SourceFiles/export/export_controller.h | 9 +- .../admin_log/history_admin_log_inner.cpp | 2 +- .../SourceFiles/history/history_widget.cpp | 162 +++--- Telegram/SourceFiles/history/history_widget.h | 20 +- .../view/history_view_top_bar_widget.cpp | 2 +- .../info_common_groups_inner_widget.cpp | 3 +- .../polls/info_polls_results_inner_widget.cpp | 3 +- .../inline_bots/inline_results_widget.cpp | 8 +- Telegram/SourceFiles/main/main_account.cpp | 7 +- Telegram/SourceFiles/main/main_session.cpp | 6 +- Telegram/SourceFiles/main/main_session.h | 7 +- Telegram/SourceFiles/mainwidget.cpp | 89 +-- Telegram/SourceFiles/mainwidget.h | 27 +- Telegram/SourceFiles/mtproto/facade.cpp | 14 +- Telegram/SourceFiles/mtproto/facade.h | 84 +-- Telegram/SourceFiles/mtproto/mtp_instance.cpp | 11 +- Telegram/SourceFiles/mtproto/mtp_instance.h | 4 +- .../mtproto/mtproto_concurrent_sender.cpp | 14 +- .../mtproto/mtproto_concurrent_sender.h | 6 +- .../mtproto/mtproto_rpc_sender.cpp | 21 - .../SourceFiles/mtproto/mtproto_rpc_sender.h | 543 ------------------ Telegram/SourceFiles/mtproto/sender.h | 23 +- .../passport/passport_form_controller.cpp | 6 +- .../passport/passport_panel_controller.cpp | 4 +- .../settings/settings_advanced.cpp | 7 +- .../settings/settings_privacy_controllers.cpp | 2 +- .../settings/settings_privacy_security.cpp | 4 +- .../storage/download_manager_mtproto.cpp | 4 +- Telegram/SourceFiles/storage/file_upload.h | 2 +- .../SourceFiles/storage/localimageloader.cpp | 14 +- .../SourceFiles/storage/localimageloader.h | 7 +- .../SourceFiles/support/support_helper.cpp | 2 +- .../window/themes/window_theme.cpp | 6 +- .../window/themes/window_theme_editor_box.cpp | 8 +- .../window/window_connecting_widget.cpp | 12 +- 84 files changed, 823 insertions(+), 1362 deletions(-) diff --git a/Telegram/SourceFiles/api/api_updates.cpp b/Telegram/SourceFiles/api/api_updates.cpp index f66bac02b..82a835de7 100644 --- a/Telegram/SourceFiles/api/api_updates.cpp +++ b/Telegram/SourceFiles/api/api_updates.cpp @@ -649,7 +649,7 @@ void Updates::getChannelDifference( } void Updates::sendPing() { - api().instance()->ping(); + _session->mtp()->ping(); } void Updates::addActiveChat(rpl::producer chat) { diff --git a/Telegram/SourceFiles/api/api_updates.h b/Telegram/SourceFiles/api/api_updates.h index c85b94494..98bd13d60 100644 --- a/Telegram/SourceFiles/api/api_updates.h +++ b/Telegram/SourceFiles/api/api_updates.h @@ -7,10 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once -#include "mtproto/mtproto_rpc_sender.h" #include "data/data_pts_waiter.h" #include "base/timer.h" +class RPCError; class ApiWrap; class History; diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp index e98047ca5..3c7eb19f7 100644 --- a/Telegram/SourceFiles/apiwrap.cpp +++ b/Telegram/SourceFiles/apiwrap.cpp @@ -4242,6 +4242,7 @@ void ApiWrap::sendVoiceMessage( const auto caption = TextWithTags(); const auto to = fileLoadTaskOptions(action); _fileLoader->addTask(std::make_unique( + instance()->mainDcId(), result, duration, waveform, @@ -4260,6 +4261,7 @@ void ApiWrap::editMedia( auto &file = list.files.front(); const auto to = fileLoadTaskOptions(action); _fileLoader->addTask(std::make_unique( + instance()->mainDcId(), file.path, file.content, std::move(file.information), @@ -4307,6 +4309,7 @@ void ApiWrap::sendFiles( } } tasks.push_back(std::make_unique( + instance()->mainDcId(), file.path, file.content, std::move(file.information), @@ -4333,6 +4336,7 @@ void ApiWrap::sendFile( const auto to = fileLoadTaskOptions(action); auto caption = TextWithTags(); _fileLoader->addTask(std::make_unique( + instance()->mainDcId(), QString(), fileContent, nullptr, @@ -5017,7 +5021,7 @@ FileLoadTo ApiWrap::fileLoadTaskOptions(const SendAction &action) const { void ApiWrap::uploadPeerPhoto(not_null peer, QImage &&image) { peer = peer->migrateToOrMe(); - const auto ready = PreparePeerPhoto(peer->id, std::move(image)); + const auto ready = PreparePeerPhoto(instance()->mainDcId(), peer->id, std::move(image)); const auto fakeId = FullMsgId( peerToChannel(peer->id), diff --git a/Telegram/SourceFiles/boxes/add_contact_box.cpp b/Telegram/SourceFiles/boxes/add_contact_box.cpp index 5615946d1..c352047d5 100644 --- a/Telegram/SourceFiles/boxes/add_contact_box.cpp +++ b/Telegram/SourceFiles/boxes/add_contact_box.cpp @@ -453,7 +453,7 @@ GroupInfoBox::GroupInfoBox( const QString &title, Fn)> channelDone) : _navigation(navigation) -, _api(_navigation->session().api().instance()) +, _api(_navigation->session().mtp()) , _type(type) , _initialTitle(title) , _channelDone(std::move(channelDone)) { @@ -750,6 +750,7 @@ SetupChannelBox::SetupChannelBox( bool existing) : _navigation(navigation) , _channel(channel) +, _api(_channel->session().mtp()) , _existing(existing) , _privacyGroup( std::make_shared>(Privacy::Public)) @@ -797,12 +798,12 @@ void SetupChannelBox::prepare() { setMouseTracking(true); - _checkRequestId = MTP::send( - MTPchannels_CheckUsername( - _channel->inputChannel, - MTP_string("preston")), - RPCDoneHandlerPtr(), - rpcFail(&SetupChannelBox::onFirstCheckFail)); + _checkRequestId = _api.request(MTPchannels_CheckUsername( + _channel->inputChannel, + MTP_string("preston") + )).fail([=](const RPCError &error) { + firstCheckFail(error); + }).send(); addButton(tr::lng_settings_save(), [=] { save(); }); addButton( @@ -950,12 +951,22 @@ void SetupChannelBox::updateSelected(const QPoint &cursorGlobalPosition) { } void SetupChannelBox::save() { + const auto saveUsername = [&](const QString &link) { + _sentUsername = link; + _saveRequestId = _api.request(MTPchannels_UpdateUsername( + _channel->inputChannel, + MTP_string(_sentUsername) + )).done([=](const MTPBool &result) { + updateDone(result); + }).fail([=](const RPCError &error) { + updateFail(error); + }).send(); + }; if (_saveRequestId) { return; } else if (_privacyGroup->value() == Privacy::Private) { if (_existing) { - _sentUsername = QString(); - _saveRequestId = MTP::send(MTPchannels_UpdateUsername(_channel->inputChannel, MTP_string(_sentUsername)), rpcDone(&SetupChannelBox::onUpdateDone), rpcFail(&SetupChannelBox::onUpdateFail)); + saveUsername(QString()); } else { closeBox(); } @@ -966,8 +977,7 @@ void SetupChannelBox::save() { _link->showError(); return; } - _sentUsername = link; - _saveRequestId = MTP::send(MTPchannels_UpdateUsername(_channel->inputChannel, MTP_string(_sentUsername)), rpcDone(&SetupChannelBox::onUpdateDone), rpcFail(&SetupChannelBox::onUpdateFail)); + saveUsername(link); } } @@ -1010,17 +1020,19 @@ void SetupChannelBox::handleChange() { void SetupChannelBox::check() { if (_checkRequestId) { - MTP::cancel(_checkRequestId); + _channel->session().api().request(_checkRequestId).cancel(); } QString link = _link->text().trimmed(); if (link.size() >= kMinUsernameLength) { _checkUsername = link; - _checkRequestId = MTP::send( - MTPchannels_CheckUsername( - _channel->inputChannel, - MTP_string(link)), - rpcDone(&SetupChannelBox::onCheckDone), - rpcFail(&SetupChannelBox::onCheckFail)); + _checkRequestId = _api.request(MTPchannels_CheckUsername( + _channel->inputChannel, + MTP_string(link) + )).done([=](const MTPBool &result) { + checkDone(result); + }).fail([=](const RPCError &error) { + checkFail(error); + }).send(); } } @@ -1053,38 +1065,36 @@ void SetupChannelBox::privacyChanged(Privacy value) { update(); } -void SetupChannelBox::onUpdateDone(const MTPBool &result) { +void SetupChannelBox::updateDone(const MTPBool &result) { _channel->setName(TextUtilities::SingleLine(_channel->name), _sentUsername); closeBox(); } -bool SetupChannelBox::onUpdateFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void SetupChannelBox::updateFail(const RPCError &error) { _saveRequestId = 0; QString err(error.type()); - if (err == "USERNAME_NOT_MODIFIED" || _sentUsername == _channel->username) { - _channel->setName(TextUtilities::SingleLine(_channel->name), TextUtilities::SingleLine(_sentUsername)); + if (err == "USERNAME_NOT_MODIFIED" + || _sentUsername == _channel->username) { + _channel->setName( + TextUtilities::SingleLine(_channel->name), + TextUtilities::SingleLine(_sentUsername)); closeBox(); - return true; } else if (err == "USERNAME_INVALID") { _link->setFocus(); _link->showError(); _errorText = tr::lng_create_channel_link_invalid(tr::now); update(); - return true; } else if (err == "USERNAME_OCCUPIED" || err == "USERNAMES_UNAVAILABLE") { _link->setFocus(); _link->showError(); _errorText = tr::lng_create_channel_link_occupied(tr::now); update(); - return true; + } else { + _link->setFocus(); } - _link->setFocus(); - return true; } -void SetupChannelBox::onCheckDone(const MTPBool &result) { +void SetupChannelBox::checkDone(const MTPBool &result) { _checkRequestId = 0; QString newError = (mtpIsTrue(result) || _checkUsername == _channel->username) ? QString() : tr::lng_create_channel_link_occupied(tr::now); QString newGood = newError.isEmpty() ? tr::lng_create_channel_link_available(tr::now) : QString(); @@ -1095,14 +1105,11 @@ void SetupChannelBox::onCheckDone(const MTPBool &result) { } } -bool SetupChannelBox::onCheckFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void SetupChannelBox::checkFail(const RPCError &error) { _checkRequestId = 0; QString err(error.type()); if (err == qstr("CHANNEL_PUBLIC_GROUP_NA")) { Ui::hideLayer(); - return true; } else if (err == qstr("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) { if (_existing) { showRevokePublicLinkBoxForEdit(); @@ -1110,19 +1117,16 @@ bool SetupChannelBox::onCheckFail(const RPCError &error) { _tooMuchUsernames = true; _privacyGroup->setValue(Privacy::Private); } - return true; } else if (err == qstr("USERNAME_INVALID")) { _errorText = tr::lng_create_channel_link_invalid(tr::now); update(); - return true; } else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != _channel->username) { _errorText = tr::lng_create_channel_link_occupied(tr::now); update(); - return true; + } else { + _goodText = QString(); + _link->setFocus(); } - _goodText = QString(); - _link->setFocus(); - return true; } void SetupChannelBox::showRevokePublicLinkBoxForEdit() { @@ -1142,14 +1146,11 @@ void SetupChannelBox::showRevokePublicLinkBoxForEdit() { Ui::LayerOption::KeepOther); } -bool SetupChannelBox::onFirstCheckFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void SetupChannelBox::firstCheckFail(const RPCError &error) { _checkRequestId = 0; const auto &type = error.type(); if (type == qstr("CHANNEL_PUBLIC_GROUP_NA")) { Ui::hideLayer(); - return true; } else if (type == qstr("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) { if (_existing) { showRevokePublicLinkBoxForEdit(); @@ -1157,15 +1158,15 @@ bool SetupChannelBox::onFirstCheckFail(const RPCError &error) { _tooMuchUsernames = true; _privacyGroup->setValue(Privacy::Private); } - return true; + } else { + _goodText = QString(); + _link->setFocus(); } - _goodText = QString(); - _link->setFocus(); - return true; } EditNameBox::EditNameBox(QWidget*, not_null user) : _user(user) +, _api(_user->session().mtp()) , _first(this, st::defaultInputField, tr::lng_signup_firstname(), _user->firstName) , _last(this, st::defaultInputField, tr::lng_signup_lastname(), _user->lastName) , _invertOrder(langFirstNameGoesSecond()) { @@ -1248,14 +1249,16 @@ void EditNameBox::save() { _sentName = first; auto flags = MTPaccount_UpdateProfile::Flag::f_first_name | MTPaccount_UpdateProfile::Flag::f_last_name; - _requestId = MTP::send( - MTPaccount_UpdateProfile( - MTP_flags(flags), - MTP_string(first), - MTP_string(last), - MTPstring()), - rpcDone(&EditNameBox::saveSelfDone), - rpcFail(&EditNameBox::saveSelfFail)); + _requestId = _api.request(MTPaccount_UpdateProfile( + MTP_flags(flags), + MTP_string(first), + MTP_string(last), + MTPstring() + )).done([=](const MTPUser &result) { + saveSelfDone(result); + }).fail([=](const RPCError &error) { + saveSelfFail(error); + }).send(); } void EditNameBox::saveSelfDone(const MTPUser &user) { @@ -1263,27 +1266,22 @@ void EditNameBox::saveSelfDone(const MTPUser &user) { closeBox(); } -bool EditNameBox::saveSelfFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void EditNameBox::saveSelfFail(const RPCError &error) { auto err = error.type(); auto first = TextUtilities::SingleLine(_first->getLastText().trimmed()); auto last = TextUtilities::SingleLine(_last->getLastText().trimmed()); if (err == "NAME_NOT_MODIFIED") { _user->setName(first, last, QString(), TextUtilities::SingleLine(_user->username)); closeBox(); - return true; } else if (err == "FIRSTNAME_INVALID") { _first->setFocus(); _first->showError(); - return true; } else if (err == "LASTNAME_INVALID") { _last->setFocus(); _last->showError(); - return true; + } else { + _first->setFocus(); } - _first->setFocus(); - return true; } RevokePublicLinkBox::Inner::Inner( @@ -1292,7 +1290,7 @@ RevokePublicLinkBox::Inner::Inner( Fn revokeCallback) : TWidget(parent) , _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _revokeWidth(st::normalFont->width(tr::lng_channels_too_much_public_revoke(tr::now))) , _revokeCallback(std::move(revokeCallback)) { diff --git a/Telegram/SourceFiles/boxes/add_contact_box.h b/Telegram/SourceFiles/boxes/add_contact_box.h index 488893da8..e72a2fd20 100644 --- a/Telegram/SourceFiles/boxes/add_contact_box.h +++ b/Telegram/SourceFiles/boxes/add_contact_box.h @@ -140,9 +140,8 @@ private: }; -class SetupChannelBox +class SetupChannelBox final : public Ui::BoxContent - , public RPCSender , private base::Subscriber { public: SetupChannelBox( @@ -174,12 +173,12 @@ private: void check(); void save(); - void onUpdateDone(const MTPBool &result); - bool onUpdateFail(const RPCError &error); + void updateDone(const MTPBool &result); + void updateFail(const RPCError &error); - void onCheckDone(const MTPBool &result); - bool onCheckFail(const RPCError &error); - bool onFirstCheckFail(const RPCError &error); + void checkDone(const MTPBool &result); + void checkFail(const RPCError &error); + void firstCheckFail(const RPCError &error); void updateMaxHeight(); @@ -187,6 +186,7 @@ private: const not_null _navigation; const not_null _channel; + MTP::Sender _api; bool _existing = false; @@ -210,7 +210,7 @@ private: }; -class EditNameBox : public Ui::BoxContent, public RPCSender { +class EditNameBox : public Ui::BoxContent { public: EditNameBox(QWidget*, not_null user); @@ -224,9 +224,10 @@ private: void submit(); void save(); void saveSelfDone(const MTPUser &user); - bool saveSelfFail(const RPCError &error); + void saveSelfFail(const RPCError &error); - not_null _user; + const not_null _user; + MTP::Sender _api; object_ptr _first; object_ptr _last; @@ -238,9 +239,8 @@ private: }; -class RevokePublicLinkBox +class RevokePublicLinkBox final : public Ui::BoxContent - , public RPCSender , private base::Subscriber { public: RevokePublicLinkBox( diff --git a/Telegram/SourceFiles/boxes/background_box.cpp b/Telegram/SourceFiles/boxes/background_box.cpp index 625b78149..a39256c42 100644 --- a/Telegram/SourceFiles/boxes/background_box.cpp +++ b/Telegram/SourceFiles/boxes/background_box.cpp @@ -193,7 +193,7 @@ BackgroundBox::Inner::Inner( not_null session) : RpWidget(parent) , _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _check(std::make_unique(st::overviewCheck, [=] { update(); })) { _check->setChecked(true, anim::type::instant); if (_session->data().wallpapers().empty()) { diff --git a/Telegram/SourceFiles/boxes/calendar_box.cpp b/Telegram/SourceFiles/boxes/calendar_box.cpp index a9d5158f7..5fdaabafe 100644 --- a/Telegram/SourceFiles/boxes/calendar_box.cpp +++ b/Telegram/SourceFiles/boxes/calendar_box.cpp @@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "boxes/calendar_box.h" -#include "mtproto/mtproto_rpc_sender.h" #include "ui/widgets/buttons.h" #include "lang/lang_keys.h" #include "ui/effects/ripple_animation.h" @@ -199,7 +198,7 @@ QString CalendarBox::Context::labelFromIndex(int index) const { return QString::number(day()); } -class CalendarBox::Inner : public TWidget, public RPCSender, private base::Subscriber { +class CalendarBox::Inner : public TWidget, private base::Subscriber { public: Inner( QWidget *parent, diff --git a/Telegram/SourceFiles/boxes/change_phone_box.cpp b/Telegram/SourceFiles/boxes/change_phone_box.cpp index 110047ac0..9369fa04b 100644 --- a/Telegram/SourceFiles/boxes/change_phone_box.cpp +++ b/Telegram/SourceFiles/boxes/change_phone_box.cpp @@ -19,7 +19,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "main/main_session.h" #include "data/data_session.h" #include "data/data_user.h" -#include "mtproto/facade.h" +#include "mtproto/sender.h" +#include "apiwrap.h" #include "app.h" #include "styles/style_layers.h" #include "styles/style_boxes.h" @@ -76,14 +77,15 @@ protected: private: void submit(); - void sendPhoneDone(const QString &phoneNumber, const MTPauth_SentCode &result); - bool sendPhoneFail(const QString &phoneNumber, const RPCError &error); + void sendPhoneDone(const MTPauth_SentCode &result, const QString &phoneNumber); + void sendPhoneFail(const RPCError &error, const QString &phoneNumber); void showError(const QString &text); void hideError() { showError(QString()); } const not_null _session; + MTP::Sender _api; object_ptr _phone = { nullptr }; object_ptr> _error = { nullptr }; @@ -112,7 +114,7 @@ private: void submit(); void sendCall(); void updateCall(); - bool sendCodeFail(const RPCError &error); + void sendCodeFail(const RPCError &error); void showError(const QString &text); void hideError() { showError(QString()); @@ -120,6 +122,7 @@ private: int countHeight(); const not_null _session; + MTP::Sender _api; QString _phone; QString _hash; @@ -136,7 +139,8 @@ private: ChangePhoneBox::EnterPhone::EnterPhone( QWidget*, not_null session) -: _session(session) { +: _session(session) +, _api(session->mtp()) { } void ChangePhoneBox::EnterPhone::prepare() { @@ -171,20 +175,19 @@ void ChangePhoneBox::EnterPhone::submit() { hideError(); auto phoneNumber = _phone->getLastText().trimmed(); - _requestId = MTP::send( - MTPaccount_SendChangePhoneCode( - MTP_string(phoneNumber), - MTP_codeSettings(MTP_flags(0))), - rpcDone(crl::guard(this, [=]( - const MTPauth_SentCode &result) { - return sendPhoneDone(phoneNumber, result); - })), rpcFail(crl::guard(this, [=]( - const RPCError &error) { - return sendPhoneFail(phoneNumber, error); - }))); + _requestId = _api.request(MTPaccount_SendChangePhoneCode( + MTP_string(phoneNumber), + MTP_codeSettings(MTP_flags(0)) + )).done([=](const MTPauth_SentCode &result) { + sendPhoneDone(result, phoneNumber); + }).fail([=](const RPCError &error) { + sendPhoneFail(error, phoneNumber); + }).handleFloodErrors().send(); } -void ChangePhoneBox::EnterPhone::sendPhoneDone(const QString &phoneNumber, const MTPauth_SentCode &result) { +void ChangePhoneBox::EnterPhone::sendPhoneDone( + const MTPauth_SentCode &result, + const QString &phoneNumber) { Expects(result.type() == mtpc_auth_sentCode); _requestId = 0; @@ -219,18 +222,14 @@ void ChangePhoneBox::EnterPhone::sendPhoneDone(const QString &phoneNumber, const Ui::LayerOption::KeepOther); } -bool ChangePhoneBox::EnterPhone::sendPhoneFail(const QString &phoneNumber, const RPCError &error) { - auto errorText = Lang::Hard::ServerError(); +void ChangePhoneBox::EnterPhone::sendPhoneFail(const RPCError &error, const QString &phoneNumber) { + _requestId = 0; if (MTP::isFloodError(error)) { - errorText = tr::lng_flood_error(tr::now); - } else if (MTP::isDefaultHandledError(error)) { - return false; + showError(tr::lng_flood_error(tr::now)); } else if (error.type() == qstr("PHONE_NUMBER_INVALID")) { - errorText = tr::lng_bad_phone(tr::now); + showError(tr::lng_bad_phone(tr::now)); } else if (error.type() == qstr("PHONE_NUMBER_BANNED")) { ShowPhoneBannedError(phoneNumber); - _requestId = 0; - return true; } else if (error.type() == qstr("PHONE_NUMBER_OCCUPIED")) { Ui::show(Box( tr::lng_change_phone_occupied( @@ -238,12 +237,9 @@ bool ChangePhoneBox::EnterPhone::sendPhoneFail(const QString &phoneNumber, const lt_phone, App::formatPhone(phoneNumber)), tr::lng_box_ok(tr::now))); - _requestId = 0; - return true; + } else { + showError(Lang::Hard::ServerError()); } - showError(errorText); - _requestId = 0; - return true; } void ChangePhoneBox::EnterPhone::showError(const QString &text) { @@ -261,6 +257,7 @@ ChangePhoneBox::EnterCode::EnterCode( int codeLength, int callTimeout) : _session(session) +, _api(session->mtp()) , _phone(phone) , _hash(hash) , _codeLength(codeLength) @@ -313,25 +310,28 @@ void ChangePhoneBox::EnterCode::submit() { const auto session = _session; const auto code = _code->getDigitsOnly(); const auto weak = Ui::MakeWeak(this); - _requestId = MTP::send(MTPaccount_ChangePhone( + _requestId = session->api().request(MTPaccount_ChangePhone( MTP_string(_phone), MTP_string(_hash), MTP_string(code) - ), rpcDone([=](const MTPUser &result) { + )).done([=](const MTPUser &result) { session->data().processUser(result); if (weak) { Ui::hideLayer(); } Ui::Toast::Show(tr::lng_change_phone_success(tr::now)); - }), rpcFail(crl::guard(this, [this](const RPCError &error) { - return sendCodeFail(error); - }))); + }).fail(crl::guard(this, [=](const RPCError &error) { + sendCodeFail(error); + })).handleFloodErrors().send(); } void ChangePhoneBox::EnterCode::sendCall() { - MTP::send(MTPauth_ResendCode(MTP_string(_phone), MTP_string(_hash)), rpcDone(crl::guard(this, [this] { + _api.request(MTPauth_ResendCode( + MTP_string(_phone), + MTP_string(_hash) + )).done([=](const MTPauth_SentCode &result) { _call.callDone(); - }))); + }).send(); } void ChangePhoneBox::EnterCode::updateCall() { @@ -354,25 +354,20 @@ void ChangePhoneBox::EnterCode::showError(const QString &text) { } } -bool ChangePhoneBox::EnterCode::sendCodeFail(const RPCError &error) { - auto errorText = Lang::Hard::ServerError(); +void ChangePhoneBox::EnterCode::sendCodeFail(const RPCError &error) { + _requestId = 0; if (MTP::isFloodError(error)) { - errorText = tr::lng_flood_error(tr::now); - } else if (MTP::isDefaultHandledError(error)) { - return false; + showError(tr::lng_flood_error(tr::now)); } else if (error.type() == qstr("PHONE_CODE_EMPTY") || error.type() == qstr("PHONE_CODE_INVALID")) { - errorText = tr::lng_bad_code(tr::now); + showError(tr::lng_bad_code(tr::now)); } else if (error.type() == qstr("PHONE_CODE_EXPIRED") || error.type() == qstr("PHONE_NUMBER_BANNED")) { closeBox(); // Go back to phone input. - _requestId = 0; - return true; } else if (error.type() == qstr("PHONE_NUMBER_INVALID")) { - errorText = tr::lng_bad_phone(tr::now); + showError(tr::lng_bad_phone(tr::now)); + } else { + showError(Lang::Hard::ServerError()); } - _requestId = 0; - showError(errorText); - return true; } ChangePhoneBox::ChangePhoneBox(QWidget*, not_null session) diff --git a/Telegram/SourceFiles/boxes/confirm_box.cpp b/Telegram/SourceFiles/boxes/confirm_box.cpp index 4f346f633..61270a514 100644 --- a/Telegram/SourceFiles/boxes/confirm_box.cpp +++ b/Telegram/SourceFiles/boxes/confirm_box.cpp @@ -432,6 +432,7 @@ PinMessageBox::PinMessageBox( not_null peer, MsgId msgId) : _peer(peer) +, _api(peer->session().mtp()) , _msgId(msgId) , _text(this, tr::lng_pinned_pin_sure(tr::now), st::boxLabel) { } @@ -474,24 +475,16 @@ void PinMessageBox::pinMessage() { if (_notify && !_notify->checked()) { flags |= MTPmessages_UpdatePinnedMessage::Flag::f_silent; } - _requestId = MTP::send( - MTPmessages_UpdatePinnedMessage( - MTP_flags(flags), - _peer->input, - MTP_int(_msgId)), - rpcDone(&PinMessageBox::pinDone), - rpcFail(&PinMessageBox::pinFail)); -} - -void PinMessageBox::pinDone(const MTPUpdates &updates) { - _peer->session().api().applyUpdates(updates); - Ui::hideLayer(); -} - -bool PinMessageBox::pinFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - Ui::hideLayer(); - return true; + _requestId = _api.request(MTPmessages_UpdatePinnedMessage( + MTP_flags(flags), + _peer->input, + MTP_int(_msgId) + )).done([=](const MTPUpdates &result) { + _peer->session().api().applyUpdates(result); + Ui::hideLayer(); + }).fail([=](const RPCError &error) { + Ui::hideLayer(); + }).send(); } DeleteMessagesBox::DeleteMessagesBox( @@ -847,8 +840,8 @@ void DeleteMessagesBox::deleteAndClear() { peer->session().api().request(MTPmessages_DeleteScheduledMessages( peer->input, MTP_vector(ids) - )).done([=, peer=peer](const MTPUpdates &updates) { - peer->session().api().applyUpdates(updates); + )).done([peer=peer](const MTPUpdates &result) { + peer->session().api().applyUpdates(result); }).send(); } diff --git a/Telegram/SourceFiles/boxes/confirm_box.h b/Telegram/SourceFiles/boxes/confirm_box.h index db7ac9e7d..91a0e0b20 100644 --- a/Telegram/SourceFiles/boxes/confirm_box.h +++ b/Telegram/SourceFiles/boxes/confirm_box.h @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once #include "boxes/abstract_box.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" namespace Data { class PhotoMedia; @@ -129,7 +129,7 @@ private: }; -class PinMessageBox : public Ui::BoxContent, public RPCSender { +class PinMessageBox final : public Ui::BoxContent { public: PinMessageBox(QWidget*, not_null peer, MsgId msgId); @@ -141,10 +141,9 @@ protected: private: void pinMessage(); - void pinDone(const MTPUpdates &updates); - bool pinFail(const RPCError &error); - not_null _peer; + const not_null _peer; + MTP::Sender _api; MsgId _msgId; object_ptr _text; @@ -154,7 +153,7 @@ private: }; -class DeleteMessagesBox : public Ui::BoxContent, public RPCSender { +class DeleteMessagesBox final : public Ui::BoxContent { public: DeleteMessagesBox( QWidget*, @@ -207,9 +206,8 @@ private: }; -class ConfirmInviteBox +class ConfirmInviteBox final : public Ui::BoxContent - , public RPCSender , private base::Subscriber { public: ConfirmInviteBox( diff --git a/Telegram/SourceFiles/boxes/confirm_phone_box.cpp b/Telegram/SourceFiles/boxes/confirm_phone_box.cpp index 6cd1a62e2..336a9aca9 100644 --- a/Telegram/SourceFiles/boxes/confirm_phone_box.cpp +++ b/Telegram/SourceFiles/boxes/confirm_phone_box.cpp @@ -15,6 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/click_handler_types.h" // UrlClickHandler #include "base/qthelp_url.h" // qthelp::url_encode #include "base/platform/base_platform_info.h" +#include "main/main_session.h" #include "mainwidget.h" #include "numbers.h" #include "app.h" @@ -203,36 +204,54 @@ QString SentCodeCall::getText() const { return QString(); } -void ConfirmPhoneBox::start(const QString &phone, const QString &hash) { - if (CurrentConfirmPhoneBox && CurrentConfirmPhoneBox->getPhone() != phone) { +void ConfirmPhoneBox::Start( + not_null session, + const QString &phone, + const QString &hash) { + if (CurrentConfirmPhoneBox + && (CurrentConfirmPhoneBox->getPhone() != phone + || &CurrentConfirmPhoneBox->session() != session)) { CurrentConfirmPhoneBox.destroyDelayed(); } if (!CurrentConfirmPhoneBox) { - CurrentConfirmPhoneBox = Box(phone, hash); + CurrentConfirmPhoneBox = Box(session, phone, hash); } CurrentConfirmPhoneBox->checkPhoneAndHash(); } -ConfirmPhoneBox::ConfirmPhoneBox(QWidget*, const QString &phone, const QString &hash) -: _phone(phone) +ConfirmPhoneBox::ConfirmPhoneBox( + QWidget*, + not_null session, + const QString &phone, + const QString &hash) +: _session(session) +, _api(session->mtp()) +, _phone(phone) , _hash(hash) , _call([this] { sendCall(); }, [this] { update(); }) { } void ConfirmPhoneBox::sendCall() { - MTP::send(MTPauth_ResendCode(MTP_string(_phone), MTP_string(_phoneHash)), rpcDone(&ConfirmPhoneBox::callDone)); + _api.request(MTPauth_ResendCode( + MTP_string(_phone), + MTP_string(_phoneHash) + )).done([=](const MTPauth_SentCode &result) { + callDone(result); + }).send(); } void ConfirmPhoneBox::checkPhoneAndHash() { if (_sendCodeRequestId) { return; } - _sendCodeRequestId = MTP::send( - MTPaccount_SendConfirmPhoneCode( - MTP_string(_hash), - MTP_codeSettings(MTP_flags(0))), - rpcDone(&ConfirmPhoneBox::sendCodeDone), - rpcFail(&ConfirmPhoneBox::sendCodeFail)); + _sendCodeRequestId = _api.request(MTPaccount_SendConfirmPhoneCode( + MTP_string(_hash), + MTP_codeSettings(MTP_flags(0)) + )).done([=](const MTPauth_SentCode &result) { + sendCodeDone(result); + }).fail([=](const RPCError &error) { + sendCodeFail(error); + }).handleFloodErrors().send(); } void ConfirmPhoneBox::sendCodeDone(const MTPauth_SentCode &result) { @@ -259,12 +278,10 @@ void ConfirmPhoneBox::sendCodeDone(const MTPauth_SentCode &result) { }); } -bool ConfirmPhoneBox::sendCodeFail(const RPCError &error) { +void ConfirmPhoneBox::sendCodeFail(const RPCError &error) { auto errorText = Lang::Hard::ServerError(); if (MTP::isFloodError(error)) { errorText = tr::lng_flood_error(tr::now); - } else if (MTP::isDefaultHandledError(error)) { - return false; } else if (error.code() == 400) { errorText = tr::lng_confirm_phone_link_invalid(tr::now); } @@ -275,7 +292,6 @@ bool ConfirmPhoneBox::sendCodeFail(const RPCError &error) { } else { deleteLater(); } - return true; } void ConfirmPhoneBox::launch() { @@ -327,10 +343,14 @@ void ConfirmPhoneBox::sendCode() { showError(QString()); - _sendCodeRequestId = MTP::send( - MTPaccount_ConfirmPhone(MTP_string(_phoneHash), MTP_string(code)), - rpcDone(&ConfirmPhoneBox::confirmDone), - rpcFail(&ConfirmPhoneBox::confirmFail)); + _sendCodeRequestId = _api.request(MTPaccount_ConfirmPhone( + MTP_string(_phoneHash), + MTP_string(code) + )).done([=](const MTPBool &result) { + confirmDone(result); + }).fail([=](const RPCError &error) { + confirmFail(error); + }).handleFloodErrors().send(); } void ConfirmPhoneBox::confirmDone(const MTPBool &result) { @@ -338,12 +358,10 @@ void ConfirmPhoneBox::confirmDone(const MTPBool &result) { Ui::show(Box(tr::lng_confirm_phone_success(tr::now, lt_phone, App::formatPhone(_phone)))); } -bool ConfirmPhoneBox::confirmFail(const RPCError &error) { +void ConfirmPhoneBox::confirmFail(const RPCError &error) { auto errorText = Lang::Hard::ServerError(); if (MTP::isFloodError(error)) { errorText = tr::lng_flood_error(tr::now); - } else if (MTP::isDefaultHandledError(error)) { - return false; } else { auto &errorType = error.type(); if (errorType == qstr("PHONE_CODE_EMPTY") || errorType == qstr("PHONE_CODE_INVALID")) { @@ -354,7 +372,6 @@ bool ConfirmPhoneBox::confirmFail(const RPCError &error) { _code->setDisabled(false); _code->setFocus(); showError(errorText); - return true; } void ConfirmPhoneBox::showError(const QString &error) { @@ -406,9 +423,3 @@ void ConfirmPhoneBox::resizeEvent(QResizeEvent *e) { void ConfirmPhoneBox::setInnerFocus() { _code->setFocusFast(); } - -ConfirmPhoneBox::~ConfirmPhoneBox() { - if (_sendCodeRequestId) { - MTP::cancel(_sendCodeRequestId); - } -} diff --git a/Telegram/SourceFiles/boxes/confirm_phone_box.h b/Telegram/SourceFiles/boxes/confirm_phone_box.h index 398b8062f..735b137cb 100644 --- a/Telegram/SourceFiles/boxes/confirm_phone_box.h +++ b/Telegram/SourceFiles/boxes/confirm_phone_box.h @@ -10,13 +10,17 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/abstract_box.h" #include "base/timer.h" #include "ui/widgets/input_fields.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" namespace Ui { class InputField; class FlatLabel; } // namespace Ui +namespace Main { +class Session; +} // namespace Main + void ShowPhoneBannedError(const QString &phone); [[nodiscard]] QString ExtractPhonePrefix(const QString &phone); @@ -86,11 +90,16 @@ private: }; -class ConfirmPhoneBox : public Ui::BoxContent, public RPCSender { +class ConfirmPhoneBox final : public Ui::BoxContent { public: - static void start(const QString &phone, const QString &hash); + static void Start( + not_null session, + const QString &phone, + const QString &hash); - ~ConfirmPhoneBox(); + [[nodiscard]] Main::Session &session() const { + return *_session; + } protected: void prepare() override; @@ -100,7 +109,11 @@ protected: void resizeEvent(QResizeEvent *e) override; private: - ConfirmPhoneBox(QWidget*, const QString &phone, const QString &hash); + ConfirmPhoneBox( + QWidget*, + not_null session, + const QString &phone, + const QString &hash); friend class object_ptr; void sendCode(); @@ -108,12 +121,12 @@ private: void checkPhoneAndHash(); void sendCodeDone(const MTPauth_SentCode &result); - bool sendCodeFail(const RPCError &error); + void sendCodeFail(const RPCError &error); void callDone(const MTPauth_SentCode &result); void confirmDone(const MTPBool &result); - bool confirmFail(const RPCError &error); + void confirmFail(const RPCError &error); QString getPhone() const { return _phone; @@ -122,6 +135,8 @@ private: void showError(const QString &error); + const not_null _session; + MTP::Sender _api; mtpRequestId _sendCodeRequestId = 0; // _hash from the link for account.sendConfirmPhoneCode call. diff --git a/Telegram/SourceFiles/boxes/connection_box.cpp b/Telegram/SourceFiles/boxes/connection_box.cpp index 68130f4e5..eff5032e0 100644 --- a/Telegram/SourceFiles/boxes/connection_box.cpp +++ b/Telegram/SourceFiles/boxes/connection_box.cpp @@ -1376,7 +1376,9 @@ void ProxiesBoxController::setTryIPv6(bool enabled) { return; } Global::SetTryIPv6(enabled); - MTP::restart(); + if (const auto mtproto = _account->mtp()) { + mtproto->restart(); + } Global::RefConnectionTypeChanged().notify(); saveDelayed(); } @@ -1408,7 +1410,8 @@ void ProxiesBoxController::updateView(const Item &item) { if (!selected || (Global::ProxySettings() != ProxyData::Settings::Enabled)) { return item.state; - } else if (MTP::dcstate() == MTP::ConnectedState) { + } else if (_account->mtp() + && _account->mtp()->dcstate() == MTP::ConnectedState) { return ItemState::Online; } return ItemState::Connecting; diff --git a/Telegram/SourceFiles/boxes/edit_caption_box.cpp b/Telegram/SourceFiles/boxes/edit_caption_box.cpp index 461213e5e..df5b732c8 100644 --- a/Telegram/SourceFiles/boxes/edit_caption_box.cpp +++ b/Telegram/SourceFiles/boxes/edit_caption_box.cpp @@ -45,6 +45,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/text_options.h" #include "window/window_session_controller.h" #include "confirm_box.h" +#include "apiwrap.h" #include "facades.h" #include "app.h" #include "styles/style_layers.h" @@ -66,6 +67,7 @@ EditCaptionBox::EditCaptionBox( not_null controller, not_null item) : _controller(controller) +, _api(controller->session().mtp()) , _msgId(item->fullId()) { Expects(item->media() != nullptr); Expects(item->media()->allowsEditCaption()); @@ -963,18 +965,20 @@ void EditCaptionBox::save() { return; } - _saveRequestId = MTP::send( - MTPmessages_EditMessage( - MTP_flags(flags), - item->history()->peer->input, - MTP_int(item->id), - MTP_string(sending.text), - MTPInputMedia(), - MTPReplyMarkup(), - sentEntities, - MTP_int(0)), // schedule_date - rpcDone(&EditCaptionBox::saveDone), - rpcFail(&EditCaptionBox::saveFail)); + _saveRequestId = _api.request(MTPmessages_EditMessage( + MTP_flags(flags), + item->history()->peer->input, + MTP_int(item->id), + MTP_string(sending.text), + MTPInputMedia(), + MTPReplyMarkup(), + sentEntities, + MTP_int(0) + )).done([=](const MTPUpdates &result) { + saveDone(result); + }).fail([=](const RPCError &error) { + saveFail(error); + }).send(); } void EditCaptionBox::saveDone(const MTPUpdates &updates) { @@ -984,26 +988,24 @@ void EditCaptionBox::saveDone(const MTPUpdates &updates) { controller->session().api().applyUpdates(updates); } -bool EditCaptionBox::saveFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void EditCaptionBox::saveFail(const RPCError &error) { _saveRequestId = 0; const auto &type = error.type(); if (type == qstr("MESSAGE_ID_INVALID") || type == qstr("CHAT_ADMIN_REQUIRED") || type == qstr("MESSAGE_EDIT_TIME_EXPIRED")) { _error = tr::lng_edit_error(tr::now); + update(); } else if (type == qstr("MESSAGE_NOT_MODIFIED")) { closeBox(); - return true; } else if (type == qstr("MESSAGE_EMPTY")) { _field->setFocus(); _field->showError(); + update(); } else { _error = tr::lng_edit_error(tr::now); + update(); } - update(); - return true; } void EditCaptionBox::setName(QString nameString, qint64 size) { diff --git a/Telegram/SourceFiles/boxes/edit_caption_box.h b/Telegram/SourceFiles/boxes/edit_caption_box.h index a786377fd..61e2eb72a 100644 --- a/Telegram/SourceFiles/boxes/edit_caption_box.h +++ b/Telegram/SourceFiles/boxes/edit_caption_box.h @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/abstract_box.h" #include "storage/storage_media_prepare.h" #include "ui/wrap/slide_wrap.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" class Image; @@ -49,10 +49,7 @@ struct Information; } // namespace Streaming } // namespace Media -class EditCaptionBox - : public Ui::BoxContent - , public RPCSender - , private base::Subscriber { +class EditCaptionBox final : public Ui::BoxContent, private base::Subscriber { public: EditCaptionBox( QWidget*, @@ -87,7 +84,7 @@ private: void captionResized(); void saveDone(const MTPUpdates &updates); - bool saveFail(const RPCError &error); + void saveFail(const RPCError &error); void setName(QString nameString, qint64 size); bool fileFromClipboard(not_null data); @@ -104,7 +101,9 @@ private: : _preparedList.files.front().path; } - not_null _controller; + const not_null _controller; + MTP::Sender _api; + FullMsgId _msgId; std::shared_ptr _photoMedia; std::shared_ptr _documentMedia; diff --git a/Telegram/SourceFiles/boxes/passcode_box.cpp b/Telegram/SourceFiles/boxes/passcode_box.cpp index 85a5e3bc8..804a67c10 100644 --- a/Telegram/SourceFiles/boxes/passcode_box.cpp +++ b/Telegram/SourceFiles/boxes/passcode_box.cpp @@ -49,7 +49,7 @@ PasscodeBox::PasscodeBox( not_null session, bool turningOff) : _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _turningOff(turningOff) , _about(st::boxWidth - st::boxPadding.left() * 1.5) , _oldPasscode(this, st::defaultInputField, tr::lng_passcode_enter_old()) @@ -65,7 +65,7 @@ PasscodeBox::PasscodeBox( not_null session, const CloudFields &fields) : _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _turningOff(fields.turningOff) , _cloudPwd(true) , _cloudFields(fields) @@ -684,7 +684,7 @@ void PasscodeBox::setNewCloudPassword(const QString &newPassword) { setPasswordDone(newPasswordBytes); }).fail([=](const RPCError &error) { setPasswordFail(newPasswordBytes, email, error); - }).send(); + }).handleFloodErrors().send(); } void PasscodeBox::changeCloudPassword( @@ -737,9 +737,9 @@ void PasscodeBox::changeCloudPassword( sendChangeCloudPassword(check, newPassword, secureSecret); }); } - }).handleFloodErrors().fail([=](const RPCError &error) { + }).fail([=](const RPCError &error) { setPasswordFail(error); - }).send(); + }).handleFloodErrors().send(); } void PasscodeBox::suggestSecretReset(const QString &newPassword) { @@ -832,9 +832,9 @@ void PasscodeBox::sendChangeCloudPassword( MTP_long(newSecureSecretId))) )).done([=](const MTPBool &result) { setPasswordDone(newPasswordBytes); - }).handleFloodErrors().fail([=](const RPCError &error) { + }).fail([=](const RPCError &error) { setPasswordFail(newPasswordBytes, QString(), error); - }).send(); + }).handleFloodErrors().send(); } void PasscodeBox::badOldPasscode() { @@ -896,6 +896,7 @@ void PasscodeBox::recover() { if (_pattern == "-") return; const auto box = getDelegate()->show(Box( + _session, _pattern, _cloudFields.notEmptyPassport)); @@ -924,9 +925,11 @@ void PasscodeBox::recoverStartFail(const RPCError &error) { RecoverBox::RecoverBox( QWidget*, + not_null session, const QString &pattern, bool notEmptyPassport) -: _pattern(st::normalFont->elided(tr::lng_signin_recover_hint(tr::now, lt_recover_email, pattern), st::boxWidth - st::boxPadding.left() * 1.5)) +: _api(session->mtp()) +, _pattern(st::normalFont->elided(tr::lng_signin_recover_hint(tr::now, lt_recover_email, pattern), st::boxWidth - st::boxPadding.left() * 1.5)) , _notEmptyPassport(notEmptyPassport) , _recoverCode(this, st::defaultInputField, tr::lng_signin_code()) { } @@ -989,10 +992,13 @@ void RecoverBox::submit() { } const auto send = crl::guard(this, [=] { - _submitRequest = MTP::send( - MTPauth_RecoverPassword(MTP_string(code)), - rpcDone(&RecoverBox::codeSubmitDone, true), - rpcFail(&RecoverBox::codeSubmitFail)); + _submitRequest = _api.request(MTPauth_RecoverPassword( + MTP_string(code) + )).done([=](const MTPauth_Authorization &result) { + codeSubmitDone(result); + }).fail([=](const RPCError &error) { + codeSubmitFail(error); + }).handleFloodErrors().send(); }); if (_notEmptyPassport) { const auto box = std::make_shared>(); @@ -1016,9 +1022,7 @@ void RecoverBox::codeChanged() { update(); } -void RecoverBox::codeSubmitDone( - bool recover, - const MTPauth_Authorization &result) { +void RecoverBox::codeSubmitDone(const MTPauth_Authorization &result) { _submitRequest = 0; _passwordCleared.fire({}); @@ -1027,16 +1031,14 @@ void RecoverBox::codeSubmitDone( Ui::LayerOption::CloseOther); } -bool RecoverBox::codeSubmitFail(const RPCError &error) { +void RecoverBox::codeSubmitFail(const RPCError &error) { if (MTP::isFloodError(error)) { _submitRequest = 0; _error = tr::lng_flood_error(tr::now); update(); _recoverCode->showError(); - return true; + return; } - if (MTP::isDefaultHandledError(error)) return false; - _submitRequest = 0; const QString &err = error.type(); @@ -1045,33 +1047,31 @@ bool RecoverBox::codeSubmitFail(const RPCError &error) { getDelegate()->show( Box(tr::lng_cloud_password_removed(tr::now)), Ui::LayerOption::CloseOther); - return true; } else if (err == qstr("PASSWORD_RECOVERY_NA")) { closeBox(); - return true; } else if (err == qstr("PASSWORD_RECOVERY_EXPIRED")) { _recoveryExpired.fire({}); closeBox(); - return true; } else if (err == qstr("CODE_INVALID")) { _error = tr::lng_signin_wrong_code(tr::now); update(); _recoverCode->selectAll(); _recoverCode->setFocus(); _recoverCode->showError(); - return true; - } - if (Logs::DebugEnabled()) { // internal server error - _error = err + ": " + error.description(); } else { - _error = Lang::Hard::ServerError(); + if (Logs::DebugEnabled()) { // internal server error + _error = err + ": " + error.description(); + } else { + _error = Lang::Hard::ServerError(); + } + update(); + _recoverCode->setFocus(); } - update(); - _recoverCode->setFocus(); - return false; } -RecoveryEmailValidation ConfirmRecoveryEmail(const QString &pattern) { +RecoveryEmailValidation ConfirmRecoveryEmail( + not_null session, + const QString &pattern) { const auto errors = std::make_shared>(); const auto resent = std::make_shared>(); const auto requestId = std::make_shared(0); @@ -1083,7 +1083,9 @@ RecoveryEmailValidation ConfirmRecoveryEmail(const QString &pattern) { if (*requestId) { return; } - const auto done = [=](const MTPBool &result) { + *requestId = session->api().request(MTPaccount_ConfirmPasswordEmail( + MTP_string(code) + )).done([=](const MTPBool &result) { *requestId = 0; reloads->fire({}); if (*weak) { @@ -1091,13 +1093,7 @@ RecoveryEmailValidation ConfirmRecoveryEmail(const QString &pattern) { Box(tr::lng_cloud_password_was_set(tr::now)), Ui::LayerOption::CloseOther); } - }; - const auto fail = [=](const RPCError &error) { - const auto skip = MTP::isDefaultHandledError(error) - && !MTP::isFloodError(error); - if (skip) { - return false; - } + }).fail([=](const RPCError &error) { *requestId = 0; if (MTP::isFloodError(error)) { errors->fire(tr::lng_flood_error(tr::now)); @@ -1115,26 +1111,20 @@ RecoveryEmailValidation ConfirmRecoveryEmail(const QString &pattern) { } else { errors->fire(Lang::Hard::ServerError()); } - return true; - }; - *requestId = MTP::send( - MTPaccount_ConfirmPasswordEmail(MTP_string(code)), - rpcDone(done), - rpcFail(fail)); + }).handleFloodErrors().send(); }; const auto resend = [=] { if (*requestId) { return; } - *requestId = MTP::send(MTPaccount_ResendPasswordEmail( - ), rpcDone([=](const MTPBool &result) { + *requestId = session->api().request(MTPaccount_ResendPasswordEmail( + )).done([=](const MTPBool &result) { *requestId = 0; resent->fire(tr::lng_cloud_password_resent(tr::now)); - }), rpcFail([=](const RPCError &error) { + }).fail([=](const RPCError &error) { *requestId = 0; errors->fire(Lang::Hard::ServerError()); - return true; - })); + }).send(); }; auto box = Passport::VerifyEmailBox( diff --git a/Telegram/SourceFiles/boxes/passcode_box.h b/Telegram/SourceFiles/boxes/passcode_box.h index 03ab68f87..54d783793 100644 --- a/Telegram/SourceFiles/boxes/passcode_box.h +++ b/Telegram/SourceFiles/boxes/passcode_box.h @@ -164,9 +164,13 @@ private: }; -class RecoverBox : public Ui::BoxContent, public RPCSender { +class RecoverBox final : public Ui::BoxContent { public: - RecoverBox(QWidget*, const QString &pattern, bool notEmptyPassport); + RecoverBox( + QWidget*, + not_null session, + const QString &pattern, + bool notEmptyPassport); rpl::producer<> passwordCleared() const; rpl::producer<> recoveryExpired() const; @@ -184,9 +188,10 @@ protected: private: void submit(); void codeChanged(); - void codeSubmitDone(bool recover, const MTPauth_Authorization &result); - bool codeSubmitFail(const RPCError &error); + void codeSubmitDone(const MTPauth_Authorization &result); + void codeSubmitFail(const RPCError &error); + MTP::Sender _api; mtpRequestId _submitRequest = 0; QString _pattern; @@ -206,4 +211,6 @@ struct RecoveryEmailValidation { rpl::producer<> reloadRequests; rpl::producer<> cancelRequests; }; -RecoveryEmailValidation ConfirmRecoveryEmail(const QString &pattern); +[[nodiscard]] RecoveryEmailValidation ConfirmRecoveryEmail( + not_null session, + const QString &pattern); diff --git a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp index 34b0c8fb3..d8e07c329 100644 --- a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp +++ b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp @@ -147,7 +147,7 @@ void PeerListRowWithLink::paintAction( PeerListGlobalSearchController::PeerListGlobalSearchController( not_null navigation) : _navigation(navigation) -, _api(_navigation->session().api().instance()) { +, _api(_navigation->session().mtp()) { _timer.setCallback([this] { searchOnServer(); }); } diff --git a/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp b/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp index ff7d2c3d1..9cc8dcea5 100644 --- a/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp @@ -276,7 +276,7 @@ AddSpecialBoxController::AddSpecialBoxController( peer, &_additional)) , _peer(peer) -, _api(_peer->session().api().instance()) +, _api(_peer->session().mtp()) , _role(role) , _additional(peer, Role::Members) , _adminDoneCallback(std::move(adminDoneCallback)) @@ -830,7 +830,7 @@ AddSpecialBoxSearchController::AddSpecialBoxSearchController( not_null additional) : _peer(peer) , _additional(additional) -, _api(_peer->session().api().instance()) +, _api(_peer->session().mtp()) , _timer([=] { searchOnServer(); }) { subscribeToMigration(); } diff --git a/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp index fb1a84375..80a27e8c2 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp @@ -755,7 +755,7 @@ ParticipantsBoxController::ParticipantsBoxController( : PeerListController(CreateSearchController(peer, role, &_additional)) , _navigation(navigation) , _peer(peer) -, _api(_peer->session().api().instance()) +, _api(_peer->session().mtp()) , _role(role) , _additional(peer, _role) { subscribeToMigration(); @@ -1928,7 +1928,7 @@ ParticipantsBoxSearchController::ParticipantsBoxSearchController( : _channel(channel) , _role(role) , _additional(additional) -, _api(_channel->session().api().instance()) { +, _api(_channel->session().mtp()) { _timer.setCallback([=] { searchOnServer(); }); } diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp index 08f82b88b..03ec4c4a3 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp @@ -356,7 +356,7 @@ Controller::Controller( : _navigation(navigation) , _box(box) , _peer(peer) -, _api(_peer->session().api().instance()) +, _api(_peer->session().mtp()) , _isGroup(_peer->isChat() || _peer->isMegagroup()) { _box->setTitle(_isGroup ? tr::lng_edit_group() diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_type_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_type_box.cpp index 71ee082ca..5f2a891d8 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_peer_type_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_peer_type_box.cpp @@ -168,7 +168,7 @@ Controller::Controller( std::optional privacySavedValue, std::optional usernameSavedValue) : _peer(peer) -, _api(_peer->session().api().instance()) +, _api(_peer->session().mtp()) , _privacySavedValue(privacySavedValue) , _usernameSavedValue(usernameSavedValue) , _useLocationPhrases(useLocationPhrases) diff --git a/Telegram/SourceFiles/boxes/rate_call_box.cpp b/Telegram/SourceFiles/boxes/rate_call_box.cpp index e1c97e6e8..aa6e72b2c 100644 --- a/Telegram/SourceFiles/boxes/rate_call_box.cpp +++ b/Telegram/SourceFiles/boxes/rate_call_box.cpp @@ -31,7 +31,7 @@ RateCallBox::RateCallBox( uint64 callId, uint64 callAccessHash) : _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _callId(callId) , _callAccessHash(callAccessHash) { } diff --git a/Telegram/SourceFiles/boxes/report_box.cpp b/Telegram/SourceFiles/boxes/report_box.cpp index ff95cc5aa..a55ab4835 100644 --- a/Telegram/SourceFiles/boxes/report_box.cpp +++ b/Telegram/SourceFiles/boxes/report_box.cpp @@ -15,7 +15,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" #include "ui/toast/toast.h" -#include "mtproto/facade.h" #include "mainwindow.h" #include "styles/style_layers.h" #include "styles/style_boxes.h" @@ -28,11 +27,13 @@ constexpr auto kReportReasonLengthMax = 200; } // namespace ReportBox::ReportBox(QWidget*, not_null peer) -: _peer(peer) { +: _peer(peer) +, _api(_peer->session().mtp()) { } ReportBox::ReportBox(QWidget*, not_null peer, MessageIdsList ids) : _peer(peer) +, _api(_peer->session().mtp()) , _ids(std::move(ids)) { } @@ -137,7 +138,9 @@ void ReportBox::reasonResized() { } void ReportBox::report() { - if (_requestId) return; + if (_requestId) { + return; + } if (_reasonOtherText && _reasonOtherText->getLastText().trimmed().isEmpty()) { _reasonOtherText->showError(); @@ -159,18 +162,24 @@ void ReportBox::report() { for (const auto &fullId : *_ids) { ids.push_back(MTP_int(fullId.msg)); } - _requestId = MTP::send( - MTPmessages_Report( - _peer->input, - MTP_vector(ids), - reason), - rpcDone(&ReportBox::reportDone), - rpcFail(&ReportBox::reportFail)); + _requestId = _api.request(MTPmessages_Report( + _peer->input, + MTP_vector(ids), + reason + )).done([=](const MTPBool &result) { + reportDone(result); + }).fail([=](const RPCError &error) { + reportFail(error); + }).send(); } else { - _requestId = MTP::send( - MTPaccount_ReportPeer(_peer->input, reason), - rpcDone(&ReportBox::reportDone), - rpcFail(&ReportBox::reportFail)); + _requestId = _api.request(MTPaccount_ReportPeer( + _peer->input, + reason + )).done([=](const MTPBool &result) { + reportDone(result); + }).fail([=](const RPCError &error) { + reportFail(error); + }).send(); } } @@ -180,16 +189,11 @@ void ReportBox::reportDone(const MTPBool &result) { closeBox(); } -bool ReportBox::reportFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) { - return false; - } - +void ReportBox::reportFail(const RPCError &error) { _requestId = 0; if (_reasonOtherText) { _reasonOtherText->showError(); } - return true; } void ReportBox::updateMaxHeight() { diff --git a/Telegram/SourceFiles/boxes/report_box.h b/Telegram/SourceFiles/boxes/report_box.h index 05782b8ce..238ebfe3c 100644 --- a/Telegram/SourceFiles/boxes/report_box.h +++ b/Telegram/SourceFiles/boxes/report_box.h @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once #include "boxes/abstract_box.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" namespace Ui { template @@ -18,7 +18,7 @@ class Radioenum; class InputField; } // namespace Ui -class ReportBox : public Ui::BoxContent, public RPCSender { +class ReportBox final : public Ui::BoxContent { public: ReportBox(QWidget*, not_null peer); ReportBox(QWidget*, not_null peer, MessageIdsList ids); @@ -43,9 +43,10 @@ private: void report(); void reportDone(const MTPBool &result); - bool reportFail(const RPCError &error); + void reportFail(const RPCError &error); - not_null _peer; + const not_null _peer; + MTP::Sender _api; std::optional _ids; std::shared_ptr> _reasonGroup; diff --git a/Telegram/SourceFiles/boxes/sessions_box.cpp b/Telegram/SourceFiles/boxes/sessions_box.cpp index 071058b17..ff494213b 100644 --- a/Telegram/SourceFiles/boxes/sessions_box.cpp +++ b/Telegram/SourceFiles/boxes/sessions_box.cpp @@ -11,7 +11,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "mainwidget.h" #include "mainwindow.h" -#include "apiwrap.h" #include "main/main_session.h" #include "data/data_session.h" #include "base/unixtime.h" @@ -78,7 +77,7 @@ private: SessionsBox::SessionsBox(QWidget*, not_null session) : _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _shortPollTimer([=] { shortPollSessions(); }) { } diff --git a/Telegram/SourceFiles/boxes/share_box.cpp b/Telegram/SourceFiles/boxes/share_box.cpp index b0bba83ec..a2a223be9 100644 --- a/Telegram/SourceFiles/boxes/share_box.cpp +++ b/Telegram/SourceFiles/boxes/share_box.cpp @@ -41,10 +41,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "styles/style_boxes.h" #include "styles/style_history.h" -class ShareBox::Inner - : public Ui::RpWidget - , public RPCSender - , private base::Subscriber { +class ShareBox::Inner final : public Ui::RpWidget, private base::Subscriber { public: Inner( QWidget *parent, @@ -163,6 +160,7 @@ ShareBox::ShareBox( SubmitCallback &&submitCallback, FilterCallback &&filterCallback) : _navigation(navigation) +, _api(_navigation->session().mtp()) , _copyCallback(std::move(copyCallback)) , _submitCallback(std::move(submitCallback)) , _filterCallback(std::move(filterCallback)) @@ -309,18 +307,20 @@ bool ShareBox::searchByUsername(bool searchCache) { if (i != _peopleCache.cend()) { _peopleQuery = query; _peopleRequest = 0; - peopleReceived(i.value(), 0); + peopleDone(i.value(), 0); return true; } } else if (_peopleQuery != query) { _peopleQuery = query; _peopleFull = false; - _peopleRequest = MTP::send( - MTPcontacts_Search( - MTP_string(_peopleQuery), - MTP_int(SearchPeopleLimit)), - rpcDone(&ShareBox::peopleReceived), - rpcFail(&ShareBox::peopleFailed)); + _peopleRequest = _api.request(MTPcontacts_Search( + MTP_string(_peopleQuery), + MTP_int(SearchPeopleLimit) + )).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) { + peopleDone(result, requestId); + }).fail([=](const RPCError &error, mtpRequestId requestId) { + peopleFail(error, requestId); + }).send(); _peopleQueries.insert(_peopleRequest, _peopleQuery); } } @@ -333,7 +333,7 @@ void ShareBox::needSearchByUsername() { } } -void ShareBox::peopleReceived( +void ShareBox::peopleDone( const MTPcontacts_Found &result, mtpRequestId requestId) { Expects(result.type() == mtpc_contacts_found); @@ -364,14 +364,11 @@ void ShareBox::peopleReceived( } } -bool ShareBox::peopleFailed(const RPCError &error, mtpRequestId requestId) { - if (MTP::isDefaultHandledError(error)) return false; - +void ShareBox::peopleFail(const RPCError &error, mtpRequestId requestId) { if (_peopleRequest == requestId) { _peopleRequest = 0; _peopleFull = true; } - return true; } void ShareBox::setInnerFocus() { diff --git a/Telegram/SourceFiles/boxes/share_box.h b/Telegram/SourceFiles/boxes/share_box.h index b5d3f5397..14a0e0dbc 100644 --- a/Telegram/SourceFiles/boxes/share_box.h +++ b/Telegram/SourceFiles/boxes/share_box.h @@ -12,7 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/timer.h" #include "ui/effects/animations.h" #include "ui/effects/round_checkbox.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" enum class SendMenuType; @@ -53,7 +53,7 @@ void ShareGameScoreByHash( not_null session, const QString &hash); -class ShareBox : public Ui::BoxContent, public RPCSender { +class ShareBox final : public Ui::BoxContent { public: using CopyCallback = Fn; using SubmitCallback = Fn _navigation; + MTP::Sender _api; CopyCallback _copyCallback; SubmitCallback _submitCallback; diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.cpp b/Telegram/SourceFiles/boxes/sticker_set_box.cpp index 0ee09b509..b1ad4c216 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.cpp +++ b/Telegram/SourceFiles/boxes/sticker_set_box.cpp @@ -229,7 +229,7 @@ StickerSetBox::Inner::Inner( const MTPInputStickerSet &set) : RpWidget(parent) , _controller(controller) -, _api(_controller->session().api().instance()) +, _api(_controller->session().mtp()) , _input(set) , _previewTimer([=] { showPreview(); }) { set.match([&](const MTPDinputStickerSetID &data) { diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.h b/Telegram/SourceFiles/boxes/sticker_set_box.h index a051febbd..30eb10b0b 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.h +++ b/Telegram/SourceFiles/boxes/sticker_set_box.h @@ -21,7 +21,7 @@ namespace Ui { class PlainShadow; } // namespace Ui -class StickerSetBox : public Ui::BoxContent, public RPCSender { +class StickerSetBox final : public Ui::BoxContent { public: StickerSetBox( QWidget*, @@ -43,7 +43,7 @@ private: void addStickers(); void shareStickers(); - not_null _controller; + const not_null _controller; MTPInputStickerSet _set; class Inner; diff --git a/Telegram/SourceFiles/boxes/stickers_box.cpp b/Telegram/SourceFiles/boxes/stickers_box.cpp index 7f2d83a12..5638570f3 100644 --- a/Telegram/SourceFiles/boxes/stickers_box.cpp +++ b/Telegram/SourceFiles/boxes/stickers_box.cpp @@ -363,6 +363,7 @@ StickersBox::StickersBox( not_null session, Section section) : _session(session) +, _api(session->mtp()) , _tabs(this, st::stickersTabs) , _unreadBadge( this, @@ -376,6 +377,7 @@ StickersBox::StickersBox( StickersBox::StickersBox(QWidget*, not_null megagroup) : _session(&megagroup->session()) +, _api(_session->mtp()) , _section(Section::Installed) , _installed(0, this, megagroup) , _megagroupSet(megagroup) { @@ -389,6 +391,7 @@ StickersBox::StickersBox( not_null session, const MTPVector &attachedSets) : _session(session) +, _api(session->mtp()) , _section(Section::Attached) , _attached(0, this, session, Section::Attached) , _attachedSets(attachedSets) { @@ -422,8 +425,8 @@ void StickersBox::showAttachedStickers() { } void StickersBox::getArchivedDone( - uint64 offsetId, - const MTPmessages_ArchivedStickers &result) { + const MTPmessages_ArchivedStickers &result, + uint64 offsetId) { _archivedRequestId = 0; _archivedLoaded = true; if (result.type() != mtpc_messages_archivedStickers) { @@ -631,12 +634,13 @@ void StickersBox::loadMoreArchived() { } } } - _archivedRequestId = MTP::send( - MTPmessages_GetArchivedStickers( - MTP_flags(0), - MTP_long(lastId), - MTP_int(kArchivedLimitPerPage)), - rpcDone(&StickersBox::getArchivedDone, lastId)); + _archivedRequestId = _api.request(MTPmessages_GetArchivedStickers( + MTP_flags(0), + MTP_long(lastId), + MTP_int(kArchivedLimitPerPage) + )).done([=](const MTPmessages_ArchivedStickers &result) { + getArchivedDone(result, lastId); + }).send(); } void StickersBox::paintEvent(QPaintEvent *e) { @@ -759,12 +763,14 @@ void StickersBox::installSet(uint64 setId) { } if (!(set->flags & MTPDstickerSet::Flag::f_installed_date) || (set->flags & MTPDstickerSet::Flag::f_archived)) { - MTP::send( - MTPmessages_InstallStickerSet( - set->mtpInput(), - MTP_boolFalse()), - rpcDone(&StickersBox::installDone), - rpcFail(&StickersBox::installFail, setId)); + _api.request(MTPmessages_InstallStickerSet( + set->mtpInput(), + MTP_boolFalse() + )).done([=](const MTPmessages_StickerSetInstallResult &result) { + installDone(result); + }).fail([=](const RPCError &error) { + installFail(error, setId); + }).send(); _session->data().stickers().installLocally(setId); } @@ -777,24 +783,28 @@ void StickersBox::installDone(const MTPmessages_StickerSetInstallResult &result) } } -bool StickersBox::installFail(uint64 setId, const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void StickersBox::installFail(const RPCError &error, uint64 setId) { const auto &sets = _session->data().stickers().sets(); const auto it = sets.find(setId); if (it == sets.cend()) { rebuildList(); - return true; + } else { + _session->data().stickers().undoInstallLocally(setId); } - - _session->data().stickers().undoInstallLocally(setId); - return true; } void StickersBox::preloadArchivedSets() { - if (!_tabs) return; + if (!_tabs) { + return; + } if (!_archivedRequestId) { - _archivedRequestId = MTP::send(MTPmessages_GetArchivedStickers(MTP_flags(0), MTP_long(0), MTP_int(kArchivedLimitFirstRequest)), rpcDone(&StickersBox::getArchivedDone, 0ULL)); + _archivedRequestId = _api.request(MTPmessages_GetArchivedStickers( + MTP_flags(0), + MTP_long(0), + MTP_int(kArchivedLimitFirstRequest) + )).done([=](const MTPmessages_ArchivedStickers &result) { + getArchivedDone(result, 0); + }).send(); } } @@ -918,7 +928,7 @@ StickersBox::Inner::Inner( StickersBox::Section section) : RpWidget(parent) , _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _section(section) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _shiftingAnimation([=](crl::time now) { @@ -935,7 +945,7 @@ StickersBox::Inner::Inner( StickersBox::Inner::Inner(QWidget *parent, not_null megagroup) : RpWidget(parent) , _session(&megagroup->session()) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _section(StickersBox::Section::Installed) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _shiftingAnimation([=](crl::time now) { diff --git a/Telegram/SourceFiles/boxes/stickers_box.h b/Telegram/SourceFiles/boxes/stickers_box.h index 217682bc4..46977553e 100644 --- a/Telegram/SourceFiles/boxes/stickers_box.h +++ b/Telegram/SourceFiles/boxes/stickers_box.h @@ -45,10 +45,7 @@ namespace Stickers { class Set; } // namespace Stickers -class StickersBox final - : public Ui::BoxContent - , public RPCSender - , private base::Subscriber { +class StickersBox final : public Ui::BoxContent, private base::Subscriber { public: enum class Section { Installed, @@ -66,11 +63,10 @@ public: QWidget*, not_null session, const MTPVector &attachedSets); + ~StickersBox(); void setInnerFocus() override; - ~StickersBox(); - protected: void prepare() override; @@ -117,15 +113,18 @@ private: QPixmap grabContentCache(); void installDone(const MTPmessages_StickerSetInstallResult &result); - bool installFail(uint64 setId, const RPCError &error); + void installFail(const RPCError &error, uint64 setId); void preloadArchivedSets(); void requestArchivedSets(); void loadMoreArchived(); - void getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedStickers &result); + void getArchivedDone( + const MTPmessages_ArchivedStickers &result, + uint64 offsetId); void showAttachedStickers(); const not_null _session; + MTP::Sender _api; object_ptr _tabs = { nullptr }; QList
_tabIndices; diff --git a/Telegram/SourceFiles/boxes/username_box.cpp b/Telegram/SourceFiles/boxes/username_box.cpp index 8ede8e0be..d592cea8b 100644 --- a/Telegram/SourceFiles/boxes/username_box.cpp +++ b/Telegram/SourceFiles/boxes/username_box.cpp @@ -17,7 +17,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "main/main_session.h" #include "data/data_session.h" #include "data/data_user.h" -#include "mtproto/facade.h" #include "styles/style_layers.h" #include "styles/style_boxes.h" @@ -32,6 +31,7 @@ constexpr auto kMinUsernameLength = 5; UsernameBox::UsernameBox(QWidget*, not_null session) : _session(session) +, _api(_session->mtp()) , _username( this, st::defaultInputField, @@ -115,21 +115,28 @@ void UsernameBox::save() { if (_saveRequestId) return; _sentUsername = getName(); - _saveRequestId = MTP::send(MTPaccount_UpdateUsername(MTP_string(_sentUsername)), rpcDone(&UsernameBox::onUpdateDone), rpcFail(&UsernameBox::onUpdateFail)); + _saveRequestId = _api.request(MTPaccount_UpdateUsername( + MTP_string(_sentUsername) + )).done([=](const MTPUser &result) { + updateDone(result); + }).fail([=](const RPCError &error) { + updateFail(error); + }).send(); } void UsernameBox::check() { - if (_checkRequestId) { - MTP::cancel(_checkRequestId); - } + _api.request(base::take(_checkRequestId)).cancel(); + QString name = getName(); if (name.size() >= kMinUsernameLength) { _checkUsername = name; - _checkRequestId = MTP::send( - MTPaccount_CheckUsername( - MTP_string(name)), - rpcDone(&UsernameBox::onCheckDone), - rpcFail(&UsernameBox::onCheckFail)); + _checkRequestId = _api.request(MTPaccount_CheckUsername( + MTP_string(name) + )).done([=](const MTPBool &result) { + checkDone(result); + }).fail([=](const RPCError &error) { + checkFail(error); + }).send(); } } @@ -176,14 +183,12 @@ void UsernameBox::linkClick() { Ui::Toast::Show(tr::lng_username_copied(tr::now)); } -void UsernameBox::onUpdateDone(const MTPUser &user) { +void UsernameBox::updateDone(const MTPUser &user) { _session->data().processUser(user); closeBox(); } -bool UsernameBox::onUpdateFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void UsernameBox::updateFail(const RPCError &error) { _saveRequestId = 0; const auto self = _session->user(); const auto &err = error.type(); @@ -194,25 +199,22 @@ bool UsernameBox::onUpdateFail(const RPCError &error) { TextUtilities::SingleLine(self->nameOrPhone), TextUtilities::SingleLine(_sentUsername)); closeBox(); - return true; } else if (err == qstr("USERNAME_INVALID")) { _username->setFocus(); _username->showError(); _errorText = tr::lng_username_invalid(tr::now); update(); - return true; } else if (err == qstr("USERNAME_OCCUPIED") || err == qstr("USERNAMES_UNAVAILABLE")) { _username->setFocus(); _username->showError(); _errorText = tr::lng_username_occupied(tr::now); update(); - return true; + } else { + _username->setFocus(); } - _username->setFocus(); - return true; } -void UsernameBox::onCheckDone(const MTPBool &result) { +void UsernameBox::checkDone(const MTPBool &result) { _checkRequestId = 0; const auto newError = (mtpIsTrue(result) || _checkUsername == _session->user()->username) @@ -228,23 +230,19 @@ void UsernameBox::onCheckDone(const MTPBool &result) { } } -bool UsernameBox::onCheckFail(const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void UsernameBox::checkFail(const RPCError &error) { _checkRequestId = 0; QString err(error.type()); if (err == qstr("USERNAME_INVALID")) { _errorText = tr::lng_username_invalid(tr::now); update(); - return true; } else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != _session->user()->username) { _errorText = tr::lng_username_occupied(tr::now); update(); - return true; + } else { + _goodText = QString(); + _username->setFocus(); } - _goodText = QString(); - _username->setFocus(); - return true; } QString UsernameBox::getName() const { diff --git a/Telegram/SourceFiles/boxes/username_box.h b/Telegram/SourceFiles/boxes/username_box.h index 3a78c6596..10b0cb6cc 100644 --- a/Telegram/SourceFiles/boxes/username_box.h +++ b/Telegram/SourceFiles/boxes/username_box.h @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once #include "boxes/abstract_box.h" -#include "mtproto/mtproto_rpc_sender.h" +#include "mtproto/sender.h" namespace Ui { class UsernameInput; @@ -19,7 +19,7 @@ namespace Main { class Session; } // namespace Main -class UsernameBox : public Ui::BoxContent, public RPCSender { +class UsernameBox : public Ui::BoxContent { public: UsernameBox(QWidget*, not_null session); @@ -31,11 +31,11 @@ protected: void resizeEvent(QResizeEvent *e) override; private: - void onUpdateDone(const MTPUser &result); - bool onUpdateFail(const RPCError &error); + void updateDone(const MTPUser &result); + void updateFail(const RPCError &error); - void onCheckDone(const MTPBool &result); - bool onCheckFail(const RPCError &error); + void checkDone(const MTPBool &result); + void checkFail(const RPCError &error); void save(); @@ -48,6 +48,7 @@ private: void updateLinkText(); const not_null _session; + MTP::Sender _api; object_ptr _username; object_ptr _link; diff --git a/Telegram/SourceFiles/calls/calls_box_controller.cpp b/Telegram/SourceFiles/calls/calls_box_controller.cpp index 4d441067e..f6e90c4f3 100644 --- a/Telegram/SourceFiles/calls/calls_box_controller.cpp +++ b/Telegram/SourceFiles/calls/calls_box_controller.cpp @@ -21,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "data/data_media_types.h" #include "data/data_user.h" -#include "apiwrap.h" #include "facades.h" #include "app.h" @@ -218,7 +217,7 @@ void BoxController::Row::stopLastActionRipple() { BoxController::BoxController(not_null window) : _window(window) -, _api(_window->session().api().instance()) { +, _api(_window->session().mtp()) { } Main::Session &BoxController::session() const { diff --git a/Telegram/SourceFiles/calls/calls_call.cpp b/Telegram/SourceFiles/calls/calls_call.cpp index 2a2c5b8a8..25cc94531 100644 --- a/Telegram/SourceFiles/calls/calls_call.cpp +++ b/Telegram/SourceFiles/calls/calls_call.cpp @@ -96,7 +96,7 @@ Call::Call( Type type) : _delegate(delegate) , _user(user) -, _api(_user->session().api().instance()) +, _api(_user->session().mtp()) , _type(type) { _discardByTimeoutTimer.setCallback([this] { hangup(); }); diff --git a/Telegram/SourceFiles/calls/calls_instance.cpp b/Telegram/SourceFiles/calls/calls_instance.cpp index 6faaff119..4809102ae 100644 --- a/Telegram/SourceFiles/calls/calls_instance.cpp +++ b/Telegram/SourceFiles/calls/calls_instance.cpp @@ -34,7 +34,7 @@ constexpr auto kServerConfigUpdateTimeoutMs = 24 * 3600 * crl::time(1000); Instance::Instance(not_null session) : _session(session) -, _api(_session->api().instance()) { +, _api(_session->mtp()) { } void Instance::startOutgoingCall(not_null user) { diff --git a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp index c7626f32e..70d7cb756 100644 --- a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp @@ -25,7 +25,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "lang/lang_keys.h" #include "mainwindow.h" -#include "apiwrap.h" #include "window/window_session_controller.h" #include "history/view/history_view_cursor_state.h" #include "facades.h" @@ -135,7 +134,7 @@ GifsListWidget::GifsListWidget( QWidget *parent, not_null controller) : Inner(parent, controller) -, _api(controller->session().api().instance()) +, _api(controller->session().mtp()) , _section(Section::Gifs) , _updateInlineItems([=] { updateInlineItems(); }) , _previewTimer([=] { showPreview(); }) { diff --git a/Telegram/SourceFiles/chat_helpers/stickers_dice_pack.cpp b/Telegram/SourceFiles/chat_helpers/stickers_dice_pack.cpp index 30b3c7c8e..0ca837c9d 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers_dice_pack.cpp +++ b/Telegram/SourceFiles/chat_helpers/stickers_dice_pack.cpp @@ -102,6 +102,7 @@ void DicePack::tryGenerateLocalZero() { return; } auto task = FileLoadTask( + _session->mainDcId(), path, QByteArray(), nullptr, diff --git a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp index d0d48499d..4de94aaa1 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp @@ -873,7 +873,7 @@ StickersListWidget::StickersListWidget( QWidget *parent, not_null controller) : Inner(parent, controller) -, _api(controller->session().api().instance()) +, _api(controller->session().mtp()) , _section(Section::Stickers) , _megagroupSetAbout(st::columnMinimalWidthThird - st::emojiScroll.width - st::emojiPanHeaderLeft) , _addText(tr::lng_stickers_featured_add(tr::now).toUpper()) diff --git a/Telegram/SourceFiles/core/local_url_handlers.cpp b/Telegram/SourceFiles/core/local_url_handlers.cpp index a37fee555..9768c82d7 100644 --- a/Telegram/SourceFiles/core/local_url_handlers.cpp +++ b/Telegram/SourceFiles/core/local_url_handlers.cpp @@ -153,7 +153,7 @@ bool ConfirmPhone( if (phone.isEmpty() || hash.isEmpty()) { return false; } - ConfirmPhoneBox::start(phone, hash); + ConfirmPhoneBox::Start(session, phone, hash); return true; } diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index b4aaaade7..b7de383de 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -926,7 +926,9 @@ void Session::startExport(const MTPInputPeer &singlePeer) { _exportPanel->activatePanel(); return; } - _export = std::make_unique(singlePeer); + _export = std::make_unique( + session().mtp().get(), + singlePeer); _exportPanel = std::make_unique( &session(), _export.get()); @@ -2484,7 +2486,7 @@ DocumentData *Session::documentFromWeb( QByteArray(), ImageWithLocation{ .location = thumbnailLocation }, ImageWithLocation{ .location = videoThumbnailLocation }, - MTP::maindc(), + session().mainDcId(), int32(0)); // data.vsize().v result->setWebLocation(WebFileLocation( data.vurl().v, @@ -2506,7 +2508,7 @@ DocumentData *Session::documentFromWeb( QByteArray(), ImageWithLocation{ .location = thumbnailLocation }, ImageWithLocation{ .location = videoThumbnailLocation }, - MTP::maindc(), + session().mainDcId(), int32(0)); // data.vsize().v result->setContentUrl(qs(data.vurl())); return result; diff --git a/Telegram/SourceFiles/data/stickers/data_stickers.cpp b/Telegram/SourceFiles/data/stickers/data_stickers.cpp index 756e7a6a5..b6344c616 100644 --- a/Telegram/SourceFiles/data/stickers/data_stickers.cpp +++ b/Telegram/SourceFiles/data/stickers/data_stickers.cpp @@ -370,7 +370,9 @@ void Stickers::requestSetToPushFaved(not_null document) { } setIsFaved(document, std::move(list)); }; - MTP::send(MTPmessages_GetStickerSet(document->sticker()->set), rpcDone([=](const MTPmessages_StickerSet &result) { + session().api().request(MTPmessages_GetStickerSet( + document->sticker()->set + )).done([=](const MTPmessages_StickerSet &result) { Expects(result.type() == mtpc_messages_stickerSet); auto list = std::vector>(); @@ -388,14 +390,10 @@ void Stickers::requestSetToPushFaved(not_null document) { } } addAnyway(std::move(list)); - }), rpcFail([addAnyway](const RPCError &error) { - if (MTP::isDefaultHandledError(error)) { - return false; - } + }).fail([=](const RPCError &error) { // Perhaps this is a deleted sticker pack. Add anyway. addAnyway({}); - return true; - })); + }).send(); } void Stickers::setIsNotFaved(not_null document) { diff --git a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h index 93552c71e..8028bd752 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h +++ b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h @@ -13,7 +13,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/rp_widget.h" #include "base/flags.h" #include "base/object_ptr.h" -#include "mtproto/mtproto_rpc_sender.h" + +class RPCError; namespace Main { class Session; @@ -63,10 +64,7 @@ enum class WidgetState { Filtered, }; -class InnerWidget - : public Ui::RpWidget - , public RPCSender - , private base::Subscriber { +class InnerWidget final : public Ui::RpWidget, private base::Subscriber { Q_OBJECT public: diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp index 6a3f387d0..824e84c0f 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp @@ -784,7 +784,7 @@ bool Widget::onSearchMessages(bool searchCache) { auto q = _filter->getLastText().trimmed(); if (q.isEmpty() && !_searchFromUser) { cancelSearchRequest(); - MTP::cancel(base::take(_peerSearchRequest)); + session().api().request(base::take(_peerSearchRequest)).cancel(); return true; } if (searchCache) { @@ -853,33 +853,39 @@ bool Widget::onSearchMessages(bool searchCache) { return _searchRequest; }); //} else if (const auto feed = _searchInChat.feed()) { // #feed - // _searchRequest = MTP::send( - // MTPchannels_SearchFeed( - // MTP_int(feed->id()), - // MTP_string(_searchQuery), - // MTP_int(0), - // MTP_inputPeerEmpty(), - // MTP_int(0), - // MTP_int(SearchPerPage)), - // rpcDone(&Widget::searchReceived, SearchRequestType::FromStart), - // rpcFail(&Widget::searchFailed, SearchRequestType::FromStart)); + // const auto type = SearchRequestType::FromStart; + // _searchRequest = session().api().request(MTPchannels_SearchFeed( + // MTP_int(feed->id()), + // MTP_string(_searchQuery), + // MTP_int(0), + // MTP_inputPeerEmpty(), + // MTP_int(0), + // MTP_int(SearchPerPage) + // )).done([=](const MTPmessages_Messages &result) { + // searchReceived(type, result, _searchRequest); + // }).fail([=](const RPCError &error) { + // searchFailed(type, error, _searchRequest); + // }).send(); // _searchQueries.insert(_searchRequest, _searchQuery); } else { + const auto type = SearchRequestType::FromStart; const auto flags = session().settings().skipArchiveInSearch() ? MTPmessages_SearchGlobal::Flag::f_folder_id : MTPmessages_SearchGlobal::Flag(0); const auto folderId = 0; - _searchRequest = MTP::send( - MTPmessages_SearchGlobal( - MTP_flags(flags), - MTP_int(folderId), - MTP_string(_searchQuery), - MTP_int(0), - MTP_inputPeerEmpty(), - MTP_int(0), - MTP_int(SearchPerPage)), - rpcDone(&Widget::searchReceived, SearchRequestType::FromStart), - rpcFail(&Widget::searchFailed, SearchRequestType::FromStart)); + _searchRequest = session().api().request(MTPmessages_SearchGlobal( + MTP_flags(flags), + MTP_int(folderId), + MTP_string(_searchQuery), + MTP_int(0), + MTP_inputPeerEmpty(), + MTP_int(0), + MTP_int(SearchPerPage) + )).done([=](const MTPmessages_Messages &result) { + searchReceived(type, result, _searchRequest); + }).fail([=](const RPCError &error) { + searchFailed(type, error, _searchRequest); + }).send(); _searchQueries.insert(_searchRequest, _searchQuery); } } @@ -896,12 +902,14 @@ bool Widget::onSearchMessages(bool searchCache) { } else if (_peerSearchQuery != query) { _peerSearchQuery = query; _peerSearchFull = false; - _peerSearchRequest = MTP::send( - MTPcontacts_Search( - MTP_string(_peerSearchQuery), - MTP_int(SearchPeopleLimit)), - rpcDone(&Widget::peerSearchReceived), - rpcFail(&Widget::peopleFailed)); + _peerSearchRequest = session().api().request(MTPcontacts_Search( + MTP_string(_peerSearchQuery), + MTP_int(SearchPeopleLimit) + )).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) { + peerSearchReceived(result, requestId); + }).fail([=](const RPCError &error, mtpRequestId requestId) { + peopleFailed(error, requestId); + }).send(); _peerSearchQueries.insert(_peerSearchRequest, _peerSearchQuery); } } else { @@ -1016,39 +1024,49 @@ void Widget::onSearchMore() { return _searchRequest; }); //} else if (const auto feed = _searchInChat.feed()) { // #feed - // _searchRequest = MTP::send( - // MTPchannels_SearchFeed( - // MTP_int(feed->id()), - // MTP_string(_searchQuery), - // MTP_int(offsetDate), - // offsetPeer - // ? offsetPeer->input - // : MTP_inputPeerEmpty(), - // MTP_int(offsetId), - // MTP_int(SearchPerPage)), - // rpcDone(&Widget::searchReceived, offsetId ? SearchRequestType::FromOffset : SearchRequestType::FromStart), - // rpcFail(&Widget::searchFailed, offsetId ? SearchRequestType::FromOffset : SearchRequestType::FromStart)); + // const auto type = offsetId + // ? SearchRequestType::FromOffset + // : SearchRequestType::FromStart; + // _searchRequest = session().api().request(MTPchannels_SearchFeed( + // MTP_int(feed->id()), + // MTP_string(_searchQuery), + // MTP_int(offsetDate), + // offsetPeer + // ? offsetPeer->input + // : MTP_inputPeerEmpty(), + // MTP_int(offsetId), + // MTP_int(SearchPerPage)), + // )).done([=](const MTPmessages_Messages &result) { + // searchReceived(type, result, _searchRequest); + // }).fail([=](const RPCError &error) { + // searchFailed(type, error, _searchRequest); + // }).send(); // if (!offsetId) { // _searchQueries.insert(_searchRequest, _searchQuery); // } } else { + const auto type = offsetId + ? SearchRequestType::FromOffset + : SearchRequestType::FromStart; const auto flags = session().settings().skipArchiveInSearch() ? MTPmessages_SearchGlobal::Flag::f_folder_id : MTPmessages_SearchGlobal::Flag(0); const auto folderId = 0; - _searchRequest = MTP::send( - MTPmessages_SearchGlobal( - MTP_flags(flags), - MTP_int(folderId), - MTP_string(_searchQuery), - MTP_int(_searchNextRate), - offsetPeer - ? offsetPeer->input - : MTP_inputPeerEmpty(), - MTP_int(offsetId), - MTP_int(SearchPerPage)), - rpcDone(&Widget::searchReceived, offsetId ? SearchRequestType::FromOffset : SearchRequestType::FromStart), - rpcFail(&Widget::searchFailed, offsetId ? SearchRequestType::FromOffset : SearchRequestType::FromStart)); + _searchRequest = session().api().request(MTPmessages_SearchGlobal( + MTP_flags(flags), + MTP_int(folderId), + MTP_string(_searchQuery), + MTP_int(_searchNextRate), + offsetPeer + ? offsetPeer->input + : MTP_inputPeerEmpty(), + MTP_int(offsetId), + MTP_int(SearchPerPage) + )).done([=](const MTPmessages_Messages &result) { + searchReceived(type, result, _searchRequest); + }).fail([=](const RPCError &error) { + searchFailed(type, error, _searchRequest); + }).send(); if (!offsetId) { _searchQueries.insert(_searchRequest, _searchQuery); } @@ -1233,12 +1251,10 @@ void Widget::peerSearchReceived( } } -bool Widget::searchFailed( +void Widget::searchFailed( SearchRequestType type, const RPCError &error, mtpRequestId requestId) { - if (MTP::isDefaultHandledError(error)) return false; - if (_searchRequest == requestId) { _searchRequest = 0; if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) { @@ -1247,17 +1263,13 @@ bool Widget::searchFailed( _searchFull = true; } } - return true; } -bool Widget::peopleFailed(const RPCError &error, mtpRequestId req) { - if (MTP::isDefaultHandledError(error)) return false; - - if (_peerSearchRequest == req) { +void Widget::peopleFailed(const RPCError &error, mtpRequestId requestId) { + if (_peerSearchRequest == requestId) { _peerSearchRequest = 0; _peerSearchFull = true; } - return true; } void Widget::dragEnterEvent(QDragEnterEvent *e) { @@ -1726,10 +1738,7 @@ void Widget::removeDialog(Key key) { } void Widget::cancelSearchRequest() { - if (_searchRequest) { - MTP::cancel(_searchRequest); - _searchRequest = 0; - } + session().api().request(base::take(_searchRequest)).cancel(); if (_searchInHistoryRequest) { session().data().histories().cancelRequest(_searchInHistoryRequest); _searchInHistoryRequest = 0; diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.h b/Telegram/SourceFiles/dialogs/dialogs_widget.h index 918315b5e..2cd4b8412 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_widget.h +++ b/Telegram/SourceFiles/dialogs/dialogs_widget.h @@ -13,7 +13,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/scroll_area.h" #include "ui/special_buttons.h" #include "api/api_single_message_search.h" -#include "mtproto/mtproto_rpc_sender.h" + +class RPCError; namespace Main { class Session; @@ -49,7 +50,7 @@ struct ChosenRow; class InnerWidget; enum class SearchRequestType; -class Widget : public Window::AbstractSectionWidget, public RPCSender { +class Widget final : public Window::AbstractSectionWidget { Q_OBJECT public: @@ -167,8 +168,11 @@ private: void refreshLoadMoreButton(bool mayBlock, bool isBlocked); void loadMoreBlockedByDate(); - bool searchFailed(SearchRequestType type, const RPCError &error, mtpRequestId req); - bool peopleFailed(const RPCError &error, mtpRequestId req); + void searchFailed( + SearchRequestType type, + const RPCError &error, + mtpRequestId requestId); + void peopleFailed(const RPCError &error, mtpRequestId requestId); void scrollToTop(); void setupScrollUpButton(); diff --git a/Telegram/SourceFiles/export/export_api_wrap.cpp b/Telegram/SourceFiles/export/export_api_wrap.cpp index b036089cb..1476b8ccc 100644 --- a/Telegram/SourceFiles/export/export_api_wrap.cpp +++ b/Telegram/SourceFiles/export/export_api_wrap.cpp @@ -410,8 +410,8 @@ auto ApiWrap::fileRequest(const Data::FileLocation &location, int offset) { }).toDC(MTP::ShiftDcId(location.dcId, MTP::kExportMediaDcShift))); } -ApiWrap::ApiWrap(Fn)> runner) -: _mtp(std::move(runner)) +ApiWrap::ApiWrap(QPointer weak, Fn)> runner) +: _mtp(weak, std::move(runner)) , _fileCache(std::make_unique(kLocationCacheSize)) { } diff --git a/Telegram/SourceFiles/export/export_api_wrap.h b/Telegram/SourceFiles/export/export_api_wrap.h index db3457194..0644537b6 100644 --- a/Telegram/SourceFiles/export/export_api_wrap.h +++ b/Telegram/SourceFiles/export/export_api_wrap.h @@ -35,7 +35,7 @@ struct Settings; class ApiWrap { public: - explicit ApiWrap(Fn)> runner); + ApiWrap(QPointer weak, Fn)> runner); rpl::producer errors() const; rpl::producer ioErrors() const; diff --git a/Telegram/SourceFiles/export/export_controller.cpp b/Telegram/SourceFiles/export/export_controller.cpp index a9d98db16..896d017c6 100644 --- a/Telegram/SourceFiles/export/export_controller.cpp +++ b/Telegram/SourceFiles/export/export_controller.cpp @@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "export/output/export_output_abstract.h" #include "export/output/export_output_result.h" #include "export/output/export_output_stats.h" +#include "mtproto/mtp_instance.h" namespace Export { namespace { @@ -34,6 +35,7 @@ class ControllerObject { public: ControllerObject( crl::weak_on_queue weak, + QPointer mtproto, const MTPInputPeer &peer); rpl::producer state() const; @@ -131,8 +133,9 @@ private: ControllerObject::ControllerObject( crl::weak_on_queue weak, + QPointer mtproto, const MTPInputPeer &peer) -: _api(weak.runner()) +: _api(mtproto, weak.runner()) , _state(PasswordCheckState{}) { _api.errors( ) | rpl::start_with_next([=](RPCError &&error) { @@ -586,7 +589,10 @@ void ControllerObject::setFinishedState() { _stats.bytesCount() }); } -Controller::Controller(const MTPInputPeer &peer) : _wrapped(peer) { +Controller::Controller( + QPointer mtproto, + const MTPInputPeer &peer) +: _wrapped(std::move(mtproto), peer) { } rpl::producer Controller::state() const { diff --git a/Telegram/SourceFiles/export/export_controller.h b/Telegram/SourceFiles/export/export_controller.h index aa8afa9a4..89b7fd857 100644 --- a/Telegram/SourceFiles/export/export_controller.h +++ b/Telegram/SourceFiles/export/export_controller.h @@ -10,8 +10,13 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/variant.h" #include "mtproto/mtproto_rpc_sender.h" +#include #include +namespace MTP { +class Instance; +} // namespace MTP + namespace Export { class ControllerObject; @@ -112,7 +117,9 @@ using State = base::optional_variant< class Controller { public: - explicit Controller(const MTPInputPeer &peer); + Controller( + QPointer mtproto, + const MTPInputPeer &peer); rpl::producer state() const; diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp index b723d9e77..43d800cd3 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp @@ -229,7 +229,7 @@ InnerWidget::InnerWidget( , _controller(controller) , _channel(channel) , _history(channel->owner().history(channel)) -, _api(_channel->session().api().instance()) +, _api(_channel->session().mtp()) , _scrollDateCheck([=] { scrollDateCheck(); }) , _emptyText( st::historyAdminLogEmptyWidth diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index 05e964f10..5bf028576 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -1089,18 +1089,20 @@ void HistoryWidget::updateInlineBotQuery() { if (_inlineBotUsername != query.username) { _inlineBotUsername = query.username; if (_inlineBotResolveRequestId) { - MTP::cancel(_inlineBotResolveRequestId); + session().api().request(_inlineBotResolveRequestId).cancel(); _inlineBotResolveRequestId = 0; } if (query.lookingUpBot) { _inlineBot = nullptr; _inlineLookingUpBot = true; - _inlineBotResolveRequestId = MTP::send( - MTPcontacts_ResolveUsername(MTP_string(_inlineBotUsername)), - rpcDone(&HistoryWidget::inlineBotResolveDone), - rpcFail( - &HistoryWidget::inlineBotResolveFail, - _inlineBotUsername)); + const auto username = _inlineBotUsername; + _inlineBotResolveRequestId = session().api().request(MTPcontacts_ResolveUsername( + MTP_string(username) + )).done([=](const MTPcontacts_ResolvedPeer &result) { + inlineBotResolveDone(result); + }).fail([=](const RPCError &error) { + inlineBotResolveFail(error, username); + }).send(); } else { applyInlineBotQuery(query.bot, query.query); } @@ -1343,9 +1345,9 @@ void HistoryWidget::writeDrafts(Data::Draft **localDraft, Data::Draft **editDraf void HistoryWidget::cancelSendAction( not_null history, SendAction::Type type) { - auto i = _sendActionRequests.find(qMakePair(history, type)); - if (i != _sendActionRequests.cend()) { - MTP::cancel(i.value()); + const auto i = _sendActionRequests.find({ history, type }); + if (i != _sendActionRequests.end()) { + session().api().request(i->second).cancel(); _sendActionRequests.erase(i); } } @@ -1386,13 +1388,13 @@ void HistoryWidget::updateSendAction( case Type::ChooseContact: action = MTP_sendMessageChooseContactAction(); break; case Type::PlayGame: action = MTP_sendMessageGamePlayAction(); break; } - const auto key = qMakePair(history, type); - const auto requestId = MTP::send( - MTPmessages_SetTyping( - peer->input, - action), - rpcDone(&HistoryWidget::sendActionDone)); - _sendActionRequests.insert(key, requestId); + const auto requestId = session().api().request(MTPmessages_SetTyping( + peer->input, + action + )).done([=](const MTPBool &result, mtpRequestId requestId) { + sendActionDone(result, requestId); + }).send(); + _sendActionRequests.emplace(std::pair(history, type), requestId); if (type == Type::Typing) { _sendActionStopTimer.callOnce(kCancelTypingActionTimeout); } @@ -1400,9 +1402,11 @@ void HistoryWidget::updateSendAction( } } -void HistoryWidget::sendActionDone(const MTPBool &result, mtpRequestId req) { +void HistoryWidget::sendActionDone( + const MTPBool &result, + mtpRequestId requestId) { for (auto i = _sendActionRequests.begin(), e = _sendActionRequests.end(); i != e; ++i) { - if (i.value() == req) { + if (i->second == requestId) { _sendActionRequests.erase(i); break; } @@ -2401,18 +2405,14 @@ void HistoryWidget::unreadCountUpdated() { } } -bool HistoryWidget::messagesFailed(const RPCError &error, int requestId) { - if (MTP::isDefaultHandledError(error)) { - return false; - } - +void HistoryWidget::messagesFailed(const RPCError &error, int requestId) { if (error.type() == qstr("CHANNEL_PRIVATE") || error.type() == qstr("CHANNEL_PUBLIC_GROUP_NA") || error.type() == qstr("USER_BANNED_IN_CHANNEL")) { auto was = _peer; controller()->showBackFromStack(); Ui::show(Box((was && was->isMegagroup()) ? tr::lng_group_not_accessible(tr::now) : tr::lng_channel_not_accessible(tr::now))); - return true; + return; } LOG(("RPC Error: %1 %2: %3").arg(error.code()).arg(error.type()).arg(error.description())); @@ -2426,7 +2426,6 @@ bool HistoryWidget::messagesFailed(const RPCError &error, int requestId) { } else if (_delayedShowAtRequest == requestId) { _delayedShowAtRequest = 0; } - return true; } void HistoryWidget::messagesReceived(PeerData *peer, const MTPmessages_Messages &messages, int requestId) { @@ -3046,29 +3045,32 @@ void HistoryWidget::saveEditMsg() { }).send(); } -void HistoryWidget::saveEditMsgDone(History *history, const MTPUpdates &updates, mtpRequestId req) { +void HistoryWidget::saveEditMsgDone( + not_null history, + const MTPUpdates &updates, + mtpRequestId requestId) { session().api().applyUpdates(updates); - if (req == _saveEditMsgRequestId) { + if (requestId == _saveEditMsgRequestId) { _saveEditMsgRequestId = 0; cancelEdit(); } if (auto editDraft = history->editDraft()) { - if (editDraft->saveRequestId == req) { + if (editDraft->saveRequestId == requestId) { history->clearEditDraft(); session().local().writeDrafts(history); } } } -bool HistoryWidget::saveEditMsgFail(History *history, const RPCError &error, mtpRequestId req) { - if (MTP::isDefaultHandledError(error)) { - return false; - } - if (req == _saveEditMsgRequestId) { +void HistoryWidget::saveEditMsgFail( + not_null history, + const RPCError &error, + mtpRequestId requestId) { + if (requestId == _saveEditMsgRequestId) { _saveEditMsgRequestId = 0; } if (auto editDraft = history->editDraft()) { - if (editDraft->saveRequestId == req) { + if (editDraft->saveRequestId == requestId) { editDraft->saveRequestId = 0; } } @@ -3085,7 +3087,6 @@ bool HistoryWidget::saveEditMsgFail(History *history, const RPCError &error, mtp Ui::show(Box(tr::lng_edit_error(tr::now))); } update(); - return true; } void HistoryWidget::hideSelectorControlsAnimated() { @@ -3655,14 +3656,16 @@ void HistoryWidget::app_sendBotCallback( flags |= MTPmessages_GetBotCallbackAnswer::Flag::f_data; sendData = button->data; } - button->requestId = MTP::send( - MTPmessages_GetBotCallbackAnswer( - MTP_flags(flags), - _peer->input, - MTP_int(msg->id), - MTP_bytes(sendData)), - rpcDone(&HistoryWidget::botCallbackDone, info), - rpcFail(&HistoryWidget::botCallbackFail, info)); + button->requestId = session().api().request(MTPmessages_GetBotCallbackAnswer( + MTP_flags(flags), + _peer->input, + MTP_int(msg->id), + MTP_bytes(sendData) + )).done([=](const MTPmessages_BotCallbackAnswer &result, mtpRequestId requestId) { + botCallbackDone(info, result, requestId); + }).fail([=](const RPCError &error, mtpRequestId requestId) { + botCallbackFail(info, error, requestId); + }).send(); session().data().requestItemRepaint(msg); if (_replyToId == msg->id) { @@ -3893,16 +3896,13 @@ void HistoryWidget::inlineBotResolveDone( } } -bool HistoryWidget::inlineBotResolveFail(QString name, const RPCError &error) { - if (MTP::isDefaultHandledError(error)) { - return false; - } - +void HistoryWidget::inlineBotResolveFail( + const RPCError &error, + const QString &username) { _inlineBotResolveRequestId = 0; - if (name == _inlineBotUsername) { + if (username == _inlineBotUsername) { clearInlineBot(); } - return true; } bool HistoryWidget::isBotStart() const { @@ -6162,19 +6162,16 @@ void HistoryWidget::unpinMessage(FullMsgId itemId) { peer->clearPinnedMessage(); Ui::hideLayer(); - MTP::send( - MTPmessages_UpdatePinnedMessage( - MTP_flags(0), - peer->input, - MTP_int(0)), - rpcDone(&HistoryWidget::unpinDone)); + session().api().request(MTPmessages_UpdatePinnedMessage( + MTP_flags(0), + peer->input, + MTP_int(0) + )).done([=](const MTPUpdates &result) { + session().api().applyUpdates(result); + }).send(); }))); } -void HistoryWidget::unpinDone(const MTPUpdates &updates) { - session().api().applyUpdates(updates); -} - void HistoryWidget::hidePinnedMessage() { const auto pinnedId = _peer ? _peer->pinnedMessageId() : MsgId(0); if (!pinnedId) { @@ -6329,7 +6326,7 @@ void HistoryWidget::cancelFieldAreaState() { } void HistoryWidget::previewCancel() { - MTP::cancel(base::take(_previewRequest)); + session().api().request(base::take(_previewRequest)).cancel(); _previewData = nullptr; _previewLinks.clear(); updatePreview(); @@ -6343,28 +6340,29 @@ void HistoryWidget::checkPreview() { previewCancel(); return; } - const auto newLinks = _parsedLinks.join(' '); - if (_previewLinks != newLinks) { - MTP::cancel(base::take(_previewRequest)); - _previewLinks = newLinks; + const auto links = _parsedLinks.join(' '); + if (_previewLinks != links) { + session().api().request(base::take(_previewRequest)).cancel(); + _previewLinks = links; if (_previewLinks.isEmpty()) { if (_previewData && _previewData->pendingTill >= 0) { previewCancel(); } } else { - const auto i = _previewCache.constFind(_previewLinks); + const auto i = _previewCache.constFind(links); if (i == _previewCache.cend()) { - _previewRequest = MTP::send( - MTPmessages_GetWebPagePreview( - MTP_flags(0), - MTP_string(_previewLinks), - MTPVector()), - rpcDone(&HistoryWidget::gotPreview, _previewLinks)); + _previewRequest = session().api().request(MTPmessages_GetWebPagePreview( + MTP_flags(0), + MTP_string(links), + MTPVector() + )).done([=](const MTPMessageMedia &result, mtpRequestId requestId) { + gotPreview(links, result, requestId); + }).send(); } else if (i.value()) { _previewData = session().data().webpage(i.value()); updatePreview(); - } else { - if (_previewData && _previewData->pendingTill >= 0) previewCancel(); + } else if (_previewData && _previewData->pendingTill >= 0) { + previewCancel(); } } } @@ -6376,12 +6374,14 @@ void HistoryWidget::requestPreview() { || _previewLinks.isEmpty()) { return; } - _previewRequest = MTP::send( - MTPmessages_GetWebPagePreview( - MTP_flags(0), - MTP_string(_previewLinks), - MTPVector()), - rpcDone(&HistoryWidget::gotPreview, _previewLinks)); + const auto links = _previewLinks; + _previewRequest = session().api().request(MTPmessages_GetWebPagePreview( + MTP_flags(0), + MTP_string(links), + MTPVector() + )).done([=](const MTPMessageMedia &result, mtpRequestId requestId) { + gotPreview(links, result, requestId); + }).send(); } void HistoryWidget::gotPreview(QString links, const MTPMessageMedia &result, mtpRequestId req) { diff --git a/Telegram/SourceFiles/history/history_widget.h b/Telegram/SourceFiles/history/history_widget.h index 95a433937..3815789de 100644 --- a/Telegram/SourceFiles/history/history_widget.h +++ b/Telegram/SourceFiles/history/history_widget.h @@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/flags.h" #include "base/timer.h" +class RPCError; struct FileLoadResult; struct FileMediaInformation; struct SendingAlbum; @@ -96,9 +97,7 @@ class MessageField; class HistoryInner; struct HistoryMessageMarkupButton; -class HistoryWidget final - : public Window::AbstractSectionWidget - , public RPCSender { +class HistoryWidget final : public Window::AbstractSectionWidget { Q_OBJECT public: @@ -435,7 +434,7 @@ private: not_null history, SendAction::Type type); void cancelTypingAction(); - void sendActionDone(const MTPBool &result, mtpRequestId req); + void sendActionDone(const MTPBool &result, mtpRequestId requestId); void animationCallback(); void updateOverStates(QPoint pos); @@ -556,7 +555,6 @@ private: void updatePinnedBar(bool force = false); bool pinnedMsgVisibilityUpdated(); void destroyPinnedBar(); - void unpinDone(const MTPUpdates &updates); void sendInlineResult( not_null result, @@ -583,14 +581,14 @@ private: void createUnreadBarAndResize(); void saveEditMsg(); - void saveEditMsgDone(History *history, const MTPUpdates &updates, mtpRequestId req); - bool saveEditMsgFail(History *history, const RPCError &error, mtpRequestId req); + void saveEditMsgDone(not_null history, const MTPUpdates &updates, mtpRequestId requestId); + void saveEditMsgFail(not_null history, const RPCError &error, mtpRequestId requestId); void checkPreview(); void requestPreview(); void gotPreview(QString links, const MTPMessageMedia &media, mtpRequestId req); void messagesReceived(PeerData *peer, const MTPmessages_Messages &messages, int requestId); - bool messagesFailed(const RPCError &error, int requestId); + void messagesFailed(const RPCError &error, int requestId); void addMessagesToFront(PeerData *peer, const QVector &messages); void addMessagesToBack(PeerData *peer, const QVector &messages); @@ -645,7 +643,7 @@ private: void handleSupportSwitch(not_null updated); void inlineBotResolveDone(const MTPcontacts_ResolvedPeer &result); - bool inlineBotResolveFail(QString name, const RPCError &error); + void inlineBotResolveFail(const RPCError &error, const QString &username); bool isBotStart() const; bool isBlocked() const; @@ -813,7 +811,9 @@ private: base::Timer _highlightTimer; crl::time _highlightStart = 0; - QMap, SendAction::Type>, mtpRequestId> _sendActionRequests; + base::flat_map< + std::pair, SendAction::Type>, + mtpRequestId> _sendActionRequests; base::Timer _sendActionStopTimer; crl::time _saveDraftStart = 0; diff --git a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp index e322ce035..c1e26fd35 100644 --- a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp +++ b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp @@ -154,7 +154,7 @@ Main::Session &TopBarWidget::session() const { } void TopBarWidget::updateConnectingState() { - const auto mtp = MTP::dcstate(); + const auto mtp = _controller->session().mtp()->dcstate(); if (mtp == MTP::ConnectedState) { if (_connecting) { _connecting = nullptr; diff --git a/Telegram/SourceFiles/info/common_groups/info_common_groups_inner_widget.cpp b/Telegram/SourceFiles/info/common_groups/info_common_groups_inner_widget.cpp index 608922e21..e68dc414e 100644 --- a/Telegram/SourceFiles/info/common_groups/info_common_groups_inner_widget.cpp +++ b/Telegram/SourceFiles/info/common_groups/info_common_groups_inner_widget.cpp @@ -17,7 +17,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/search_field_controller.h" #include "data/data_user.h" #include "data/data_session.h" -#include "apiwrap.h" #include "styles/style_info.h" #include "styles/style_widgets.h" @@ -69,7 +68,7 @@ ListController::ListController( not_null user) : PeerListController() , _controller(controller) -, _api(_controller->session().api().instance()) +, _api(_controller->session().mtp()) , _user(user) { _controller->setSearchEnabledByContent(false); } diff --git a/Telegram/SourceFiles/info/polls/info_polls_results_inner_widget.cpp b/Telegram/SourceFiles/info/polls/info_polls_results_inner_widget.cpp index 88d0263a6..b25cb2570 100644 --- a/Telegram/SourceFiles/info/polls/info_polls_results_inner_widget.cpp +++ b/Telegram/SourceFiles/info/polls/info_polls_results_inner_widget.cpp @@ -24,7 +24,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "main/main_session.h" #include "history/history.h" #include "history/history_item.h" -#include "apiwrap.h" #include "styles/style_layers.h" #include "styles/style_boxes.h" #include "styles/style_info.h" @@ -233,7 +232,7 @@ ListController::ListController( , _poll(poll) , _context(context) , _option(option) -, _api(_session->api().instance()) { +, _api(_session->mtp()) { const auto i = ranges::find(poll->answers, option, &PollAnswer::option); Assert(i != poll->answers.end()); _fullCount = i->votes; diff --git a/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp b/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp index 5b9389258..225b5f471 100644 --- a/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp +++ b/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp @@ -24,7 +24,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "lang/lang_keys.h" #include "mainwindow.h" -#include "apiwrap.h" #include "mainwidget.h" #include "main/main_session.h" #include "window/window_session_controller.h" @@ -744,7 +743,7 @@ Widget::Widget( not_null controller) : RpWidget(parent) , _controller(controller) -, _api(_controller->session().api().instance()) +, _api(_controller->session().mtp()) , _contentMaxHeight(st::emojiPanMaxHeight) , _contentHeight(_contentMaxHeight) , _scroll(this, st::inlineBotsScroll) { @@ -1027,8 +1026,7 @@ void Widget::inlineBotChanged() { hideAnimated(); } - if (_inlineRequestId) MTP::cancel(_inlineRequestId); - _inlineRequestId = 0; + _api.request(base::take(_inlineRequestId)).cancel(); _inlineQuery = _inlineNextQuery = _inlineNextOffset = QString(); _inlineBot = nullptr; _inlineCache.clear(); @@ -1104,7 +1102,7 @@ void Widget::queryInlineBot(UserData *bot, PeerData *peer, QString query) { if (_inlineQuery != query || force) { if (_inlineRequestId) { - MTP::cancel(_inlineRequestId); + _api.request(_inlineRequestId).cancel(); _inlineRequestId = 0; _requesting.fire(false); } diff --git a/Telegram/SourceFiles/main/main_account.cpp b/Telegram/SourceFiles/main/main_account.cpp index 0e21790ab..73a70fdf3 100644 --- a/Telegram/SourceFiles/main/main_account.cpp +++ b/Telegram/SourceFiles/main/main_account.cpp @@ -21,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwidget.h" #include "observer_peer.h" #include "api/api_updates.h" -#include "apiwrap.h" #include "main/main_app_config.h" #include "main/main_session.h" #include "facades.h" @@ -350,14 +349,14 @@ void Account::startMtp() { } return true; })); - _mtp->setStateChangedHandler([](MTP::ShiftedDcId dc, int32 state) { - if (dc == MTP::maindc()) { + _mtp->setStateChangedHandler([=](MTP::ShiftedDcId dc, int32 state) { + if (dc == _mtp->mainDcId()) { Global::RefConnectionTypeChanged().notify(); } }); _mtp->setSessionResetHandler([=](MTP::ShiftedDcId shiftedDcId) { if (sessionExists()) { - if (shiftedDcId == session().api().instance()->mainDcId()) { + if (shiftedDcId == _mtp->mainDcId()) { session().updates().getDifference(); } } diff --git a/Telegram/SourceFiles/main/main_session.cpp b/Telegram/SourceFiles/main/main_session.cpp index 56a455b26..82295708e 100644 --- a/Telegram/SourceFiles/main/main_session.cpp +++ b/Telegram/SourceFiles/main/main_session.cpp @@ -148,7 +148,11 @@ void Session::saveSettingsDelayed(crl::time delay) { _saveSettingsTimer.callOnce(delay); } -not_null Session::mtp() { +MTP::DcId Session::mainDcId() const { + return _account->mtp()->mainDcId(); +} + +not_null Session::mtp() const { return _account->mtp(); } diff --git a/Telegram/SourceFiles/main/main_session.h b/Telegram/SourceFiles/main/main_session.h index 1e23100ce..bb71e4998 100644 --- a/Telegram/SourceFiles/main/main_session.h +++ b/Telegram/SourceFiles/main/main_session.h @@ -105,8 +105,6 @@ public: return *_diceStickersPacks; } - [[nodiscard]] base::Observable &downloaderTaskFinished(); - [[nodiscard]] Window::Notifications::System ¬ifications() { return *_notifications; } @@ -124,7 +122,10 @@ public: [[nodiscard]] auto windows() const -> const base::flat_set> &; - [[nodiscard]] not_null mtp(); + // Shortcuts. + [[nodiscard]] base::Observable &downloaderTaskFinished(); + [[nodiscard]] MTP::DcId mainDcId() const; + [[nodiscard]] not_null mtp() const; [[nodiscard]] ApiWrap &api() { return *_api; } diff --git a/Telegram/SourceFiles/mainwidget.cpp b/Telegram/SourceFiles/mainwidget.cpp index 88383a676..931dbd9f6 100644 --- a/Telegram/SourceFiles/mainwidget.cpp +++ b/Telegram/SourceFiles/mainwidget.cpp @@ -1279,43 +1279,53 @@ void MainWidget::scheduleViewIncrement(HistoryItem *item) { PeerData *peer = item->history()->peer; auto i = _viewsIncremented.find(peer); if (i != _viewsIncremented.cend()) { - if (i.value().contains(item->id)) return; + if (i->second.contains(item->id)) return; } else { - i = _viewsIncremented.insert(peer, ViewsIncrementMap()); + i = _viewsIncremented.emplace(peer).first; } - i.value().insert(item->id, true); + i->second.emplace(item->id); auto j = _viewsToIncrement.find(peer); if (j == _viewsToIncrement.cend()) { - j = _viewsToIncrement.insert(peer, ViewsIncrementMap()); + j = _viewsToIncrement.emplace(peer).first; _viewsIncrementTimer.callOnce(kSendViewsTimeout); } - j.value().insert(item->id, true); + j->second.emplace(item->id); } void MainWidget::viewsIncrement() { + const auto api = &session().api(); for (auto i = _viewsToIncrement.begin(); i != _viewsToIncrement.cend();) { - if (_viewsIncrementRequests.contains(i.key())) { + if (_viewsIncrementRequests.contains(i->first)) { ++i; continue; } QVector ids; - ids.reserve(i.value().size()); - for (ViewsIncrementMap::const_iterator j = i.value().cbegin(), end = i.value().cend(); j != end; ++j) { - ids.push_back(MTP_int(j.key())); + ids.reserve(i->second.size()); + for (const auto msgId : i->second) { + ids.push_back(MTP_int(msgId)); } - auto req = MTP::send(MTPmessages_GetMessagesViews(i.key()->input, MTP_vector(ids), MTP_bool(true)), rpcDone(&MainWidget::viewsIncrementDone, ids), rpcFail(&MainWidget::viewsIncrementFail), 0, 5); - _viewsIncrementRequests.insert(i.key(), req); + const auto requestId = api->request(MTPmessages_GetMessagesViews( + i->first->input, + MTP_vector(ids), + MTP_bool(true) + )).done([=](const MTPVector &result, mtpRequestId requestId) { + viewsIncrementDone(ids, result, requestId); + }).fail([=](const RPCError &error, mtpRequestId requestId) { + viewsIncrementFail(error, requestId); + }).afterDelay(5).send(); + + _viewsIncrementRequests.emplace(i->first, requestId); i = _viewsToIncrement.erase(i); } } -void MainWidget::viewsIncrementDone(QVector ids, const MTPVector &result, mtpRequestId req) { +void MainWidget::viewsIncrementDone(QVector ids, const MTPVector &result, mtpRequestId requestId) { auto &v = result.v; if (ids.size() == v.size()) { for (auto i = _viewsIncrementRequests.begin(); i != _viewsIncrementRequests.cend(); ++i) { - if (i.value() == req) { - PeerData *peer = i.key(); + if (i->second == requestId) { + const auto peer = i->first; ChannelId channel = peerToChannel(peer->id); for (int32 j = 0, l = ids.size(); j < l; ++j) { if (HistoryItem *item = session().data().message(channel, ids.at(j).v)) { @@ -1327,24 +1337,21 @@ void MainWidget::viewsIncrementDone(QVector ids, const MTPVector } } } - if (!_viewsToIncrement.isEmpty() && !_viewsIncrementTimer.isActive()) { + if (!_viewsToIncrement.empty() && !_viewsIncrementTimer.isActive()) { _viewsIncrementTimer.callOnce(kSendViewsTimeout); } } -bool MainWidget::viewsIncrementFail(const RPCError &error, mtpRequestId req) { - if (MTP::isDefaultHandledError(error)) return false; - +void MainWidget::viewsIncrementFail(const RPCError &error, mtpRequestId requestId) { for (auto i = _viewsIncrementRequests.begin(); i != _viewsIncrementRequests.cend(); ++i) { - if (i.value() == req) { + if (i->second == requestId) { _viewsIncrementRequests.erase(i); break; } } - if (!_viewsToIncrement.isEmpty() && !_viewsIncrementTimer.isActive()) { + if (!_viewsToIncrement.empty() && !_viewsIncrementTimer.isActive()) { _viewsIncrementTimer.callOnce(kSendViewsTimeout); } - return false; } void MainWidget::refreshDialog(Dialogs::Key key) { @@ -2690,7 +2697,13 @@ void MainWidget::openPeerByName( }); } } else { - MTP::send(MTPcontacts_ResolveUsername(MTP_string(username)), rpcDone(&MainWidget::usernameResolveDone, qMakePair(msgId, startToken)), rpcFail(&MainWidget::usernameResolveFail, username)); + session().api().request(MTPcontacts_ResolveUsername( + MTP_string(username) + )).done([=](const MTPcontacts_ResolvedPeer &result) { + usernameResolveDone(result, msgId, startToken); + }).fail([=](const RPCError &error) { + usernameResolveFail(error, username); + }).send(); } } @@ -2700,19 +2713,24 @@ bool MainWidget::contentOverlapped(const QRect &globalRect) { || (_playerVolume && _playerVolume->overlaps(globalRect))); } -void MainWidget::usernameResolveDone(QPair msgIdAndStartToken, const MTPcontacts_ResolvedPeer &result) { +void MainWidget::usernameResolveDone( + const MTPcontacts_ResolvedPeer &result, + MsgId msgId, + const QString &startToken) { Ui::hideLayer(); - if (result.type() != mtpc_contacts_resolvedPeer) return; + if (result.type() != mtpc_contacts_resolvedPeer) { + return; + } const auto &d(result.c_contacts_resolvedPeer()); session().data().processUsers(d.vusers()); session().data().processChats(d.vchats()); - PeerId peerId = peerFromMTP(d.vpeer()); - if (!peerId) return; + const auto peerId = peerFromMTP(d.vpeer()); + if (!peerId) { + return; + } - PeerData *peer = session().data().peer(peerId); - MsgId msgId = msgIdAndStartToken.first; - QString startToken = msgIdAndStartToken.second; + const auto peer = session().data().peer(peerId); if (msgId == ShowAtProfileMsgId && !peer->isChannel()) { if (peer->isUser() && peer->asUser()->isBot() && !peer->asUser()->botInfo->cantJoinGroups && !startToken.isEmpty()) { peer->asUser()->botInfo->startGroupToken = startToken; @@ -2730,7 +2748,8 @@ void MainWidget::usernameResolveDone(QPair msgIdAndStartToken, c _controller->showPeerInfo(peer); } } else { - if (msgId == ShowAtProfileMsgId || !peer->isChannel()) { // show specific posts only in channels / supergroups + // show specific posts only in channels / supergroups + if (msgId == ShowAtProfileMsgId || !peer->isChannel()) { msgId = ShowAtUnreadMsgId; } if (peer->isUser() && peer->asUser()->isBot()) { @@ -2740,7 +2759,7 @@ void MainWidget::usernameResolveDone(QPair msgIdAndStartToken, c _history->updateControlsGeometry(); } } - InvokeQueued(this, [this, peer, msgId] { + InvokeQueued(this, [=] { _controller->showPeerHistory( peer->id, SectionShow::Way::Forward, @@ -2749,13 +2768,11 @@ void MainWidget::usernameResolveDone(QPair msgIdAndStartToken, c } } -bool MainWidget::usernameResolveFail(QString name, const RPCError &error) { - if (MTP::isDefaultHandledError(error)) return false; - +void MainWidget::usernameResolveFail(const RPCError &error, const QString &username) { if (error.code() == 400) { - Ui::show(Box(tr::lng_username_not_found(tr::now, lt_user, name))); + Ui::show(Box( + tr::lng_username_not_found(tr::now, lt_user, username))); } - return true; } void MainWidget::incrementSticker(DocumentData *sticker) { diff --git a/Telegram/SourceFiles/mainwidget.h b/Telegram/SourceFiles/mainwidget.h index c41c3acc8..fb843bf7a 100644 --- a/Telegram/SourceFiles/mainwidget.h +++ b/Telegram/SourceFiles/mainwidget.h @@ -13,8 +13,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/effects/animations.h" #include "media/player/media_player_float.h" #include "data/data_pts_waiter.h" -#include "mtproto/mtproto_rpc_sender.h" +class RPCError; struct HistoryMessageMarkupButton; class MainWindow; class ConfirmBox; @@ -100,7 +100,6 @@ class ItemBase; class MainWidget : public Ui::RpWidget - , public RPCSender , private base::Subscriber , private Media::Player::FloatDelegate { Q_OBJECT @@ -324,8 +323,13 @@ private: void saveSectionInStack(); - void usernameResolveDone(QPair msgIdAndStartToken, const MTPcontacts_ResolvedPeer &result); - bool usernameResolveFail(QString name, const RPCError &error); + void usernameResolveDone( + const MTPcontacts_ResolvedPeer &result, + MsgId msgId, + const QString &startToken); + void usernameResolveFail( + const RPCError &error, + const QString &username); int getMainSectionTop() const; int getThirdSectionTop() const; @@ -348,8 +352,11 @@ private: bool floatPlayerIsVisible(not_null item) override; void floatPlayerClosed(FullMsgId itemId); - void viewsIncrementDone(QVector ids, const MTPVector &result, mtpRequestId req); - bool viewsIncrementFail(const RPCError &error, mtpRequestId req); + void viewsIncrementDone( + QVector ids, + const MTPVector &result, + mtpRequestId requestId); + void viewsIncrementFail(const RPCError &error, mtpRequestId requestId); void refreshResizeAreas(); template @@ -422,10 +429,10 @@ private: PhotoData *_deletingPhoto = nullptr; - using ViewsIncrementMap = QMap; - QMap _viewsIncremented, _viewsToIncrement; - QMap _viewsIncrementRequests; - QMap _viewsIncrementByRequest; + base::flat_map, base::flat_set> _viewsIncremented; + base::flat_map, base::flat_set> _viewsToIncrement; + base::flat_map, mtpRequestId> _viewsIncrementRequests; + base::flat_map> _viewsIncrementByRequest; base::Timer _viewsIncrementTimer; struct SettingBackground; diff --git a/Telegram/SourceFiles/mtproto/facade.cpp b/Telegram/SourceFiles/mtproto/facade.cpp index 011999252..2ff96d0ac 100644 --- a/Telegram/SourceFiles/mtproto/facade.cpp +++ b/Telegram/SourceFiles/mtproto/facade.cpp @@ -16,6 +16,7 @@ namespace details { namespace { int PauseLevel = 0; +rpl::event_stream<> Unpaused; } // namespace @@ -30,18 +31,13 @@ void pause() { void unpause() { --PauseLevel; if (!PauseLevel) { - if (auto instance = MainInstance()) { - instance->unpaused(); - } + Unpaused.fire({}); } } -} // namespace details - -Instance *MainInstance() { - return Core::IsAppLaunched() // #TODO multi - ? Core::App().activeAccount().mtp() - : nullptr; +rpl::producer<> unpaused() { + return Unpaused.events(); } +} // namespace details } // namespace MTP diff --git a/Telegram/SourceFiles/mtproto/facade.h b/Telegram/SourceFiles/mtproto/facade.h index 037085366..6afce1e0d 100644 --- a/Telegram/SourceFiles/mtproto/facade.h +++ b/Telegram/SourceFiles/mtproto/facade.h @@ -16,6 +16,7 @@ namespace details { [[nodiscard]] bool paused(); void pause(); void unpause(); +[[nodiscard]] rpl::producer<> unpaused(); } // namespace details @@ -114,87 +115,4 @@ enum { RequestSending = 2 }; -Instance *MainInstance(); - -inline void restart() { - return MainInstance()->restart(); -} - -inline void restart(ShiftedDcId shiftedDcId) { - return MainInstance()->restart(shiftedDcId); -} - -inline DcId maindc() { - return MainInstance()->mainDcId(); -} - -inline int32 dcstate(ShiftedDcId shiftedDcId = 0) { - if (const auto instance = MainInstance()) { - return instance->dcstate(shiftedDcId); - } - return DisconnectedState; -} - -inline QString dctransport(ShiftedDcId shiftedDcId = 0) { - if (auto instance = MainInstance()) { - return instance->dctransport(shiftedDcId); - } - return QString(); -} - -template -inline mtpRequestId send( - const TRequest &request, - RPCResponseHandler &&callbacks = {}, - ShiftedDcId dcId = 0, - crl::time msCanWait = 0, - mtpRequestId after = 0) { - return MainInstance()->send(request, std::move(callbacks), dcId, msCanWait, after); -} - -template -inline mtpRequestId send( - const TRequest &request, - RPCDoneHandlerPtr &&onDone, - RPCFailHandlerPtr &&onFail = nullptr, - ShiftedDcId dcId = 0, - crl::time msCanWait = 0, - mtpRequestId after = 0) { - return MainInstance()->send(request, std::move(onDone), std::move(onFail), dcId, msCanWait, after); -} - -inline void sendAnything(ShiftedDcId shiftedDcId = 0, crl::time msCanWait = 0) { - if (const auto instance = MainInstance()) { - instance->sendAnything(shiftedDcId, msCanWait); - } -} - -inline void cancel(mtpRequestId requestId) { - if (const auto instance = MainInstance()) { - instance->cancel(requestId); - } -} - -inline void ping() { - if (const auto instance = MainInstance()) { - instance->ping(); - } -} - -inline void killSession(ShiftedDcId shiftedDcId) { - if (const auto instance = MainInstance()) { - instance->killSession(shiftedDcId); - } -} - -inline void stopSession(ShiftedDcId shiftedDcId) { - if (const auto instance = MainInstance()) { - instance->stopSession(shiftedDcId); - } -} - -inline int32 state(mtpRequestId requestId) { // < 0 means waiting for such count of ms - return MainInstance()->state(requestId); -} - } // namespace MTP diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.cpp b/Telegram/SourceFiles/mtproto/mtp_instance.cpp index 3aec7f4f8..bf561124c 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_instance.cpp @@ -107,7 +107,6 @@ public: ShiftedDcId shiftedDcId, AuthKeyPtr &&key = nullptr); void removeDc(ShiftedDcId shiftedDcId); - void unpaused(); void sendRequest( mtpRequestId requestId, @@ -169,6 +168,8 @@ private: bool exportFail(const RPCError &error, mtpRequestId requestId); bool onErrorDefault(mtpRequestId requestId, const RPCError &error); + void unpaused(); + Session *findSession(ShiftedDcId shiftedDcId); not_null startSession(ShiftedDcId shiftedDcId); Session *removeSession(ShiftedDcId shiftedDcId); @@ -270,6 +271,10 @@ Instance::Private::Private( , _mode(mode) { const auto idealThreadPoolSize = QThread::idealThreadCount(); _fileSessionThreads.resize(2 * std::max(idealThreadPoolSize / 2, 1)); + details::unpaused( + ) | rpl::start_with_next([=] { + unpaused(); + }, _lifetime); } void Instance::Private::start(Config &&config) { @@ -1794,10 +1799,6 @@ QString Instance::systemVersion() const { return _private->systemVersion(); } -void Instance::unpaused() { - _private->unpaused(); -} - void Instance::setUpdatesHandler(RPCDoneHandlerPtr onDone) { _private->setUpdatesHandler(onDone); } diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.h b/Telegram/SourceFiles/mtproto/mtp_instance.h index 868a0b1ab..7e44f9553 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.h +++ b/Telegram/SourceFiles/mtproto/mtp_instance.h @@ -7,8 +7,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once -#include "mtproto/mtproto_rpc_sender.h" #include "mtproto/details/mtproto_serialized_request.h" +#include "mtproto/mtproto_rpc_sender.h" namespace MTP { namespace details { @@ -90,8 +90,6 @@ public: void reInitConnection(DcId dcId); void logout(Fn done); - void unpaused(); - void setUpdatesHandler(RPCDoneHandlerPtr onDone); void setGlobalFailHandler(RPCFailHandlerPtr onFail); void setStateChangedHandler(Fn handler); diff --git a/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.cpp b/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.cpp index b211cda30..50a2d95ab 100644 --- a/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.cpp +++ b/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.cpp @@ -102,8 +102,11 @@ bool ConcurrentSender::RPCFailHandler::operator()( template auto ConcurrentSender::with_instance(Method &&method) -> std::enable_if_t>> { - crl::on_main([method = std::forward(method)]() mutable { - if (const auto instance = MainInstance()) { + crl::on_main([ + weak = _weak, + method = std::forward(method) + ]() mutable { + if (const auto instance = weak.data()) { std::move(method)(instance); } }); @@ -162,8 +165,11 @@ mtpRequestId ConcurrentSender::RequestBuilder::send() { return requestId; } -ConcurrentSender::ConcurrentSender(Fn)> runner) -: _runner(runner) { +ConcurrentSender::ConcurrentSender( + QPointer weak, + Fn)> runner) +: _weak(weak) +, _runner(runner) { } ConcurrentSender::~ConcurrentSender() { diff --git a/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.h b/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.h index 74c1c4482..ca47ef7f7 100644 --- a/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.h +++ b/Telegram/SourceFiles/mtproto/mtproto_concurrent_sender.h @@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/core_types.h" #include "mtproto/details/mtproto_serialized_request.h" +#include #include #ifndef _DEBUG @@ -87,7 +88,9 @@ class ConcurrentSender : public base::has_weak_ptr { }; public: - ConcurrentSender(Fn)> runner); + ConcurrentSender( + QPointer weak, + Fn)> runner); template class SpecificRequestBuilder : public RequestBuilder { @@ -193,6 +196,7 @@ private: void senderRequestCancelAll(); void senderRequestDetach(mtpRequestId requestId); + const QPointer _weak; const Fn)> _runner; base::flat_map _requests; diff --git a/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.cpp b/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.cpp index b723fd292..7d52baf7a 100644 --- a/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.cpp +++ b/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.cpp @@ -30,24 +30,3 @@ RPCError::RPCError(const MTPrpcError &error) } } } - - -RPCOwnedDoneHandler::RPCOwnedDoneHandler(RPCSender *owner) : _owner(owner) { - _owner->rpcRegHandler(this); -} - -RPCOwnedDoneHandler::~RPCOwnedDoneHandler() { - if (_owner) { - _owner->rpcUnregHandler(this); - } -} - -RPCOwnedFailHandler::RPCOwnedFailHandler(RPCSender *owner) : _owner(owner) { - _owner->rpcRegHandler(this); -} - -RPCOwnedFailHandler::~RPCOwnedFailHandler() { - if (_owner) { - _owner->rpcUnregHandler(this); - } -} diff --git a/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.h b/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.h index 338c81a15..0ca1bcc27 100644 --- a/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.h +++ b/Telegram/SourceFiles/mtproto/mtproto_rpc_sender.h @@ -313,549 +313,6 @@ inline RPCFailHandlerPtr rpcFail(bool (*onFail)(mtpRequestId)) { // fail(req_id) return RPCFailHandlerPtr(new RPCFailHandlerNoReq(onFail)); } -class RPCSender; - -class RPCOwnedDoneHandler : public RPCAbstractDoneHandler { // abstract done -public: - RPCOwnedDoneHandler(RPCSender *owner); - void invalidate() { - _owner = nullptr; - } - ~RPCOwnedDoneHandler(); - -protected: - RPCSender *_owner = nullptr; - -}; - -class RPCOwnedFailHandler : public RPCAbstractFailHandler { // abstract fail -public: - RPCOwnedFailHandler(RPCSender *owner); - void invalidate() { - _owner = nullptr; - } - ~RPCOwnedFailHandler(); - -protected: - RPCSender *_owner = nullptr; - -}; - -template -class RPCDoneHandlerBareOwned : public RPCOwnedDoneHandler { // done(from, end) - using CallbackType = bool (TReceiver::*)(const mtpPrime *, const mtpPrime *); - -public: - RPCDoneHandlerBareOwned(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - return _owner - ? (static_cast(_owner)->*_onDone)(from, end) - : true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCDoneHandlerBareOwnedReq : public RPCOwnedDoneHandler { // done(from, end, req_id) - using CallbackType = bool (TReceiver::*)(const mtpPrime *, const mtpPrime *, mtpRequestId); - -public: - RPCDoneHandlerBareOwnedReq(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - return _owner - ? (static_cast(_owner)->*_onDone)(from, end, requestId) - : true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCDoneHandlerOwned : public RPCOwnedDoneHandler { // done(result) - using CallbackType = TReturn (TReceiver::*)(const TResponse &); - -public: - RPCDoneHandlerOwned(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - auto response = TResponse(); - if (!response.read(from, end)) { - return false; - } - if (_owner) { - (static_cast(_owner)->*_onDone)(std::move(response)); - } - return true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCDoneHandlerOwnedReq : public RPCOwnedDoneHandler { // done(result, req_id) - using CallbackType = TReturn (TReceiver::*)(const TResponse &, mtpRequestId); - -public: - RPCDoneHandlerOwnedReq(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - auto response = TResponse(); - if (!response.read(from, end)) { - return false; - } - if (_owner) { - (static_cast(_owner)->*_onDone)(std::move(response), requestId); - } - return true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCDoneHandlerOwnedNo : public RPCOwnedDoneHandler { // done() - using CallbackType = TReturn (TReceiver::*)(); - -public: - RPCDoneHandlerOwnedNo(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - if (_owner) (static_cast(_owner)->*_onDone)(); - return true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCDoneHandlerOwnedNoReq : public RPCOwnedDoneHandler { // done(req_id) - using CallbackType = TReturn (TReceiver::*)(mtpRequestId); - -public: - RPCDoneHandlerOwnedNoReq(TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - if (_owner) (static_cast(_owner)->*_onDone)(requestId); - return true; - } - -private: - CallbackType _onDone; - -}; - -template -class RPCBindedDoneHandlerBareOwned : public RPCOwnedDoneHandler { // done(b, from, end) - using CallbackType = bool (TReceiver::*)(T, const mtpPrime *, const mtpPrime *); - -public: - RPCBindedDoneHandlerBareOwned(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _b(b), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - return _owner - ? (static_cast(_owner)->*_onDone)(_b, from, end) - : true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCBindedDoneHandlerBareOwnedReq : public RPCOwnedDoneHandler { // done(b, from, end, req_id) - using CallbackType = bool (TReceiver::*)(T, const mtpPrime *, const mtpPrime *, mtpRequestId); - -public: - RPCBindedDoneHandlerBareOwnedReq(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _b(b), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - return _owner - ? (static_cast(_owner)->*_onDone)(_b, from, end, requestId) - : true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCBindedDoneHandlerOwned : public RPCOwnedDoneHandler { // done(b, result) - using CallbackType = TReturn (TReceiver::*)(T, const TResponse &); - -public: - RPCBindedDoneHandlerOwned(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone), _b(b) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - auto response = TResponse(); - if (!response.read(from, end)) { - return false; - } - if (_owner) { - (static_cast(_owner)->*_onDone)(_b, std::move(response)); - } - return true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCBindedDoneHandlerOwnedReq : public RPCOwnedDoneHandler { // done(b, result, req_id) - using CallbackType = TReturn (TReceiver::*)(T, const TResponse &, mtpRequestId); - -public: - RPCBindedDoneHandlerOwnedReq(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _onDone(onDone), _b(b) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - auto response = TResponse(); - if (!response.read(from, end)) { - return false; - } - if (_owner) { - (static_cast(_owner)->*_onDone)(_b, std::move(response), requestId); - } - return true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCBindedDoneHandlerOwnedNo : public RPCOwnedDoneHandler { // done(b) - using CallbackType = TReturn (TReceiver::*)(T); - -public: - RPCBindedDoneHandlerOwnedNo(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _b(b), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - if (_owner) (static_cast(_owner)->*_onDone)(_b); - return true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCBindedDoneHandlerOwnedNoReq : public RPCOwnedDoneHandler { // done(b, req_id) - using CallbackType = TReturn (TReceiver::*)(T, mtpRequestId); - -public: - RPCBindedDoneHandlerOwnedNoReq(T b, TReceiver *receiver, CallbackType onDone) : RPCOwnedDoneHandler(receiver), _b(b), _onDone(onDone) { - } - bool operator()(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end) override { - if (_owner) (static_cast(_owner)->*_onDone)(_b, requestId); - return true; - } - -private: - CallbackType _onDone; - T _b; - -}; - -template -class RPCFailHandlerOwned : public RPCOwnedFailHandler { // fail(error) - using CallbackType = bool (TReceiver::*)(const RPCError &); - -public: - RPCFailHandlerOwned(TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(e) : true; - } - -private: - CallbackType _onFail; - -}; - -template -class RPCFailHandlerOwnedReq : public RPCOwnedFailHandler { // fail(error, req_id) - using CallbackType = bool (TReceiver::*)(const RPCError &, mtpRequestId); - -public: - RPCFailHandlerOwnedReq(TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(e, requestId) : true; - } - -private: - CallbackType _onFail; - -}; - -template -class RPCFailHandlerOwnedNo : public RPCOwnedFailHandler { // fail() - using CallbackType = bool (TReceiver::*)(); - -public: - RPCFailHandlerOwnedNo(TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)() : true; - } - -private: - CallbackType _onFail; - -}; - -template -class RPCFailHandlerOwnedNoReq : public RPCOwnedFailHandler { // fail(req_id) - using CallbackType = bool (TReceiver::*)(mtpRequestId); - -public: - RPCFailHandlerOwnedNoReq(TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(requestId) : true; - } - -private: - CallbackType _onFail; - -}; - -template -class RPCBindedFailHandlerOwned : public RPCOwnedFailHandler { // fail(b, error) - using CallbackType = bool (TReceiver::*)(T, const RPCError &); - -public: - RPCBindedFailHandlerOwned(T b, TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail), _b(b) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(_b, e) : true; - } - -private: - CallbackType _onFail; - T _b; - -}; - -template -class RPCBindedFailHandlerOwnedReq : public RPCOwnedFailHandler { // fail(b, error, req_id) - using CallbackType = bool (TReceiver::*)(T, const RPCError &, mtpRequestId); - -public: - RPCBindedFailHandlerOwnedReq(T b, TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail), _b(b) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(_b, e, requestId) : true; - } - -private: - CallbackType _onFail; - T _b; - -}; - -template -class RPCBindedFailHandlerOwnedNo : public RPCOwnedFailHandler { // fail(b) - using CallbackType = bool (TReceiver::*)(T); - -public: - RPCBindedFailHandlerOwnedNo(T b, TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail), _b(b) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(_b) : true; - } - -private: - CallbackType _onFail; - T _b; - -}; - -template -class RPCBindedFailHandlerOwnedNoReq : public RPCOwnedFailHandler { // fail(b, req_id) - using CallbackType = bool (TReceiver::*)(T, mtpRequestId); - -public: - RPCBindedFailHandlerOwnedNoReq(T b, TReceiver *receiver, CallbackType onFail) : RPCOwnedFailHandler(receiver), _onFail(onFail), _b(b) { - } - bool operator()(mtpRequestId requestId, const RPCError &e) override { - return _owner ? (static_cast(_owner)->*_onFail)(_b, requestId) : true; - } - -private: - CallbackType _onFail; - T _b; - -}; - -class RPCSender { -public: - template // done(from, end) - RPCDoneHandlerPtr rpcDone(bool (TReceiver::*onDone)(const mtpPrime *, const mtpPrime *)) { - return RPCDoneHandlerPtr(new RPCDoneHandlerBareOwned(static_cast(this), onDone)); - } - - template // done(from, end, req_id) - RPCDoneHandlerPtr rpcDone(bool (TReceiver::*onDone)(const mtpPrime *, const mtpPrime *, mtpRequestId)) { - return RPCDoneHandlerPtr(new RPCDoneHandlerBareOwnedReq(static_cast(this), onDone)); - } - - template // done(result) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(const TResponse &)) { - return RPCDoneHandlerPtr(new RPCDoneHandlerOwned(static_cast(this), onDone)); - } - - template // done(result, req_id) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(const TResponse &, mtpRequestId)) { - return RPCDoneHandlerPtr(new RPCDoneHandlerOwnedReq(static_cast(this), onDone)); - } - - template // done() - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)()) { - return RPCDoneHandlerPtr(new RPCDoneHandlerOwnedNo(static_cast(this), onDone)); - } - - template // done(req_id) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(mtpRequestId)) { - return RPCDoneHandlerPtr(new RPCDoneHandlerOwnedNoReq(static_cast(this), onDone)); - } - - template // fail(error) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(const RPCError &)) { - return RPCFailHandlerPtr(new RPCFailHandlerOwned(static_cast(this), onFail)); - } - - template // fail(error, req_id) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(const RPCError &, mtpRequestId)) { - return RPCFailHandlerPtr(new RPCFailHandlerOwnedReq(static_cast(this), onFail)); - } - - template // fail() - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)()) { - return RPCFailHandlerPtr(new RPCFailHandlerOwnedNo(static_cast(this), onFail)); - } - - template // fail(req_id) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(mtpRequestId)) { - return RPCFailHandlerPtr(new RPCFailHandlerOwnedNo(static_cast(this), onFail)); - } - - template // done(b, from, end) - RPCDoneHandlerPtr rpcDone(bool (TReceiver::*onDone)(T, const mtpPrime *, const mtpPrime *), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerBareOwned(b, static_cast(this), onDone)); - } - - template // done(b, from, end, req_id) - RPCDoneHandlerPtr rpcDone(bool (TReceiver::*onDone)(T, const mtpPrime *, const mtpPrime *, mtpRequestId), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerBareOwnedReq(b, static_cast(this), onDone)); - } - - template // done(b, result) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(T, const TResponse &), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerOwned(b, static_cast(this), onDone)); - } - - template // done(b, result, req_id) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(T, const TResponse &, mtpRequestId), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerOwnedReq(b, static_cast(this), onDone)); - } - - template // done(b) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(T), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerOwnedNo(b, static_cast(this), onDone)); - } - - template // done(b, req_id) - RPCDoneHandlerPtr rpcDone(TReturn (TReceiver::*onDone)(T, mtpRequestId), T b) { - return RPCDoneHandlerPtr(new RPCBindedDoneHandlerOwnedNoReq(b, static_cast(this), onDone)); - } - - template // fail(b, error) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(T, const RPCError &), T b) { - return RPCFailHandlerPtr(new RPCBindedFailHandlerOwned(b, static_cast(this), onFail)); - } - - template // fail(b, error, req_id) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(T, const RPCError &, mtpRequestId), T b) { - return RPCFailHandlerPtr(new RPCBindedFailHandlerOwnedReq(b, static_cast(this), onFail)); - } - - template // fail(b) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(T), T b) { - return RPCFailHandlerPtr(new RPCBindedFailHandlerOwnedNo(b, static_cast(this), onFail)); - } - - template // fail(b, req_id) - RPCFailHandlerPtr rpcFail(bool (TReceiver::*onFail)(T, mtpRequestId), T b) { - return RPCFailHandlerPtr(new RPCBindedFailHandlerOwnedNo(b, static_cast(this), onFail)); - } - - virtual void rpcClear() { - rpcInvalidate(); - } - - virtual ~RPCSender() { - rpcInvalidate(); - } - -protected: - void rpcInvalidate() { - for (auto handler : base::take(_rpcDoneHandlers)) { - handler->invalidate(); - } - for (auto handler : base::take(_rpcFailHandlers)) { - handler->invalidate(); - } - } - -private: - base::flat_set _rpcDoneHandlers; - base::flat_set _rpcFailHandlers; - - void rpcRegHandler(RPCOwnedDoneHandler *handler) { - _rpcDoneHandlers.emplace(handler); - } - - void rpcUnregHandler(RPCOwnedDoneHandler *handler) { - _rpcDoneHandlers.remove(handler); - } - - void rpcRegHandler(RPCOwnedFailHandler *handler) { - _rpcFailHandlers.emplace(handler); - } - - void rpcUnregHandler(RPCOwnedFailHandler *handler) { - _rpcFailHandlers.remove(handler); - } - - friend class RPCOwnedDoneHandler; - friend class RPCOwnedFailHandler; - -}; - using MTPStateChangedHandler = void (*)(int32 dcId, int32 state); using MTPSessionResetHandler = void (*)(int32 dcId); diff --git a/Telegram/SourceFiles/mtproto/sender.h b/Telegram/SourceFiles/mtproto/sender.h index da96ff478..189121f1f 100644 --- a/Telegram/SourceFiles/mtproto/sender.h +++ b/Telegram/SourceFiles/mtproto/sender.h @@ -300,7 +300,7 @@ public: _instance->sendAnything(); } void requestCancellingDiscard() { - for (auto &request : _requests) { + for (auto &request : base::take(_requests)) { request.handled(); } } @@ -309,16 +309,21 @@ private: class RequestWrap { public: RequestWrap( - Instance *instance, + not_null instance, mtpRequestId requestId) noexcept - : _id(requestId) { + : _instance(instance) + , _id(requestId) { } RequestWrap(const RequestWrap &other) = delete; RequestWrap &operator=(const RequestWrap &other) = delete; - RequestWrap(RequestWrap &&other) : _id(base::take(other._id)) { + RequestWrap(RequestWrap &&other) + : _instance(other._instance) + , _id(base::take(other._id)) { } RequestWrap &operator=(RequestWrap &&other) { + Expects(_instance == other._instance); + if (_id != other._id) { cancelRequest(); _id = base::take(other._id); @@ -330,6 +335,7 @@ private: return _id; } void handled() const noexcept { + _id = 0; } ~RequestWrap() { @@ -339,12 +345,11 @@ private: private: void cancelRequest() { if (_id) { - if (auto instance = MainInstance()) { - instance->cancel(_id); - } + _instance->cancel(_id); } } - mtpRequestId _id = 0; + const not_null _instance; + mutable mtpRequestId _id = 0; }; @@ -377,7 +382,7 @@ private: friend class SentRequestWrap; void senderRequestRegister(mtpRequestId requestId) { - _requests.emplace(MainInstance(), requestId); + _requests.emplace(_instance, requestId); } void senderRequestHandled(mtpRequestId requestId) { auto it = _requests.find(requestId); diff --git a/Telegram/SourceFiles/passport/passport_form_controller.cpp b/Telegram/SourceFiles/passport/passport_form_controller.cpp index fed55c489..386ae43a9 100644 --- a/Telegram/SourceFiles/passport/passport_form_controller.cpp +++ b/Telegram/SourceFiles/passport/passport_form_controller.cpp @@ -30,7 +30,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/file_upload.h" #include "storage/file_download_mtproto.h" #include "app.h" -#include "apiwrap.h" #include #include @@ -625,7 +624,7 @@ FormController::FormController( not_null controller, const FormRequest &request) : _controller(controller) -, _api(_controller->session().api().instance()) +, _api(_controller->session().mtp()) , _request(PreprocessRequest(request)) , _shortPollTimer([=] { reloadPassword(); }) , _view(std::make_unique(this)) { @@ -1001,6 +1000,7 @@ void FormController::recoverPassword() { const auto &data = result.c_auth_passwordRecovery(); const auto pattern = qs(data.vemail_pattern()); const auto box = _view->show(Box( + &_controller->session(), pattern, _password.notEmptyPassport)); @@ -1424,7 +1424,7 @@ void FormController::prepareFile( const auto fileId = rand_value(); file.fields.size = content.size(); file.fields.id = fileId; - file.fields.dcId = MTP::maindc(); + file.fields.dcId = _controller->session().mainDcId(); file.fields.secret = GenerateSecretBytes(); file.fields.date = base::unixtime::now(); file.fields.image = ReadImage(bytes::make_span(content)); diff --git a/Telegram/SourceFiles/passport/passport_panel_controller.cpp b/Telegram/SourceFiles/passport/passport_panel_controller.cpp index 4e0cf1568..bbd1f284f 100644 --- a/Telegram/SourceFiles/passport/passport_panel_controller.cpp +++ b/Telegram/SourceFiles/passport/passport_panel_controller.cpp @@ -723,7 +723,9 @@ void PanelController::cancelPasswordSubmit() { } void PanelController::validateRecoveryEmail() { - auto validation = ConfirmRecoveryEmail(unconfirmedEmailPattern()); + auto validation = ConfirmRecoveryEmail( + &_form->session(), + unconfirmedEmailPattern()); std::move( validation.reloadRequests diff --git a/Telegram/SourceFiles/settings/settings_advanced.cpp b/Telegram/SourceFiles/settings/settings_advanced.cpp index 2c12dc312..c55b7047e 100644 --- a/Telegram/SourceFiles/settings/settings_advanced.cpp +++ b/Telegram/SourceFiles/settings/settings_advanced.cpp @@ -26,6 +26,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/application.h" #include "storage/localstorage.h" #include "data/data_session.h" +#include "main/main_account.h" #include "main/main_session.h" #include "mtproto/facade.h" #include "layout.h" @@ -55,8 +56,10 @@ void SetupConnectionType( return; } #ifndef TDESKTOP_DISABLE_NETWORK_PROXY - const auto connectionType = [] { - const auto transport = MTP::dctransport(); + const auto connectionType = [=] { + const auto transport = account->mtp() + ? account->mtp()->dctransport() + : QString(); if (Global::ProxySettings() != MTP::ProxyData::Settings::Enabled) { return transport.isEmpty() ? tr::lng_connection_auto_connecting(tr::now) diff --git a/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp b/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp index c4c0446ff..97a1ab4bb 100644 --- a/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp +++ b/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp @@ -180,7 +180,7 @@ AdminLog::OwnedItem GenerateForwardedItem( BlockedBoxController::BlockedBoxController( not_null window) : _window(window) -, _api(_window->session().api().instance()) { +, _api(_window->session().mtp()) { } Main::Session &BlockedBoxController::session() const { diff --git a/Telegram/SourceFiles/settings/settings_privacy_security.cpp b/Telegram/SourceFiles/settings/settings_privacy_security.cpp index eb39295cf..24bc5bdaa 100644 --- a/Telegram/SourceFiles/settings/settings_privacy_security.cpp +++ b/Telegram/SourceFiles/settings/settings_privacy_security.cpp @@ -366,7 +366,9 @@ void SetupCloudPassword( if (!state) { return; } - auto validation = ConfirmRecoveryEmail(state->unconfirmedPattern); + auto validation = ConfirmRecoveryEmail( + &controller->session(), + state->unconfirmedPattern); std::move( validation.reloadRequests diff --git a/Telegram/SourceFiles/storage/download_manager_mtproto.cpp b/Telegram/SourceFiles/storage/download_manager_mtproto.cpp index e0f5d7e37..621ec8e00 100644 --- a/Telegram/SourceFiles/storage/download_manager_mtproto.cpp +++ b/Telegram/SourceFiles/storage/download_manager_mtproto.cpp @@ -353,7 +353,7 @@ void DownloadManagerMtproto::removeSession(MTP::DcId dcId) { Assert(session.requested == kMaxWaitedInSession * kMaxSessionsCount); dc.sessions.pop_back(); - MTP::killSession(MTP::downloadDcId(dcId, index)); + api().instance()->killSession(MTP::downloadDcId(dcId, index)); dc.lastSessionRemove = crl::now(); } @@ -403,7 +403,7 @@ void DownloadManagerMtproto::killSessions(MTP::DcId dcId) { for (auto j = 0; j != int(sessions.size()); ++j) { Assert(sessions[j].requested == 0); sessions[j] = DcSessionBalanceData(); - MTP::stopSession(MTP::downloadDcId(dcId, j)); + api().instance()->stopSession(MTP::downloadDcId(dcId, j)); } dc.sessions = base::take(sessions); } diff --git a/Telegram/SourceFiles/storage/file_upload.h b/Telegram/SourceFiles/storage/file_upload.h index df1e2b366..b42ecc4eb 100644 --- a/Telegram/SourceFiles/storage/file_upload.h +++ b/Telegram/SourceFiles/storage/file_upload.h @@ -59,7 +59,7 @@ struct UploadSecureDone { int partsCount = 0; }; -class Uploader : public QObject, public RPCSender { +class Uploader final : public QObject { Q_OBJECT public: diff --git a/Telegram/SourceFiles/storage/localimageloader.cpp b/Telegram/SourceFiles/storage/localimageloader.cpp index 05e86f343..40337cb7b 100644 --- a/Telegram/SourceFiles/storage/localimageloader.cpp +++ b/Telegram/SourceFiles/storage/localimageloader.cpp @@ -186,7 +186,7 @@ SendMediaReady::SendMediaReady( } } -SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image) { +SendMediaReady PreparePeerPhoto(MTP::DcId dcId, PeerId peerId, QImage &&image) { PreparedPhotoThumbs photoThumbs; QVector photoSizes; @@ -221,7 +221,7 @@ SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image) { MTP_bytes(), MTP_int(base::unixtime::now()), MTP_vector(photoSizes), - MTP_int(MTP::maindc())); + MTP_int(dcId)); QString file, filename; int32 filesize = 0; @@ -476,6 +476,7 @@ void FileLoadResult::setThumbData(const QByteArray &thumbdata) { FileLoadTask::FileLoadTask( + MTP::DcId dcId, const QString &filepath, const QByteArray &content, std::unique_ptr information, @@ -485,6 +486,7 @@ FileLoadTask::FileLoadTask( std::shared_ptr album, MsgId msgIdToEdit) : _id(rand_value()) +, _dcId(dcId) , _to(to) , _album(std::move(album)) , _filepath(filepath) @@ -497,12 +499,14 @@ FileLoadTask::FileLoadTask( } FileLoadTask::FileLoadTask( + MTP::DcId dcId, const QByteArray &voice, int32 duration, const VoiceWaveform &waveform, const FileLoadTo &to, const TextWithTags &caption) : _id(rand_value()) +, _dcId(dcId) , _to(to) , _content(voice) , _duration(duration) @@ -876,7 +880,7 @@ void FileLoadTask::process() { MTP_bytes(), MTP_int(base::unixtime::now()), MTP_vector(photoSizes), - MTP_int(MTP::maindc())); + MTP_int(_dcId)); if (filesize < 0) { filesize = _result->filesize = filedata.size(); @@ -909,7 +913,7 @@ void FileLoadTask::process() { MTP_int(filesize), MTP_vector(1, thumbnail.mtpSize), MTPVector(), - MTP_int(MTP::maindc()), + MTP_int(_dcId), MTP_vector(attributes)); } else if (_type != SendMediaType::Photo) { document = MTP_document( @@ -922,7 +926,7 @@ void FileLoadTask::process() { MTP_int(filesize), MTP_vector(1, thumbnail.mtpSize), MTPVector(), - MTP_int(MTP::maindc()), + MTP_int(_dcId), MTP_vector(attributes)); _type = SendMediaType::File; } diff --git a/Telegram/SourceFiles/storage/localimageloader.h b/Telegram/SourceFiles/storage/localimageloader.h index 029b71637..cd0c41d68 100644 --- a/Telegram/SourceFiles/storage/localimageloader.h +++ b/Telegram/SourceFiles/storage/localimageloader.h @@ -84,7 +84,7 @@ struct SendMediaReady { }; -SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image); +SendMediaReady PreparePeerPhoto(MTP::DcId dcId, PeerId peerId, QImage &&image); using TaskId = void*; // no interface, just id @@ -270,6 +270,7 @@ public: std::unique_ptr &result); FileLoadTask( + MTP::DcId dcId, const QString &filepath, const QByteArray &content, std::unique_ptr information, @@ -279,6 +280,7 @@ public: std::shared_ptr album = nullptr, MsgId msgIdToEdit = 0); FileLoadTask( + MTP::DcId dcId, const QByteArray &voice, int32 duration, const VoiceWaveform &waveform, @@ -316,7 +318,8 @@ private: } void removeFromAlbum(); - uint64 _id; + uint64 _id = 0; + MTP::DcId _dcId = 0; FileLoadTo _to; const std::shared_ptr _album; QString _filepath; diff --git a/Telegram/SourceFiles/support/support_helper.cpp b/Telegram/SourceFiles/support/support_helper.cpp index ec0d39582..d79a5ef23 100644 --- a/Telegram/SourceFiles/support/support_helper.cpp +++ b/Telegram/SourceFiles/support/support_helper.cpp @@ -289,7 +289,7 @@ TimeId OccupiedBySomeoneTill(History *history) { Helper::Helper(not_null session) : _session(session) -, _api(_session->api().instance()) +, _api(_session->mtp()) , _templates(_session) , _reoccupyTimer([=] { reoccupy(); }) , _checkOccupiedTimer([=] { checkOccupiedChats(); }) { diff --git a/Telegram/SourceFiles/window/themes/window_theme.cpp b/Telegram/SourceFiles/window/themes/window_theme.cpp index 10addd66e..9f9670e25 100644 --- a/Telegram/SourceFiles/window/themes/window_theme.cpp +++ b/Telegram/SourceFiles/window/themes/window_theme.cpp @@ -439,7 +439,7 @@ void ClearApplying() { GlobalApplying = Applying(); } -SendMediaReady PrepareWallPaper(const QImage &image) { +SendMediaReady PrepareWallPaper(MTP::DcId dcId, const QImage &image) { PreparedPhotoThumbs thumbnails; QVector sizes; @@ -482,7 +482,7 @@ SendMediaReady PrepareWallPaper(const QImage &image) { MTP_int(jpeg.size()), MTP_vector(sizes), MTPVector(), - MTP_int(MTP::maindc()), + MTP_int(dcId), MTP_vector(attributes)); return SendMediaReady( @@ -575,7 +575,7 @@ void ChatBackground::checkUploadWallPaper() { return; } - const auto ready = PrepareWallPaper(_original); + const auto ready = PrepareWallPaper(_session->mainDcId(), _original); const auto documentId = ready.id; _wallPaperUploadId = FullMsgId(0, _session->data().nextLocalMessageId()); _session->uploader().uploadMedia(_wallPaperUploadId, ready); diff --git a/Telegram/SourceFiles/window/themes/window_theme_editor_box.cpp b/Telegram/SourceFiles/window/themes/window_theme_editor_box.cpp index c3d61e6a0..a28f14e59 100644 --- a/Telegram/SourceFiles/window/themes/window_theme_editor_box.cpp +++ b/Telegram/SourceFiles/window/themes/window_theme_editor_box.cpp @@ -410,6 +410,7 @@ bool CopyColorsToPalette( } SendMediaReady PrepareThemeMedia( + MTP::DcId dcId, const QString &name, const QByteArray &content) { PreparedPhotoThumbs thumbnails; @@ -452,7 +453,7 @@ SendMediaReady PrepareThemeMedia( MTP_int(content.size()), MTP_vector(sizes), MTPVector(), - MTP_int(MTP::maindc()), + MTP_int(dcId), MTP_vector(attributes)); return SendMediaReady( @@ -585,7 +586,10 @@ Fn SavePreparedTheme( }; const auto uploadFile = [=](const QByteArray &theme) { - const auto media = PrepareThemeMedia(fields.title, theme); + const auto media = PrepareThemeMedia( + session->mainDcId(), + fields.title, + theme); state->filename = media.filename; state->themeContent = theme; diff --git a/Telegram/SourceFiles/window/window_connecting_widget.cpp b/Telegram/SourceFiles/window/window_connecting_widget.cpp index 83813f435..a84b45df1 100644 --- a/Telegram/SourceFiles/window/window_connecting_widget.cpp +++ b/Telegram/SourceFiles/window/window_connecting_widget.cpp @@ -10,7 +10,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/buttons.h" #include "ui/effects/radial_animation.h" #include "ui/ui_utility.h" +#include "mtproto/mtp_instance.h" #include "mtproto/facade.h" +#include "main/main_account.h" #include "core/update_checker.h" #include "window/themes/window_theme.h" #include "boxes/connection_box.h" @@ -101,6 +103,7 @@ private: QRect contentRect() const; QRect textRect() const; + const not_null _account; Layout _currentLayout; base::unique_qptr _retry; QPointer _progress; @@ -287,7 +290,9 @@ void ConnectionState::refreshState() { const auto state = [&]() -> State { const auto under = _widget && _widget->isOver(); const auto ready = (Checker().state() == Checker::State::Ready); - const auto mtp = MTP::dcstate(); + const auto mtp = _account->mtp() + ? _account->mtp()->dcstate() + : MTP::DisconnectedState; const auto proxy = (Global::ProxySettings() == MTP::ProxyData::Settings::Enabled); if (mtp == MTP::ConnectingState @@ -479,6 +484,7 @@ ConnectionState::Widget::Widget( not_null account, const Layout &layout) : AbstractButton(parent) +, _account(account) , _currentLayout(layout) { _proxyIcon = Ui::CreateChild(this); _progress = Ui::CreateChild(this); @@ -611,7 +617,9 @@ void ConnectionState::Widget::refreshRetryLink(bool hasRetry) { tr::lng_reconnecting_try_now(tr::now), st::connectingRetryLink); _retry->addClickHandler([=] { - MTP::restart(); + if (const auto mtproto = _account->mtp()) { + mtproto->restart(); + } }); updateRetryGeometry(); } else if (!hasRetry) {