Pass MTP::Instance to MTP::Sender.

This commit is contained in:
John Preston 2019-11-27 11:02:56 +03:00
parent a0152557ec
commit e943264823
65 changed files with 406 additions and 275 deletions

View File

@ -40,6 +40,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
//#include "history/feed/history_feed_section.h" // #feed //#include "history/feed/history_feed_section.h" // #feed
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "main/main_session.h" #include "main/main_session.h"
#include "main/main_account.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "boxes/stickers_box.h" #include "boxes/stickers_box.h"
#include "boxes/sticker_set_box.h" #include "boxes/sticker_set_box.h"
@ -222,7 +223,8 @@ bool ApiWrap::BlockedUsersSlice::operator!=(const BlockedUsersSlice &other) cons
} }
ApiWrap::ApiWrap(not_null<Main::Session*> session) ApiWrap::ApiWrap(not_null<Main::Session*> session)
: _session(session) : MTP::Sender(session->account().mtp())
, _session(session)
, _messageDataResolveDelayed([=] { resolveMessageDatas(); }) , _messageDataResolveDelayed([=] { resolveMessageDatas(); })
, _webPagesTimer([=] { resolveWebPages(); }) , _webPagesTimer([=] { resolveWebPages(); })
, _draftsSaveTimer([=] { saveDraftsToCloud(); }) , _draftsSaveTimer([=] { saveDraftsToCloud(); })

View File

@ -203,7 +203,7 @@ void ShowAddParticipantsError(
Ui::show(Box<InformBox>(text), Ui::LayerOption::KeepOther); Ui::show(Box<InformBox>(text), Ui::LayerOption::KeepOther);
} }
class RevokePublicLinkBox::Inner : public TWidget, private MTP::Sender { class RevokePublicLinkBox::Inner : public TWidget {
public: public:
Inner( Inner(
QWidget *parent, QWidget *parent,
@ -228,6 +228,7 @@ private:
void updateSelected(); void updateSelected();
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
PeerData *_selected = nullptr; PeerData *_selected = nullptr;
PeerData *_pressed = nullptr; PeerData *_pressed = nullptr;
@ -450,6 +451,7 @@ GroupInfoBox::GroupInfoBox(
const QString &title, const QString &title,
Fn<void(not_null<ChannelData*>)> channelDone) Fn<void(not_null<ChannelData*>)> channelDone)
: _navigation(navigation) : _navigation(navigation)
, _api(_navigation->session().api().instance())
, _type(type) , _type(type)
, _initialTitle(title) , _initialTitle(title)
, _channelDone(std::move(channelDone)) { , _channelDone(std::move(channelDone)) {
@ -569,7 +571,7 @@ void GroupInfoBox::createGroup(
if (inputs.empty()) { if (inputs.empty()) {
return; return;
} }
_creationRequestId = request(MTPmessages_CreateChat( _creationRequestId = _api.request(MTPmessages_CreateChat(
MTP_vector<MTPInputUser>(inputs), MTP_vector<MTPInputUser>(inputs),
MTP_string(title) MTP_string(title)
)).done([=](const MTPUpdates &result) { )).done([=](const MTPUpdates &result) {
@ -645,7 +647,7 @@ void GroupInfoBox::createChannel(const QString &title, const QString &descriptio
const auto flags = (_type == Type::Megagroup) const auto flags = (_type == Type::Megagroup)
? MTPchannels_CreateChannel::Flag::f_megagroup ? MTPchannels_CreateChannel::Flag::f_megagroup
: MTPchannels_CreateChannel::Flag::f_broadcast; : MTPchannels_CreateChannel::Flag::f_broadcast;
_creationRequestId = request(MTPchannels_CreateChannel( _creationRequestId = _api.request(MTPchannels_CreateChannel(
MTP_flags(flags), MTP_flags(flags),
MTP_string(title), MTP_string(title),
MTP_string(description), MTP_string(description),
@ -682,7 +684,7 @@ void GroupInfoBox::createChannel(const QString &title, const QString &descriptio
std::move(image)); std::move(image));
} }
_createdChannel = channel; _createdChannel = channel;
_creationRequestId = request(MTPmessages_ExportChatInvite( _creationRequestId = _api.request(MTPmessages_ExportChatInvite(
_createdChannel->input _createdChannel->input
)).done([=](const MTPExportedChatInvite &result) { )).done([=](const MTPExportedChatInvite &result) {
_creationRequestId = 0; _creationRequestId = 0;
@ -1287,6 +1289,7 @@ RevokePublicLinkBox::Inner::Inner(
Fn<void()> revokeCallback) Fn<void()> revokeCallback)
: TWidget(parent) : TWidget(parent)
, _session(session) , _session(session)
, _api(_session->api().instance())
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom())
, _revokeWidth(st::normalFont->width(tr::lng_channels_too_much_public_revoke(tr::now))) , _revokeWidth(st::normalFont->width(tr::lng_channels_too_much_public_revoke(tr::now)))
, _revokeCallback(std::move(revokeCallback)) { , _revokeCallback(std::move(revokeCallback)) {
@ -1294,7 +1297,7 @@ RevokePublicLinkBox::Inner::Inner(
resize(width(), 5 * _rowHeight); resize(width(), 5 * _rowHeight);
request(MTPchannels_GetAdminedPublicChannels( _api.request(MTPchannels_GetAdminedPublicChannels(
MTP_flags(0) MTP_flags(0)
)).done([=](const MTPmessages_Chats &result) { )).done([=](const MTPmessages_Chats &result) {
const auto &chats = result.match([](const auto &data) { const auto &chats = result.match([](const auto &data) {
@ -1401,7 +1404,7 @@ void RevokePublicLinkBox::Inner::mouseReleaseEvent(QMouseEvent *e) {
auto confirmText = tr::lng_channels_too_much_public_revoke(tr::now); auto confirmText = tr::lng_channels_too_much_public_revoke(tr::now);
_weakRevokeConfirmBox = Ui::show(Box<ConfirmBox>(text, confirmText, crl::guard(this, [this, pressed]() { _weakRevokeConfirmBox = Ui::show(Box<ConfirmBox>(text, confirmText, crl::guard(this, [this, pressed]() {
if (_revokeRequestId) return; if (_revokeRequestId) return;
_revokeRequestId = request(MTPchannels_UpdateUsername( _revokeRequestId = _api.request(MTPchannels_UpdateUsername(
pressed->asChannel()->inputChannel, pressed->asChannel()->inputChannel,
MTP_string() MTP_string()
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {

View File

@ -94,7 +94,7 @@ private:
}; };
class GroupInfoBox : public Ui::BoxContent, private MTP::Sender { class GroupInfoBox : public Ui::BoxContent {
public: public:
enum class Type { enum class Type {
Group, Group,
@ -124,6 +124,7 @@ private:
void updateMaxHeight(); void updateMaxHeight();
const not_null<Window::SessionNavigation*> _navigation; const not_null<Window::SessionNavigation*> _navigation;
MTP::Sender _api;
Type _type = Type::Group; Type _type = Type::Group;
QString _initialTitle; QString _initialTitle;

View File

@ -53,10 +53,7 @@ QImage TakeMiddleSample(QImage original, QSize size) {
} // namespace } // namespace
class BackgroundBox::Inner class BackgroundBox::Inner : public Ui::RpWidget, private base::Subscriber {
: public Ui::RpWidget
, private MTP::Sender
, private base::Subscriber {
public: public:
Inner( Inner(
QWidget *parent, QWidget *parent,
@ -114,6 +111,7 @@ private:
void validatePaperThumbnail(const Paper &paper) const; void validatePaperThumbnail(const Paper &paper) const;
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
std::vector<Paper> _papers; std::vector<Paper> _papers;
@ -185,6 +183,7 @@ BackgroundBox::Inner::Inner(
not_null<Main::Session*> session) not_null<Main::Session*> session)
: RpWidget(parent) : RpWidget(parent)
, _session(session) , _session(session)
, _api(_session->api().instance())
, _check(std::make_unique<Ui::RoundCheckbox>(st::overviewCheck, [=] { update(); })) { , _check(std::make_unique<Ui::RoundCheckbox>(st::overviewCheck, [=] { update(); })) {
_check->setChecked(true, Ui::RoundCheckbox::SetStyle::Fast); _check->setChecked(true, Ui::RoundCheckbox::SetStyle::Fast);
if (_session->data().wallpapers().empty()) { if (_session->data().wallpapers().empty()) {
@ -209,7 +208,7 @@ BackgroundBox::Inner::Inner(
} }
void BackgroundBox::Inner::requestPapers() { void BackgroundBox::Inner::requestPapers() {
request(MTPaccount_GetWallPapers( _api.request(MTPaccount_GetWallPapers(
MTP_int(_session->data().wallpapersHash()) MTP_int(_session->data().wallpapersHash())
)).done([=](const MTPaccount_WallPapers &result) { )).done([=](const MTPaccount_WallPapers &result) {
if (_session->data().updateWallpapers(result)) { if (_session->data().updateWallpapers(result)) {

View File

@ -100,7 +100,7 @@ private:
}; };
class EditPrivacyBox : public Ui::BoxContent, private MTP::Sender { class EditPrivacyBox : public Ui::BoxContent {
public: public:
using Value = ApiWrap::Privacy; using Value = ApiWrap::Privacy;
using Option = Value::Option; using Option = Value::Option;

View File

@ -12,6 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "boxes/confirm_phone_box.h" #include "boxes/confirm_phone_box.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "apiwrap.h"
#include "main/main_session.h" #include "main/main_session.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
@ -47,6 +48,7 @@ PasscodeBox::PasscodeBox(
not_null<Main::Session*> session, not_null<Main::Session*> session,
bool turningOff) bool turningOff)
: _session(session) : _session(session)
, _api(_session->api().instance())
, _turningOff(turningOff) , _turningOff(turningOff)
, _about(st::boxWidth - st::boxPadding.left() * 1.5) , _about(st::boxWidth - st::boxPadding.left() * 1.5)
, _oldPasscode(this, st::defaultInputField, tr::lng_passcode_enter_old()) , _oldPasscode(this, st::defaultInputField, tr::lng_passcode_enter_old())
@ -62,6 +64,7 @@ PasscodeBox::PasscodeBox(
not_null<Main::Session*> session, not_null<Main::Session*> session,
const CloudFields &fields) const CloudFields &fields)
: _session(session) : _session(session)
, _api(_session->api().instance())
, _turningOff(fields.turningOff) , _turningOff(fields.turningOff)
, _cloudPwd(true) , _cloudPwd(true)
, _cloudFields(fields) , _cloudFields(fields)
@ -357,7 +360,7 @@ void PasscodeBox::validateEmail(
if (_setRequest) { if (_setRequest) {
return; return;
} }
_setRequest = request(MTPaccount_ConfirmPasswordEmail( _setRequest = _api.request(MTPaccount_ConfirmPasswordEmail(
MTP_string(code) MTP_string(code)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
*set = true; *set = true;
@ -387,7 +390,7 @@ void PasscodeBox::validateEmail(
if (_setRequest) { if (_setRequest) {
return; return;
} }
_setRequest = request(MTPaccount_ResendPasswordEmail( _setRequest = _api.request(MTPaccount_ResendPasswordEmail(
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
_setRequest = 0; _setRequest = 0;
resent->fire(tr::lng_cloud_password_resent(tr::now)); resent->fire(tr::lng_cloud_password_resent(tr::now));
@ -597,8 +600,8 @@ void PasscodeBox::requestPasswordData() {
return serverError(); return serverError();
} }
request(base::take(_setRequest)).cancel(); _api.request(base::take(_setRequest)).cancel();
_setRequest = request( _setRequest = _api.request(
MTPaccount_GetPassword() MTPaccount_GetPassword()
).done([=](const MTPaccount_Password &result) { ).done([=](const MTPaccount_Password &result) {
_setRequest = 0; _setRequest = 0;
@ -636,7 +639,7 @@ void PasscodeBox::sendClearCloudPassword(
| MTPDaccount_passwordInputSettings::Flag::f_new_password_hash | MTPDaccount_passwordInputSettings::Flag::f_new_password_hash
| MTPDaccount_passwordInputSettings::Flag::f_hint | MTPDaccount_passwordInputSettings::Flag::f_hint
| MTPDaccount_passwordInputSettings::Flag::f_email; | MTPDaccount_passwordInputSettings::Flag::f_email;
_setRequest = request(MTPaccount_UpdatePasswordSettings( _setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
check.result, check.result,
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(flags), MTP_flags(flags),
@ -667,7 +670,7 @@ void PasscodeBox::setNewCloudPassword(const QString &newPassword) {
| MTPDaccount_passwordInputSettings::Flag::f_hint | MTPDaccount_passwordInputSettings::Flag::f_hint
| MTPDaccount_passwordInputSettings::Flag::f_email; | MTPDaccount_passwordInputSettings::Flag::f_email;
_checkPasswordCallback = nullptr; _checkPasswordCallback = nullptr;
_setRequest = request(MTPaccount_UpdatePasswordSettings( _setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
MTP_inputCheckPasswordEmpty(), MTP_inputCheckPasswordEmpty(),
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(flags), MTP_flags(flags),
@ -695,7 +698,7 @@ void PasscodeBox::changeCloudPassword(
const QString &oldPassword, const QString &oldPassword,
const Core::CloudPasswordResult &check, const Core::CloudPasswordResult &check,
const QString &newPassword) { const QString &newPassword) {
_setRequest = request(MTPaccount_GetPasswordSettings( _setRequest = _api.request(MTPaccount_GetPasswordSettings(
check.result check.result
)).done([=](const MTPaccount_PasswordSettings &result) { )).done([=](const MTPaccount_PasswordSettings &result) {
_setRequest = 0; _setRequest = 0;
@ -760,7 +763,7 @@ void PasscodeBox::resetSecret(
const QString &newPassword, const QString &newPassword,
Fn<void()> callback) { Fn<void()> callback) {
using Flag = MTPDaccount_passwordInputSettings::Flag; using Flag = MTPDaccount_passwordInputSettings::Flag;
_setRequest = request(MTPaccount_UpdatePasswordSettings( _setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
check.result, check.result,
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(Flag::f_new_secure_settings), MTP_flags(Flag::f_new_secure_settings),
@ -814,7 +817,7 @@ void PasscodeBox::sendChangeCloudPassword(
_cloudFields.newSecureSecretAlgo, _cloudFields.newSecureSecretAlgo,
bytes::make_span(newPasswordBytes))); bytes::make_span(newPasswordBytes)));
} }
_setRequest = request(MTPaccount_UpdatePasswordSettings( _setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
check.result, check.result,
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(flags), MTP_flags(flags),
@ -873,7 +876,7 @@ void PasscodeBox::emailChanged() {
void PasscodeBox::recoverByEmail() { void PasscodeBox::recoverByEmail() {
if (_pattern.isEmpty()) { if (_pattern.isEmpty()) {
_pattern = "-"; _pattern = "-";
request(MTPauth_RequestPasswordRecovery( _api.request(MTPauth_RequestPasswordRecovery(
)).done([=](const MTPauth_PasswordRecovery &result) { )).done([=](const MTPauth_PasswordRecovery &result) {
recoverStarted(result); recoverStarted(result);
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {

View File

@ -25,7 +25,7 @@ namespace Core {
struct CloudPasswordState; struct CloudPasswordState;
} // namespace Core } // namespace Core
class PasscodeBox : public Ui::BoxContent, private MTP::Sender { class PasscodeBox : public Ui::BoxContent {
public: public:
PasscodeBox(QWidget*, not_null<Main::Session*> session, bool turningOff); PasscodeBox(QWidget*, not_null<Main::Session*> session, bool turningOff);
@ -130,6 +130,7 @@ private:
void serverError(); void serverError();
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
QString _pattern; QString _pattern;

View File

@ -142,7 +142,8 @@ void PeerListRowWithLink::paintAction(
PeerListGlobalSearchController::PeerListGlobalSearchController( PeerListGlobalSearchController::PeerListGlobalSearchController(
not_null<Window::SessionNavigation*> navigation) not_null<Window::SessionNavigation*> navigation)
: _navigation(navigation) { : _navigation(navigation)
, _api(_navigation->session().api().instance()) {
_timer.setCallback([this] { searchOnServer(); }); _timer.setCallback([this] { searchOnServer(); });
} }
@ -169,7 +170,7 @@ bool PeerListGlobalSearchController::searchInCache() {
} }
void PeerListGlobalSearchController::searchOnServer() { void PeerListGlobalSearchController::searchOnServer() {
_requestId = request(MTPcontacts_Search( _requestId = _api.request(MTPcontacts_Search(
MTP_string(_query), MTP_string(_query),
MTP_int(SearchPeopleLimit) MTP_int(SearchPeopleLimit)
)).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) { )).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) {

View File

@ -59,9 +59,7 @@ private:
}; };
class PeerListGlobalSearchController class PeerListGlobalSearchController : public PeerListSearchController {
: public PeerListSearchController
, private MTP::Sender {
public: public:
PeerListGlobalSearchController( PeerListGlobalSearchController(
not_null<Window::SessionNavigation*> navigation); not_null<Window::SessionNavigation*> navigation);
@ -78,6 +76,7 @@ private:
void searchDone(const MTPcontacts_Found &result, mtpRequestId requestId); void searchDone(const MTPcontacts_Found &result, mtpRequestId requestId);
const not_null<Window::SessionNavigation*> _navigation; const not_null<Window::SessionNavigation*> _navigation;
MTP::Sender _api;
base::Timer _timer; base::Timer _timer;
QString _query; QString _query;
mtpRequestId _requestId = 0; mtpRequestId _requestId = 0;

View File

@ -276,6 +276,7 @@ AddSpecialBoxController::AddSpecialBoxController(
peer, peer,
&_additional)) &_additional))
, _peer(peer) , _peer(peer)
, _api(_peer->session().api().instance())
, _role(role) , _role(role)
, _additional(peer, Role::Members) , _additional(peer, Role::Members)
, _adminDoneCallback(std::move(adminDoneCallback)) , _adminDoneCallback(std::move(adminDoneCallback))
@ -408,7 +409,7 @@ void AddSpecialBoxController::loadMoreRows() {
const auto participantsHash = 0; const auto participantsHash = 0;
const auto channel = _peer->asChannel(); const auto channel = _peer->asChannel();
_loadRequestId = request(MTPchannels_GetParticipants( _loadRequestId = _api.request(MTPchannels_GetParticipants(
channel->inputChannel, channel->inputChannel,
MTP_channelParticipantsRecent(), MTP_channelParticipantsRecent(),
MTP_int(_offset), MTP_int(_offset),
@ -464,7 +465,7 @@ bool AddSpecialBoxController::checkInfoLoaded(
// We don't know what this user status is in the group. // We don't know what this user status is in the group.
const auto channel = _peer->asChannel(); const auto channel = _peer->asChannel();
request(MTPchannels_GetParticipant( _api.request(MTPchannels_GetParticipant(
channel->inputChannel, channel->inputChannel,
user->inputUser user->inputUser
)).done([=](const MTPchannels_ChannelParticipant &result) { )).done([=](const MTPchannels_ChannelParticipant &result) {
@ -829,6 +830,7 @@ AddSpecialBoxSearchController::AddSpecialBoxSearchController(
not_null<ParticipantsAdditionalData*> additional) not_null<ParticipantsAdditionalData*> additional)
: _peer(peer) : _peer(peer)
, _additional(additional) , _additional(additional)
, _api(_peer->session().api().instance())
, _timer([=] { searchOnServer(); }) { , _timer([=] { searchOnServer(); }) {
subscribeToMigration(); subscribeToMigration();
} }
@ -924,7 +926,7 @@ void AddSpecialBoxSearchController::requestParticipants() {
const auto participantsHash = 0; const auto participantsHash = 0;
const auto channel = _peer->asChannel(); const auto channel = _peer->asChannel();
_requestId = request(MTPchannels_GetParticipants( _requestId = _api.request(MTPchannels_GetParticipants(
channel->inputChannel, channel->inputChannel,
MTP_channelParticipantsSearch(MTP_string(_query)), MTP_channelParticipantsSearch(MTP_string(_query)),
MTP_int(_offset), MTP_int(_offset),
@ -1012,7 +1014,7 @@ void AddSpecialBoxSearchController::requestGlobal() {
} }
auto perPage = SearchPeopleLimit; auto perPage = SearchPeopleLimit;
_requestId = request(MTPcontacts_Search( _requestId = _api.request(MTPcontacts_Search(
MTP_string(_query), MTP_string(_query),
MTP_int(perPage) MTP_int(perPage)
)).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) { )).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) {

View File

@ -69,7 +69,6 @@ private:
class AddSpecialBoxController class AddSpecialBoxController
: public PeerListController : public PeerListController
, private base::Subscriber , private base::Subscriber
, private MTP::Sender
, public base::has_weak_ptr { , public base::has_weak_ptr {
public: public:
using Role = ParticipantsBoxController::Role; using Role = ParticipantsBoxController::Role;
@ -87,12 +86,12 @@ public:
AdminDoneCallback adminDoneCallback, AdminDoneCallback adminDoneCallback,
BannedDoneCallback bannedDoneCallback); BannedDoneCallback bannedDoneCallback);
Main::Session &session() const override; [[nodiscard]] Main::Session &session() const override;
void prepare() override; void prepare() override;
void rowClicked(not_null<PeerListRow*> row) override; void rowClicked(not_null<PeerListRow*> row) override;
void loadMoreRows() override; void loadMoreRows() override;
std::unique_ptr<PeerListRow> createSearchRow( [[nodiscard]] std::unique_ptr<PeerListRow> createSearchRow(
not_null<PeerData*> peer) override; not_null<PeerData*> peer) override;
private: private:
@ -120,6 +119,7 @@ private:
void migrate(not_null<ChannelData*> channel); void migrate(not_null<ChannelData*> channel);
not_null<PeerData*> _peer; not_null<PeerData*> _peer;
MTP::Sender _api;
Role _role = Role::Admins; Role _role = Role::Admins;
int _offset = 0; int _offset = 0;
mtpRequestId _loadRequestId = 0; mtpRequestId _loadRequestId = 0;
@ -139,7 +139,6 @@ protected:
// Finds chat/channel members, then contacts, then global search results. // Finds chat/channel members, then contacts, then global search results.
class AddSpecialBoxSearchController class AddSpecialBoxSearchController
: public PeerListSearchController : public PeerListSearchController
, private MTP::Sender
, private base::Subscriber { , private base::Subscriber {
public: public:
using Role = ParticipantsBoxController::Role; using Role = ParticipantsBoxController::Role;
@ -181,6 +180,7 @@ private:
not_null<PeerData*> _peer; not_null<PeerData*> _peer;
not_null<ParticipantsAdditionalData*> _additional; not_null<ParticipantsAdditionalData*> _additional;
MTP::Sender _api;
base::Timer _timer; base::Timer _timer;
QString _query; QString _query;

View File

@ -745,6 +745,7 @@ ParticipantsBoxController::ParticipantsBoxController(
: PeerListController(CreateSearchController(peer, role, &_additional)) : PeerListController(CreateSearchController(peer, role, &_additional))
, _navigation(navigation) , _navigation(navigation)
, _peer(peer) , _peer(peer)
, _api(_peer->session().api().instance())
, _role(role) , _role(role)
, _additional(peer, _role) { , _additional(peer, _role) {
subscribeToMigration(); subscribeToMigration();
@ -1022,7 +1023,7 @@ void ParticipantsBoxController::restoreState(
: nullptr; : nullptr;
if (const auto my = dynamic_cast<SavedState*>(typeErasedState)) { if (const auto my = dynamic_cast<SavedState*>(typeErasedState)) {
if (const auto requestId = base::take(_loadRequestId)) { if (const auto requestId = base::take(_loadRequestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
_additional = std::move(my->additional); _additional = std::move(my->additional);
@ -1251,7 +1252,7 @@ void ParticipantsBoxController::loadMoreRows() {
: kParticipantsFirstPageCount; : kParticipantsFirstPageCount;
const auto participantsHash = 0; const auto participantsHash = 0;
_loadRequestId = request(MTPchannels_GetParticipants( _loadRequestId = _api.request(MTPchannels_GetParticipants(
channel->inputChannel, channel->inputChannel,
filter, filter,
MTP_int(_offset), MTP_int(_offset),
@ -1906,7 +1907,8 @@ ParticipantsBoxSearchController::ParticipantsBoxSearchController(
not_null<ParticipantsAdditionalData*> additional) not_null<ParticipantsAdditionalData*> additional)
: _channel(channel) : _channel(channel)
, _role(role) , _role(role)
, _additional(additional) { , _additional(additional)
, _api(_channel->session().api().instance()) {
_timer.setCallback([=] { searchOnServer(); }); _timer.setCallback([=] { searchOnServer(); });
} }
@ -1938,7 +1940,7 @@ void ParticipantsBoxSearchController::restoreState(
std::unique_ptr<SavedStateBase> state) { std::unique_ptr<SavedStateBase> state) {
if (auto my = dynamic_cast<SavedState*>(state.get())) { if (auto my = dynamic_cast<SavedState*>(state.get())) {
if (auto requestId = base::take(_requestId)) { if (auto requestId = base::take(_requestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
_cache.clear(); _cache.clear();
_queries.clear(); _queries.clear();
@ -2002,7 +2004,7 @@ bool ParticipantsBoxSearchController::loadMoreRows() {
auto perPage = kParticipantsPerPage; auto perPage = kParticipantsPerPage;
auto participantsHash = 0; auto participantsHash = 0;
_requestId = request(MTPchannels_GetParticipants( _requestId = _api.request(MTPchannels_GetParticipants(
_channel->inputChannel, _channel->inputChannel,
filter, filter,
MTP_int(_offset), MTP_int(_offset),

View File

@ -134,7 +134,6 @@ private:
class ParticipantsBoxController class ParticipantsBoxController
: public PeerListController : public PeerListController
, private base::Subscriber , private base::Subscriber
, private MTP::Sender
, public base::has_weak_ptr { , public base::has_weak_ptr {
public: public:
using Role = ParticipantsRole; using Role = ParticipantsRole;
@ -238,6 +237,7 @@ private:
not_null<Window::SessionNavigation*> _navigation; not_null<Window::SessionNavigation*> _navigation;
not_null<PeerData*> _peer; not_null<PeerData*> _peer;
MTP::Sender _api;
Role _role = Role::Admins; Role _role = Role::Admins;
int _offset = 0; int _offset = 0;
mtpRequestId _loadRequestId = 0; mtpRequestId _loadRequestId = 0;
@ -251,9 +251,7 @@ private:
}; };
// Members, banned and restricted users server side search. // Members, banned and restricted users server side search.
class ParticipantsBoxSearchController class ParticipantsBoxSearchController : public PeerListSearchController {
: public PeerListSearchController
, private MTP::Sender {
public: public:
using Role = ParticipantsBoxController::Role; using Role = ParticipantsBoxController::Role;
@ -295,6 +293,7 @@ private:
not_null<ChannelData*> _channel; not_null<ChannelData*> _channel;
Role _role = Role::Restricted; Role _role = Role::Restricted;
not_null<ParticipantsAdditionalData*> _additional; not_null<ParticipantsAdditionalData*> _additional;
MTP::Sender _api;
base::Timer _timer; base::Timer _timer;
QString _query; QString _query;

View File

@ -240,9 +240,7 @@ namespace {
constexpr auto kMaxGroupChannelTitle = 128; // See also add_contact_box. constexpr auto kMaxGroupChannelTitle = 128; // See also add_contact_box.
constexpr auto kMaxChannelDescription = 255; // See also add_contact_box. constexpr auto kMaxChannelDescription = 255; // See also add_contact_box.
class Controller class Controller : public base::has_weak_ptr {
: public base::has_weak_ptr
, private MTP::Sender {
public: public:
Controller( Controller(
not_null<Window::SessionNavigation*> navigation, not_null<Window::SessionNavigation*> navigation,
@ -334,6 +332,7 @@ private:
const not_null<Window::SessionNavigation*> _navigation; const not_null<Window::SessionNavigation*> _navigation;
const not_null<Ui::BoxContent*> _box; const not_null<Ui::BoxContent*> _box;
not_null<PeerData*> _peer; not_null<PeerData*> _peer;
MTP::Sender _api;
const bool _isGroup = false; const bool _isGroup = false;
base::unique_qptr<Ui::VerticalLayout> _wrap; base::unique_qptr<Ui::VerticalLayout> _wrap;
@ -344,7 +343,6 @@ private:
const rpl::event_stream<Privacy> _privacyTypeUpdates; const rpl::event_stream<Privacy> _privacyTypeUpdates;
const rpl::event_stream<ChannelData*> _linkedChatUpdates; const rpl::event_stream<ChannelData*> _linkedChatUpdates;
MTP::Sender _linkedChatsRequester;
mtpRequestId _linkedChatsRequestId = 0; mtpRequestId _linkedChatsRequestId = 0;
rpl::lifetime _lifetime; rpl::lifetime _lifetime;
@ -358,6 +356,7 @@ Controller::Controller(
: _navigation(navigation) : _navigation(navigation)
, _box(box) , _box(box)
, _peer(peer) , _peer(peer)
, _api(_peer->session().api().instance())
, _isGroup(_peer->isChat() || _peer->isMegagroup()) { , _isGroup(_peer->isChat() || _peer->isMegagroup()) {
_box->setTitle(_isGroup _box->setTitle(_isGroup
? tr::lng_edit_group() ? tr::lng_edit_group()
@ -644,7 +643,7 @@ void Controller::showEditLinkedChatBox() {
callback(_linkedChatOriginalValue); callback(_linkedChatOriginalValue);
return; return;
} }
_linkedChatsRequestId = _linkedChatsRequester.request( _linkedChatsRequestId = _api.request(
MTPchannels_GetGroupsForDiscussion() MTPchannels_GetGroupsForDiscussion()
).done([=](const MTPmessages_Chats &result) { ).done([=](const MTPmessages_Chats &result) {
_linkedChatsRequestId = 0; _linkedChatsRequestId = 0;
@ -1187,7 +1186,7 @@ void Controller::saveUsername() {
return; return;
} }
request(MTPchannels_UpdateUsername( _api.request(MTPchannels_UpdateUsername(
channel->inputChannel, channel->inputChannel,
MTP_string(*_savingData.username) MTP_string(*_savingData.username)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
@ -1242,7 +1241,7 @@ void Controller::saveLinkedChat() {
const auto input = *_savingData.linkedChat const auto input = *_savingData.linkedChat
? (*_savingData.linkedChat)->inputChannel ? (*_savingData.linkedChat)->inputChannel
: MTP_inputChannelEmpty(); : MTP_inputChannelEmpty();
request(MTPchannels_SetDiscussionGroup( _api.request(MTPchannels_SetDiscussionGroup(
(channel->isBroadcast() ? channel->inputChannel : input), (channel->isBroadcast() ? channel->inputChannel : input),
(channel->isBroadcast() ? input : channel->inputChannel) (channel->isBroadcast() ? input : channel->inputChannel)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
@ -1283,14 +1282,14 @@ void Controller::saveTitle() {
}; };
if (const auto channel = _peer->asChannel()) { if (const auto channel = _peer->asChannel()) {
request(MTPchannels_EditTitle( _api.request(MTPchannels_EditTitle(
channel->inputChannel, channel->inputChannel,
MTP_string(*_savingData.title) MTP_string(*_savingData.title)
)).done(std::move(onDone) )).done(std::move(onDone)
).fail(std::move(onFail) ).fail(std::move(onFail)
).send(); ).send();
} else if (const auto chat = _peer->asChat()) { } else if (const auto chat = _peer->asChat()) {
request(MTPmessages_EditChatTitle( _api.request(MTPmessages_EditChatTitle(
chat->inputChat, chat->inputChat,
MTP_string(*_savingData.title) MTP_string(*_savingData.title)
)).done(std::move(onDone) )).done(std::move(onDone)
@ -1311,7 +1310,7 @@ void Controller::saveDescription() {
_peer->setAbout(*_savingData.description); _peer->setAbout(*_savingData.description);
continueSave(); continueSave();
}; };
request(MTPmessages_EditChatAbout( _api.request(MTPmessages_EditChatAbout(
_peer->input, _peer->input,
MTP_string(*_savingData.description) MTP_string(*_savingData.description)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
@ -1368,7 +1367,7 @@ void Controller::togglePreHistoryHidden(
done(); done();
}; };
request(MTPchannels_TogglePreHistoryHidden( _api.request(MTPchannels_TogglePreHistoryHidden(
channel->inputChannel, channel->inputChannel,
MTP_bool(hidden) MTP_bool(hidden)
)).done([=](const MTPUpdates &result) { )).done([=](const MTPUpdates &result) {
@ -1390,7 +1389,7 @@ void Controller::saveSignatures() {
|| *_savingData.signatures == channel->addsSignature()) { || *_savingData.signatures == channel->addsSignature()) {
return continueSave(); return continueSave();
} }
request(MTPchannels_ToggleSignatures( _api.request(MTPchannels_ToggleSignatures(
channel->inputChannel, channel->inputChannel,
MTP_bool(*_savingData.signatures) MTP_bool(*_savingData.signatures)
)).done([=](const MTPUpdates &result) { )).done([=](const MTPUpdates &result) {

View File

@ -51,9 +51,7 @@ namespace {
constexpr auto kUsernameCheckTimeout = crl::time(200); constexpr auto kUsernameCheckTimeout = crl::time(200);
constexpr auto kMinUsernameLength = 5; constexpr auto kMinUsernameLength = 5;
class Controller class Controller : public base::has_weak_ptr {
: public base::has_weak_ptr
, private MTP::Sender {
public: public:
Controller( Controller(
not_null<Ui::VerticalLayout*> container, not_null<Ui::VerticalLayout*> container,
@ -144,6 +142,7 @@ private:
QString inviteLinkText(); QString inviteLinkText();
not_null<PeerData*> _peer; not_null<PeerData*> _peer;
MTP::Sender _api;
std::optional<Privacy> _privacySavedValue; std::optional<Privacy> _privacySavedValue;
std::optional<QString> _usernameSavedValue; std::optional<QString> _usernameSavedValue;
@ -169,6 +168,7 @@ Controller::Controller(
std::optional<Privacy> privacySavedValue, std::optional<Privacy> privacySavedValue,
std::optional<QString> usernameSavedValue) std::optional<QString> usernameSavedValue)
: _peer(peer) : _peer(peer)
, _api(_peer->session().api().instance())
, _privacySavedValue(privacySavedValue) , _privacySavedValue(privacySavedValue)
, _usernameSavedValue(usernameSavedValue) , _usernameSavedValue(usernameSavedValue)
, _useLocationPhrases(useLocationPhrases) , _useLocationPhrases(useLocationPhrases)
@ -401,7 +401,7 @@ void Controller::privacyChanged(Privacy value) {
refreshVisibilities(); refreshVisibilities();
_controls.usernameInput->setDisplayFocused(true); _controls.usernameInput->setDisplayFocused(true);
} else { } else {
request(base::take(_checkUsernameRequestId)).cancel(); _api.request(base::take(_checkUsernameRequestId)).cancel();
_checkUsernameTimer.cancel(); _checkUsernameTimer.cancel();
refreshVisibilities(); refreshVisibilities();
} }
@ -420,11 +420,11 @@ void Controller::checkUsernameAvailability() {
return; return;
} }
if (_checkUsernameRequestId) { if (_checkUsernameRequestId) {
request(_checkUsernameRequestId).cancel(); _api.request(_checkUsernameRequestId).cancel();
} }
const auto channel = _peer->migrateToOrMe()->asChannel(); const auto channel = _peer->migrateToOrMe()->asChannel();
const auto username = channel ? channel->username : QString(); const auto username = channel ? channel->username : QString();
_checkUsernameRequestId = request(MTPchannels_CheckUsername( _checkUsernameRequestId = _api.request(MTPchannels_CheckUsername(
channel ? channel->inputChannel : MTP_inputChannelEmpty(), channel ? channel->inputChannel : MTP_inputChannelEmpty(),
MTP_string(checking) MTP_string(checking)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {

View File

@ -31,6 +31,7 @@ RateCallBox::RateCallBox(
uint64 callId, uint64 callId,
uint64 callAccessHash) uint64 callAccessHash)
: _session(session) : _session(session)
, _api(_session->api().instance())
, _callId(callId) , _callId(callId)
, _callAccessHash(callAccessHash) { , _callAccessHash(callAccessHash) {
} }
@ -120,7 +121,7 @@ void RateCallBox::send() {
return; return;
} }
auto comment = _comment ? _comment->getLastText().trimmed() : QString(); auto comment = _comment ? _comment->getLastText().trimmed() : QString();
_requestId = request(MTPphone_SetCallRating( _requestId = _api.request(MTPphone_SetCallRating(
MTP_flags(0), MTP_flags(0),
MTP_inputPhoneCall(MTP_long(_callId), MTP_long(_callAccessHash)), MTP_inputPhoneCall(MTP_long(_callId), MTP_long(_callAccessHash)),
MTP_int(_rating), MTP_int(_rating),

View File

@ -20,7 +20,7 @@ namespace Main {
class Session; class Session;
} // namespace Main } // namespace Main
class RateCallBox : public Ui::BoxContent, private MTP::Sender { class RateCallBox : public Ui::BoxContent {
public: public:
RateCallBox( RateCallBox(
QWidget*, QWidget*,
@ -41,6 +41,7 @@ private:
void commentResized(); void commentResized();
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
uint64 _callId = 0; uint64 _callId = 0;
uint64 _callAccessHash = 0; uint64 _callAccessHash = 0;

View File

@ -20,7 +20,7 @@ namespace Main {
class Session; class Session;
} // namespace Main } // namespace Main
class SelfDestructionBox : public Ui::BoxContent, private MTP::Sender { class SelfDestructionBox : public Ui::BoxContent {
public: public:
SelfDestructionBox( SelfDestructionBox(
QWidget*, QWidget*,

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "apiwrap.h"
#include "main/main_session.h" #include "main/main_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "base/unixtime.h" #include "base/unixtime.h"
@ -77,6 +78,7 @@ private:
SessionsBox::SessionsBox(QWidget*, not_null<Main::Session*> session) SessionsBox::SessionsBox(QWidget*, not_null<Main::Session*> session)
: _session(session) : _session(session)
, _api(_session->api().instance())
, _shortPollTimer([=] { shortPollSessions(); }) { , _shortPollTimer([=] { shortPollSessions(); }) {
} }
@ -280,7 +282,7 @@ void SessionsBox::shortPollSessions() {
if (_shortPollRequest) { if (_shortPollRequest) {
return; return;
} }
_shortPollRequest = request(MTPaccount_GetAuthorizations( _shortPollRequest = _api.request(MTPaccount_GetAuthorizations(
)).done([=](const MTPaccount_Authorizations &result) { )).done([=](const MTPaccount_Authorizations &result) {
got(result); got(result);
}).send(); }).send();
@ -294,7 +296,7 @@ void SessionsBox::terminateOne(uint64 hash) {
_terminateBox->closeBox(); _terminateBox->closeBox();
_terminateBox = nullptr; _terminateBox = nullptr;
} }
request(MTPaccount_ResetAuthorization( _api.request(MTPaccount_ResetAuthorization(
MTP_long(hash) MTP_long(hash)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
_inner->terminatingOne(hash, false); _inner->terminatingOne(hash, false);
@ -330,12 +332,12 @@ void SessionsBox::terminateAll() {
_terminateBox->closeBox(); _terminateBox->closeBox();
_terminateBox = nullptr; _terminateBox = nullptr;
} }
request(MTPauth_ResetAuthorizations( _api.request(MTPauth_ResetAuthorizations(
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
request(base::take(_shortPollRequest)).cancel(); _api.request(base::take(_shortPollRequest)).cancel();
shortPollSessions(); shortPollSessions();
}).fail([=](const RPCError &result) { }).fail([=](const RPCError &result) {
request(base::take(_shortPollRequest)).cancel(); _api.request(base::take(_shortPollRequest)).cancel();
shortPollSessions(); shortPollSessions();
}).send(); }).send();
setLoading(true); setLoading(true);

View File

@ -22,7 +22,7 @@ namespace Main {
class Session; class Session;
} // namespace Main } // namespace Main
class SessionsBox : public Ui::BoxContent, private MTP::Sender { class SessionsBox : public Ui::BoxContent {
public: public:
SessionsBox(QWidget*, not_null<Main::Session*> session); SessionsBox(QWidget*, not_null<Main::Session*> session);
@ -60,6 +60,7 @@ private:
void terminateAll(); void terminateAll();
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
bool _loading = false; bool _loading = false;
Full _data; Full _data;

View File

@ -99,7 +99,7 @@ private:
void showPreview(); void showPreview();
not_null<Window::SessionController*> _controller; not_null<Window::SessionController*> _controller;
MTP::Sender _mtp; MTP::Sender _api;
std::vector<Element> _elements; std::vector<Element> _elements;
std::unique_ptr<Lottie::MultiPlayer> _lottiePlayer; std::unique_ptr<Lottie::MultiPlayer> _lottiePlayer;
Stickers::Pack _pack; Stickers::Pack _pack;
@ -220,6 +220,7 @@ StickerSetBox::Inner::Inner(
const MTPInputStickerSet &set) const MTPInputStickerSet &set)
: RpWidget(parent) : RpWidget(parent)
, _controller(controller) , _controller(controller)
, _api(_controller->session().api().instance())
, _input(set) , _input(set)
, _previewTimer([=] { showPreview(); }) { , _previewTimer([=] { showPreview(); }) {
set.match([&](const MTPDinputStickerSetID &data) { set.match([&](const MTPDinputStickerSetID &data) {
@ -231,7 +232,7 @@ StickerSetBox::Inner::Inner(
}, [&](const MTPDinputStickerSetAnimatedEmoji &) { }, [&](const MTPDinputStickerSetAnimatedEmoji &) {
}); });
_mtp.request(MTPmessages_GetStickerSet( _api.request(MTPmessages_GetStickerSet(
_input _input
)).done([=](const MTPmessages_StickerSet &result) { )).done([=](const MTPmessages_StickerSet &result) {
gotSet(result); gotSet(result);
@ -700,7 +701,7 @@ void StickerSetBox::Inner::install() {
} else if (_installRequest) { } else if (_installRequest) {
return; return;
} }
_installRequest = _mtp.request(MTPmessages_InstallStickerSet( _installRequest = _api.request(MTPmessages_InstallStickerSet(
_input, _input,
MTP_bool(false) MTP_bool(false)
)).done([=](const MTPmessages_StickerSetInstallResult &result) { )).done([=](const MTPmessages_StickerSetInstallResult &result) {

View File

@ -661,6 +661,7 @@ StickersBox::Inner::Inner(
StickersBox::Section section) StickersBox::Section section)
: RpWidget(parent) : RpWidget(parent)
, _session(session) , _session(session)
, _api(_session->api().instance())
, _section(section) , _section(section)
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom())
, _shiftingAnimation([=](crl::time now) { , _shiftingAnimation([=](crl::time now) {
@ -677,6 +678,7 @@ StickersBox::Inner::Inner(
StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup) StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup)
: RpWidget(parent) : RpWidget(parent)
, _session(&megagroup->session()) , _session(&megagroup->session())
, _api(_session->api().instance())
, _section(StickersBox::Section::Installed) , _section(StickersBox::Section::Installed)
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom())
, _shiftingAnimation([=](crl::time now) { , _shiftingAnimation([=](crl::time now) {
@ -1469,11 +1471,13 @@ void StickersBox::Inner::handleMegagroupSetAddressChange() {
} }
} }
} else if (!_megagroupSetRequestId) { } else if (!_megagroupSetRequestId) {
_megagroupSetRequestId = request(MTPmessages_GetStickerSet(MTP_inputStickerSetShortName(MTP_string(text)))).done([this](const MTPmessages_StickerSet &result) { _megagroupSetRequestId = _api.request(MTPmessages_GetStickerSet(
MTP_inputStickerSetShortName(MTP_string(text))
)).done([=](const MTPmessages_StickerSet &result) {
_megagroupSetRequestId = 0; _megagroupSetRequestId = 0;
auto set = Stickers::FeedSetFull(result); auto set = Stickers::FeedSetFull(result);
setMegagroupSelectedSet(MTP_inputStickerSetID(MTP_long(set->id), MTP_long(set->access))); setMegagroupSelectedSet(MTP_inputStickerSetID(MTP_long(set->id), MTP_long(set->access)));
}).fail([this](const RPCError &error) { }).fail([=](const RPCError &error) {
_megagroupSetRequestId = 0; _megagroupSetRequestId = 0;
setMegagroupSelectedSet(MTP_inputStickerSetEmpty()); setMegagroupSelectedSet(MTP_inputStickerSetEmpty());
}).send(); }).send();

View File

@ -153,8 +153,7 @@ private:
// This class is hold in header because it requires Qt preprocessing. // This class is hold in header because it requires Qt preprocessing.
class StickersBox::Inner class StickersBox::Inner
: public Ui::RpWidget : public Ui::RpWidget
, private base::Subscriber , private base::Subscriber {
, private MTP::Sender {
Q_OBJECT Q_OBJECT
public: public:
@ -320,6 +319,7 @@ private:
int countMaxNameWidth() const; int countMaxNameWidth() const;
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
Section _section; Section _section;

View File

@ -21,6 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_media_types.h" #include "data/data_media_types.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "apiwrap.h"
#include "facades.h" #include "facades.h"
#include "app.h" #include "app.h"
@ -216,7 +217,8 @@ void BoxController::Row::stopLastActionRipple() {
} }
BoxController::BoxController(not_null<Window::SessionController*> window) BoxController::BoxController(not_null<Window::SessionController*> window)
: _window(window) { : _window(window)
, _api(_window->session().api().instance()) {
} }
Main::Session &BoxController::session() const { Main::Session &BoxController::session() const {
@ -256,7 +258,7 @@ void BoxController::loadMoreRows() {
return; return;
} }
_loadRequestId = request(MTPmessages_Search( _loadRequestId = _api.request(MTPmessages_Search(
MTP_flags(0), MTP_flags(0),
MTP_inputPeerEmpty(), MTP_inputPeerEmpty(),
MTP_string(), MTP_string(),

View File

@ -15,10 +15,7 @@ class SessionController;
namespace Calls { namespace Calls {
class BoxController class BoxController : public PeerListController, private base::Subscriber {
: public PeerListController
, private base::Subscriber
, private MTP::Sender {
public: public:
explicit BoxController(not_null<Window::SessionController*> window); explicit BoxController(not_null<Window::SessionController*> window);
@ -44,6 +41,7 @@ private:
not_null<HistoryItem*> item) const; not_null<HistoryItem*> item) const;
const not_null<Window::SessionController*> _window; const not_null<Window::SessionController*> _window;
MTP::Sender _api;
MsgId _offsetId = 0; MsgId _offsetId = 0;
mtpRequestId _loadRequestId = 0; mtpRequestId _loadRequestId = 0;

View File

@ -130,6 +130,7 @@ Call::Call(
Type type) Type type)
: _delegate(delegate) : _delegate(delegate)
, _user(user) , _user(user)
, _api(_user->session().api().instance())
, _type(type) { , _type(type) {
_discardByTimeoutTimer.setCallback([this] { hangup(); }); _discardByTimeoutTimer.setCallback([this] { hangup(); });
@ -189,7 +190,7 @@ void Call::startOutgoing() {
Expects(_state == State::Requesting); Expects(_state == State::Requesting);
Expects(_gaHash.size() == kSha256Size); Expects(_gaHash.size() == kSha256Size);
request(MTPphone_RequestCall( _api.request(MTPphone_RequestCall(
MTP_flags(0), MTP_flags(0),
_user->inputUser, _user->inputUser,
MTP_int(rand_value<int32>()), MTP_int(rand_value<int32>()),
@ -236,11 +237,13 @@ void Call::startIncoming() {
Expects(_type == Type::Incoming); Expects(_type == Type::Incoming);
Expects(_state == State::Starting); Expects(_state == State::Starting);
request(MTPphone_ReceivedCall(MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)))).done([this](const MTPBool &result) { _api.request(MTPphone_ReceivedCall(
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash))
)).done([=](const MTPBool &result) {
if (_state == State::Starting) { if (_state == State::Starting) {
setState(State::WaitingIncoming); setState(State::WaitingIncoming);
} }
}).fail([this](const RPCError &error) { }).fail([=](const RPCError &error) {
handleRequestError(error); handleRequestError(error);
}).send(); }).send();
} }
@ -267,7 +270,7 @@ void Call::actuallyAnswer() {
} else { } else {
_answerAfterDhConfigReceived = false; _answerAfterDhConfigReceived = false;
} }
request(MTPphone_AcceptCall( _api.request(MTPphone_AcceptCall(
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)), MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)),
MTP_bytes(_gb), MTP_bytes(_gb),
MTP_phoneCallProtocol( MTP_phoneCallProtocol(
@ -504,7 +507,7 @@ void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
_keyFingerprint = ComputeFingerprint(_authKey); _keyFingerprint = ComputeFingerprint(_authKey);
setState(State::ExchangingKeys); setState(State::ExchangingKeys);
request(MTPphone_ConfirmCall( _api.request(MTPphone_ConfirmCall(
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)), MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)),
MTP_bytes(_ga), MTP_bytes(_ga),
MTP_long(_keyFingerprint), MTP_long(_keyFingerprint),
@ -840,7 +843,7 @@ void Call::finish(FinishType type, const MTPPhoneCallDiscardReason &reason) {
auto duration = getDurationMs() / 1000; auto duration = getDurationMs() / 1000;
auto connectionId = _controller ? _controller->GetPreferredRelayID() : 0; auto connectionId = _controller ? _controller->GetPreferredRelayID() : 0;
_finishByTimeoutTimer.call(kHangupTimeoutMs, [this, finalState] { setState(finalState); }); _finishByTimeoutTimer.call(kHangupTimeoutMs, [this, finalState] { setState(finalState); });
request(MTPphone_DiscardCall( _api.request(MTPphone_DiscardCall(
MTP_flags(0), MTP_flags(0),
MTP_inputPhoneCall( MTP_inputPhoneCall(
MTP_long(_id), MTP_long(_id),

View File

@ -31,7 +31,7 @@ struct DhConfig {
bytes::vector p; bytes::vector p;
}; };
class Call : public base::has_weak_ptr, private MTP::Sender { class Call : public base::has_weak_ptr {
public: public:
class Delegate { class Delegate {
public: public:
@ -183,6 +183,7 @@ private:
not_null<Delegate*> _delegate; not_null<Delegate*> _delegate;
not_null<UserData*> _user; not_null<UserData*> _user;
MTP::Sender _api;
Type _type = Type::Outgoing; Type _type = Type::Outgoing;
State _state = State::Starting; State _state = State::Starting;
FinishType _finishAfterRequestingCall = FinishType::None; FinishType _finishAfterRequestingCall = FinishType::None;

View File

@ -32,7 +32,9 @@ constexpr auto kServerConfigUpdateTimeoutMs = 24 * 3600 * crl::time(1000);
} // namespace } // namespace
Instance::Instance(not_null<Main::Session*> session) : _session(session) { Instance::Instance(not_null<Main::Session*> session)
: _session(session)
, _api(_session->api().instance()) {
} }
void Instance::startOutgoingCall(not_null<UserData*> user) { void Instance::startOutgoingCall(not_null<UserData*> user) {
@ -139,7 +141,7 @@ void Instance::refreshDhConfig() {
Expects(_currentCall != nullptr); Expects(_currentCall != nullptr);
const auto weak = base::make_weak(_currentCall); const auto weak = base::make_weak(_currentCall);
request(MTPmessages_GetDhConfig( _api.request(MTPmessages_GetDhConfig(
MTP_int(_dhConfig.version), MTP_int(_dhConfig.version),
MTP_int(MTP::ModExpFirst::kRandomPowerSize) MTP_int(MTP::ModExpFirst::kRandomPowerSize)
)).done([=](const MTPmessages_DhConfig &result) { )).done([=](const MTPmessages_DhConfig &result) {
@ -203,13 +205,14 @@ void Instance::refreshServerConfig() {
if (_lastServerConfigUpdateTime && (crl::now() - _lastServerConfigUpdateTime) < kServerConfigUpdateTimeoutMs) { if (_lastServerConfigUpdateTime && (crl::now() - _lastServerConfigUpdateTime) < kServerConfigUpdateTimeoutMs) {
return; return;
} }
_serverConfigRequestId = request(MTPphone_GetCallConfig()).done([this](const MTPDataJSON &result) { _serverConfigRequestId = _api.request(MTPphone_GetCallConfig(
)).done([=](const MTPDataJSON &result) {
_serverConfigRequestId = 0; _serverConfigRequestId = 0;
_lastServerConfigUpdateTime = crl::now(); _lastServerConfigUpdateTime = crl::now();
const auto &json = result.c_dataJSON().vdata().v; const auto &json = result.c_dataJSON().vdata().v;
UpdateConfig(std::string(json.data(), json.size())); UpdateConfig(std::string(json.data(), json.size()));
}).fail([this](const RPCError &error) { }).fail([=](const RPCError &error) {
_serverConfigRequestId = 0; _serverConfigRequestId = 0;
}).send(); }).send();
} }
@ -246,7 +249,7 @@ void Instance::handleCallUpdate(const MTPPhoneCall &call) {
LOG(("API Error: Self found in phoneCallRequested.")); LOG(("API Error: Self found in phoneCallRequested."));
} }
if (alreadyInCall() || !user || user->isSelf()) { if (alreadyInCall() || !user || user->isSelf()) {
request(MTPphone_DiscardCall( _api.request(MTPphone_DiscardCall(
MTP_flags(0), MTP_flags(0),
MTP_inputPhoneCall(phoneCall.vid(), phoneCall.vaccess_hash()), MTP_inputPhoneCall(phoneCall.vid(), phoneCall.vaccess_hash()),
MTP_int(0), MTP_int(0),

View File

@ -25,8 +25,7 @@ namespace Calls {
class Panel; class Panel;
class Instance class Instance
: private MTP::Sender : private Call::Delegate
, private Call::Delegate
, private base::Subscriber , private base::Subscriber
, public base::has_weak_ptr { , public base::has_weak_ptr {
public: public:
@ -74,6 +73,7 @@ private:
void handleCallUpdate(const MTPPhoneCall &call); void handleCallUpdate(const MTPPhoneCall &call);
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
MTP::Sender _api;
DhConfig _dhConfig; DhConfig _dhConfig;

View File

@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "apiwrap.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "history/view/history_view_cursor_state.h" #include "history/view/history_view_cursor_state.h"
#include "facades.h" #include "facades.h"
@ -130,6 +131,7 @@ GifsListWidget::GifsListWidget(
QWidget *parent, QWidget *parent,
not_null<Window::SessionController*> controller) not_null<Window::SessionController*> controller)
: Inner(parent, controller) : Inner(parent, controller)
, _api(controller->session().api().instance())
, _section(Section::Gifs) , _section(Section::Gifs)
, _updateInlineItems([=] { updateInlineItems(); }) , _updateInlineItems([=] { updateInlineItems(); })
, _previewTimer([=] { showPreview(); }) { , _previewTimer([=] { showPreview(); }) {
@ -217,7 +219,7 @@ GifsListWidget::~GifsListWidget() {
void GifsListWidget::cancelGifsSearch() { void GifsListWidget::cancelGifsSearch() {
_footer->setLoading(false); _footer->setLoading(false);
if (_inlineRequestId) { if (_inlineRequestId) {
request(_inlineRequestId).cancel(); _api.request(_inlineRequestId).cancel();
_inlineRequestId = 0; _inlineRequestId = 0;
} }
_inlineRequestTimer.stop(); _inlineRequestTimer.stop();
@ -840,7 +842,7 @@ void GifsListWidget::searchForGifs(const QString &query) {
if (_inlineQuery != query) { if (_inlineQuery != query) {
_footer->setLoading(false); _footer->setLoading(false);
if (_inlineRequestId) { if (_inlineRequestId) {
request(_inlineRequestId).cancel(); _api.request(_inlineRequestId).cancel();
_inlineRequestId = 0; _inlineRequestId = 0;
} }
if (_inlineCache.find(query) != _inlineCache.cend()) { if (_inlineCache.find(query) != _inlineCache.cend()) {
@ -855,7 +857,7 @@ void GifsListWidget::searchForGifs(const QString &query) {
if (!_searchBot && !_searchBotRequestId) { if (!_searchBot && !_searchBotRequestId) {
auto username = str_const_toString(kSearchBotUsername); auto username = str_const_toString(kSearchBotUsername);
_searchBotRequestId = request(MTPcontacts_ResolveUsername( _searchBotRequestId = _api.request(MTPcontacts_ResolveUsername(
MTP_string(username) MTP_string(username)
)).done([=](const MTPcontacts_ResolvedPeer &result) { )).done([=](const MTPcontacts_ResolvedPeer &result) {
Expects(result.type() == mtpc_contacts_resolvedPeer); Expects(result.type() == mtpc_contacts_resolvedPeer);
@ -905,7 +907,7 @@ void GifsListWidget::sendInlineRequest() {
} }
_footer->setLoading(true); _footer->setLoading(true);
_inlineRequestId = request(MTPmessages_GetInlineBotResults( _inlineRequestId = _api.request(MTPmessages_GetInlineBotResults(
MTP_flags(0), MTP_flags(0),
_searchBot->inputUser, _searchBot->inputUser,
_inlineQueryPeer->input, _inlineQueryPeer->input,

View File

@ -34,8 +34,7 @@ namespace ChatHelpers {
class GifsListWidget class GifsListWidget
: public TabbedSelector::Inner : public TabbedSelector::Inner
, public InlineBots::Layout::Context , public InlineBots::Layout::Context
, private base::Subscriber , private base::Subscriber {
, private MTP::Sender {
public: public:
using InlineChosen = TabbedSelector::InlineChosen; using InlineChosen = TabbedSelector::InlineChosen;
@ -119,6 +118,8 @@ private:
void updateInlineItems(); void updateInlineItems();
void showPreview(); void showPreview();
MTP::Sender _api;
Section _section = Section::Gifs; Section _section = Section::Gifs;
crl::time _lastScrolled = 0; crl::time _lastScrolled = 0;
base::Timer _updateInlineItems; base::Timer _updateInlineItems;

View File

@ -828,6 +828,7 @@ StickersListWidget::StickersListWidget(
QWidget *parent, QWidget *parent,
not_null<Window::SessionController*> controller) not_null<Window::SessionController*> controller)
: Inner(parent, controller) : Inner(parent, controller)
, _api(controller->session().api().instance())
, _section(Section::Stickers) , _section(Section::Stickers)
, _megagroupSetAbout(st::columnMinimalWidthThird - st::emojiScroll.width - st::emojiPanHeaderLeft) , _megagroupSetAbout(st::columnMinimalWidthThird - st::emojiScroll.width - st::emojiPanHeaderLeft)
, _addText(tr::lng_stickers_featured_add(tr::now).toUpper()) , _addText(tr::lng_stickers_featured_add(tr::now).toUpper())
@ -1069,7 +1070,7 @@ void StickersListWidget::sendSearchRequest() {
_footer->setLoading(true); _footer->setLoading(true);
const auto hash = int32(0); const auto hash = int32(0);
_searchRequestId = request(MTPmessages_SearchStickerSets( _searchRequestId = _api.request(MTPmessages_SearchStickerSets(
MTP_flags(0), MTP_flags(0),
MTP_string(_searchQuery), MTP_string(_searchQuery),
MTP_int(hash) MTP_int(hash)
@ -1092,7 +1093,7 @@ void StickersListWidget::searchForSets(const QString &query) {
if (_searchQuery != cleaned) { if (_searchQuery != cleaned) {
_footer->setLoading(false); _footer->setLoading(false);
if (const auto requestId = base::take(_searchRequestId)) { if (const auto requestId = base::take(_searchRequestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
if (_searchCache.find(cleaned) != _searchCache.cend()) { if (_searchCache.find(cleaned) != _searchCache.cend()) {
_searchRequestTimer.cancel(); _searchRequestTimer.cancel();
@ -1108,7 +1109,7 @@ void StickersListWidget::searchForSets(const QString &query) {
void StickersListWidget::cancelSetsSearch() { void StickersListWidget::cancelSetsSearch() {
_footer->setLoading(false); _footer->setLoading(false);
if (const auto requestId = base::take(_searchRequestId)) { if (const auto requestId = base::take(_searchRequestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
_searchRequestTimer.cancel(); _searchRequestTimer.cancel();
_searchQuery = _searchNextQuery = QString(); _searchQuery = _searchNextQuery = QString();
@ -2468,7 +2469,7 @@ void StickersListWidget::refreshMegagroupStickers(GroupStickersPlace place) {
return; return;
} }
_megagroupSetIdRequested = set.vid().v; _megagroupSetIdRequested = set.vid().v;
request(MTPmessages_GetStickerSet( _api.request(MTPmessages_GetStickerSet(
_megagroupSet->mgInfo->stickerSet _megagroupSet->mgInfo->stickerSet
)).done([=](const MTPmessages_StickerSet &result) { )).done([=](const MTPmessages_StickerSet &result) {
if (const auto set = Stickers::FeedSetFull(result)) { if (const auto set = Stickers::FeedSetFull(result)) {
@ -2810,7 +2811,7 @@ void StickersListWidget::installSet(uint64 setId) {
const auto input = Stickers::inputSetId(*it); const auto input = Stickers::inputSetId(*it);
if ((it->flags & MTPDstickerSet_ClientFlag::f_not_loaded) if ((it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)
|| it->stickers.empty()) { || it->stickers.empty()) {
request(MTPmessages_GetStickerSet( _api.request(MTPmessages_GetStickerSet(
input input
)).done([=](const MTPmessages_StickerSet &result) { )).done([=](const MTPmessages_StickerSet &result) {
Stickers::FeedSetFull(result); Stickers::FeedSetFull(result);
@ -2825,7 +2826,7 @@ void StickersListWidget::installSet(uint64 setId) {
void StickersListWidget::sendInstallRequest( void StickersListWidget::sendInstallRequest(
uint64 setId, uint64 setId,
const MTPInputStickerSet &input) { const MTPInputStickerSet &input) {
request(MTPmessages_InstallStickerSet( _api.request(MTPmessages_InstallStickerSet(
input, input,
MTP_bool(false) MTP_bool(false)
)).done([=](const MTPmessages_StickerSetInstallResult &result) { )).done([=](const MTPmessages_StickerSetInstallResult &result) {
@ -2876,9 +2877,9 @@ void StickersListWidget::removeSet(uint64 setId) {
auto it = sets.find(_removingSetId); auto it = sets.find(_removingSetId);
if (it != sets.cend()) { if (it != sets.cend()) {
if (it->id && it->access) { if (it->id && it->access) {
request(MTPmessages_UninstallStickerSet(MTP_inputStickerSetID(MTP_long(it->id), MTP_long(it->access)))).send(); _api.request(MTPmessages_UninstallStickerSet(MTP_inputStickerSetID(MTP_long(it->id), MTP_long(it->access)))).send();
} else if (!it->shortName.isEmpty()) { } else if (!it->shortName.isEmpty()) {
request(MTPmessages_UninstallStickerSet(MTP_inputStickerSetShortName(MTP_string(it->shortName)))).send(); _api.request(MTPmessages_UninstallStickerSet(MTP_inputStickerSetShortName(MTP_string(it->shortName)))).send();
} }
auto writeRecent = false; auto writeRecent = false;
auto &recent = Stickers::GetRecentPack(); auto &recent = Stickers::GetRecentPack();

View File

@ -38,8 +38,7 @@ struct StickerIcon;
class StickersListWidget class StickersListWidget
: public TabbedSelector::Inner : public TabbedSelector::Inner
, private base::Subscriber , private base::Subscriber {
, private MTP::Sender {
public: public:
StickersListWidget( StickersListWidget(
QWidget *parent, QWidget *parent,
@ -300,6 +299,7 @@ private:
void showPreview(); void showPreview();
MTP::Sender _api;
ChannelData *_megagroupSet = nullptr; ChannelData *_megagroupSet = nullptr;
uint64 _megagroupSetIdRequested = 0; uint64 _megagroupSetIdRequested = 0;
std::vector<Set> _mySets; std::vector<Set> _mySets;

View File

@ -93,6 +93,7 @@ Application::Application(not_null<Launcher*> launcher)
, _dcOptions(std::make_unique<MTP::DcOptions>()) , _dcOptions(std::make_unique<MTP::DcOptions>())
, _account(std::make_unique<Main::Account>(cDataFile())) , _account(std::make_unique<Main::Account>(cDataFile()))
, _langpack(std::make_unique<Lang::Instance>()) , _langpack(std::make_unique<Lang::Instance>())
, _langCloudManager(std::make_unique<Lang::CloudManager>(langpack()))
, _emojiKeywords(std::make_unique<ChatHelpers::EmojiKeywords>()) , _emojiKeywords(std::make_unique<ChatHelpers::EmojiKeywords>())
, _audio(std::make_unique<Media::Audio::Instance>()) , _audio(std::make_unique<Media::Audio::Instance>())
, _logo(Window::LoadLogo()) , _logo(Window::LoadLogo())
@ -114,9 +115,6 @@ Application::Application(not_null<Launcher*> launcher)
) | rpl::filter([=](MTP::Instance *instance) { ) | rpl::filter([=](MTP::Instance *instance) {
return instance != nullptr; return instance != nullptr;
}) | rpl::start_with_next([=](not_null<MTP::Instance*> mtp) { }) | rpl::start_with_next([=](not_null<MTP::Instance*> mtp) {
_langCloudManager = std::make_unique<Lang::CloudManager>(
langpack(),
mtp);
if (!UpdaterDisabled()) { if (!UpdaterDisabled()) {
UpdateChecker().setMtproto(mtp.get()); UpdateChecker().setMtproto(mtp.get());
} }
@ -134,11 +132,6 @@ Application::~Application() {
// Some MTP requests can be cancelled from data clearing. // Some MTP requests can be cancelled from data clearing.
unlockTerms(); unlockTerms();
activeAccount().destroySession(); activeAccount().destroySession();
// The langpack manager should be destroyed before MTProto instance,
// because it is MTP::Sender and it may have pending requests.
_langCloudManager.reset();
activeAccount().clearMtp(); activeAccount().clearMtp();
Shortcuts::Finish(); Shortcuts::Finish();

View File

@ -266,7 +266,7 @@ private:
std::unique_ptr<Window::Controller> _window; std::unique_ptr<Window::Controller> _window;
std::unique_ptr<Media::View::OverlayWidget> _mediaView; std::unique_ptr<Media::View::OverlayWidget> _mediaView;
const std::unique_ptr<Lang::Instance> _langpack; const std::unique_ptr<Lang::Instance> _langpack;
std::unique_ptr<Lang::CloudManager> _langCloudManager; const std::unique_ptr<Lang::CloudManager> _langCloudManager;
const std::unique_ptr<ChatHelpers::EmojiKeywords> _emojiKeywords; const std::unique_ptr<ChatHelpers::EmojiKeywords> _emojiKeywords;
std::unique_ptr<Lang::Translator> _translator; std::unique_ptr<Lang::Translator> _translator;
base::Observable<void> _passcodedChanged; base::Observable<void> _passcodedChanged;

View File

@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h" #include "data/data_channel.h"
#include "history/history.h" #include "history/history.h"
#include "history/history_item.h" #include "history/history_item.h"
#include "apiwrap.h"
namespace Api { namespace Api {
namespace { namespace {
@ -191,6 +192,10 @@ SearchController::CacheEntry::CacheEntry(const Query &query)
: std::nullopt) { : std::nullopt) {
} }
SearchController::SearchController(not_null<Main::Session*> session)
: _api(session->api().instance()) {
}
bool SearchController::hasInCache(const Query &query) const { bool SearchController::hasInCache(const Query &query) const {
return query.query.isEmpty() || _cache.contains(query); return query.query.isEmpty() || _cache.contains(query);
} }
@ -361,7 +366,7 @@ void SearchController::requestMore(
if (!prepared) { if (!prepared) {
return; return;
} }
auto requestId = request( auto requestId = _api.request(
std::move(*prepared) std::move(*prepared)
).done([=](const MTPmessages_Messages &result) { ).done([=](const MTPmessages_Messages &result) {
listData->requests.remove(key); listData->requests.remove(key);
@ -377,11 +382,13 @@ void SearchController::requestMore(
parsed.fullCount); parsed.fullCount);
}).send(); }).send();
listData->requests.emplace(key, [=] { listData->requests.emplace(key, [=] {
request(requestId).cancel(); _api.request(requestId).cancel();
}); });
} }
DelayedSearchController::DelayedSearchController() { DelayedSearchController::DelayedSearchController(
not_null<Main::Session*> session)
: _controller(session) {
_timer.setCallback([this] { setQueryFast(_nextQuery); }); _timer.setCallback([this] { setQueryFast(_nextQuery); });
} }

View File

@ -14,6 +14,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/value_ordering.h" #include "base/value_ordering.h"
#include "base/timer.h" #include "base/timer.h"
namespace Main {
class Session;
} // namespace Main
namespace Data { namespace Data {
enum class LoadDirection : char; enum class LoadDirection : char;
} // namespace Data } // namespace Data
@ -40,7 +44,7 @@ SearchResult ParseSearchResult(
Data::LoadDirection direction, Data::LoadDirection direction,
const MTPmessages_Messages &data); const MTPmessages_Messages &data);
class SearchController : private MTP::Sender { class SearchController final {
public: public:
using IdsList = Storage::SparseIdsList; using IdsList = Storage::SparseIdsList;
struct Query { struct Query {
@ -67,6 +71,7 @@ public:
std::optional<IdsList> migratedList; std::optional<IdsList> migratedList;
}; };
explicit SearchController(not_null<Main::Session*> session);
void setQuery(const Query &query); void setQuery(const Query &query);
bool hasInCache(const Query &query) const; bool hasInCache(const Query &query) const;
@ -124,6 +129,7 @@ private:
const Query &query, const Query &query,
Data *listData); Data *listData);
MTP::Sender _api;
Cache _cache; Cache _cache;
Cache::iterator _current = _cache.end(); Cache::iterator _current = _cache.end();
@ -131,7 +137,7 @@ private:
class DelayedSearchController { class DelayedSearchController {
public: public:
DelayedSearchController(); explicit DelayedSearchController(not_null<Main::Session*> session);
using Query = SearchController::Query; using Query = SearchController::Query;
using SavedState = SearchController::SavedState; using SavedState = SearchController::SavedState;

View File

@ -226,6 +226,7 @@ InnerWidget::InnerWidget(
, _controller(controller) , _controller(controller)
, _channel(channel) , _channel(channel)
, _history(channel->owner().history(channel)) , _history(channel->owner().history(channel))
, _api(_channel->session().api().instance())
, _scrollDateCheck([=] { scrollDateCheck(); }) , _scrollDateCheck([=] { scrollDateCheck(); })
, _emptyText( , _emptyText(
st::historyAdminLogEmptyWidth st::historyAdminLogEmptyWidth
@ -407,7 +408,7 @@ void InnerWidget::applySearch(const QString &query) {
void InnerWidget::requestAdmins() { void InnerWidget::requestAdmins() {
auto participantsHash = 0; auto participantsHash = 0;
request(MTPchannels_GetParticipants( _api.request(MTPchannels_GetParticipants(
_channel->inputChannel, _channel->inputChannel,
MTP_channelParticipantsAdmins(), MTP_channelParticipantsAdmins(),
MTP_int(0), MTP_int(0),
@ -463,8 +464,8 @@ void InnerWidget::showFilter(Fn<void(FilterValue &&filter)> callback) {
} }
void InnerWidget::clearAndRequestLog() { void InnerWidget::clearAndRequestLog() {
request(base::take(_preloadUpRequestId)).cancel(); _api.request(base::take(_preloadUpRequestId)).cancel();
request(base::take(_preloadDownRequestId)).cancel(); _api.request(base::take(_preloadDownRequestId)).cancel();
_filterChanged = true; _filterChanged = true;
_upLoaded = false; _upLoaded = false;
_downLoaded = true; _downLoaded = true;
@ -635,7 +636,7 @@ void InnerWidget::preloadMore(Direction direction) {
auto maxId = (direction == Direction::Up) ? _minId : 0; auto maxId = (direction == Direction::Up) ? _minId : 0;
auto minId = (direction == Direction::Up) ? 0 : _maxId; auto minId = (direction == Direction::Up) ? 0 : _maxId;
auto perPage = _items.empty() ? kEventsFirstPage : kEventsPerPage; auto perPage = _items.empty() ? kEventsFirstPage : kEventsPerPage;
requestId = request(MTPchannels_GetAdminLog( requestId = _api.request(MTPchannels_GetAdminLog(
MTP_flags(flags), MTP_flags(flags),
_channel->inputChannel, _channel->inputChannel,
MTP_string(_searchQuery), MTP_string(_searchQuery),
@ -1217,7 +1218,7 @@ void InnerWidget::suggestRestrictUser(not_null<UserData*> user) {
if (base::contains(_admins, user)) { if (base::contains(_admins, user)) {
editRestrictions(true, MTP_chatBannedRights(MTP_flags(0), MTP_int(0))); editRestrictions(true, MTP_chatBannedRights(MTP_flags(0), MTP_int(0)));
} else { } else {
request(MTPchannels_GetParticipant( _api.request(MTPchannels_GetParticipant(
_channel->inputChannel, _channel->inputChannel,
user->inputUser user->inputUser
)).done([=](const MTPchannels_ChannelParticipant &result) { )).done([=](const MTPchannels_ChannelParticipant &result) {

View File

@ -44,7 +44,6 @@ class InnerWidget final
: public Ui::RpWidget : public Ui::RpWidget
, public Ui::AbstractTooltipShower , public Ui::AbstractTooltipShower
, public HistoryView::ElementDelegate , public HistoryView::ElementDelegate
, private MTP::Sender
, private base::Subscriber { , private base::Subscriber {
public: public:
InnerWidget( InnerWidget(
@ -216,9 +215,11 @@ private:
template <typename Method> template <typename Method>
void enumerateDates(Method method); void enumerateDates(Method method);
not_null<Window::SessionController*> _controller; const not_null<Window::SessionController*> _controller;
not_null<ChannelData*> _channel; const not_null<ChannelData*> _channel;
not_null<History*> _history; const not_null<History*> _history;
MTP::Sender _api;
std::vector<OwnedItem> _items; std::vector<OwnedItem> _items;
std::set<uint64> _eventIds; std::set<uint64> _eventIds;
std::map<not_null<const HistoryItem*>, not_null<Element*>> _itemsByData; std::map<not_null<const HistoryItem*>, not_null<Element*>> _itemsByData;

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "info/info_controller.h" #include "info/info_controller.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mtproto/sender.h" #include "mtproto/sender.h"
#include "main/main_session.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "ui/widgets/scroll_area.h" #include "ui/widgets/scroll_area.h"
#include "ui/search_field_controller.h" #include "ui/search_field_controller.h"
@ -27,10 +28,7 @@ namespace {
constexpr auto kCommonGroupsPerPage = 40; constexpr auto kCommonGroupsPerPage = 40;
constexpr auto kCommonGroupsSearchAfter = 20; constexpr auto kCommonGroupsSearchAfter = 20;
class ListController class ListController : public PeerListController , private base::Subscriber {
: public PeerListController
, private base::Subscriber
, private MTP::Sender {
public: public:
ListController( ListController(
not_null<Controller*> controller, not_null<Controller*> controller,
@ -58,6 +56,7 @@ private:
bool wasLoading = false; bool wasLoading = false;
}; };
const not_null<Controller*> _controller; const not_null<Controller*> _controller;
MTP::Sender _api;
not_null<UserData*> _user; not_null<UserData*> _user;
mtpRequestId _preloadRequestId = 0; mtpRequestId _preloadRequestId = 0;
bool _allLoaded = false; bool _allLoaded = false;
@ -70,6 +69,7 @@ ListController::ListController(
not_null<UserData*> user) not_null<UserData*> user)
: PeerListController() : PeerListController()
, _controller(controller) , _controller(controller)
, _api(_controller->session().api().instance())
, _user(user) { , _user(user) {
_controller->setSearchEnabledByContent(false); _controller->setSearchEnabledByContent(false);
} }
@ -95,7 +95,7 @@ void ListController::loadMoreRows() {
if (_preloadRequestId || _allLoaded) { if (_preloadRequestId || _allLoaded) {
return; return;
} }
_preloadRequestId = request(MTPmessages_GetCommonChats( _preloadRequestId = _api.request(MTPmessages_GetCommonChats(
_user->inputUser, _user->inputUser,
MTP_int(_preloadGroupId), MTP_int(_preloadGroupId),
MTP_int(kCommonGroupsPerPage) MTP_int(kCommonGroupsPerPage)
@ -143,7 +143,7 @@ void ListController::restoreState(
: nullptr; : nullptr;
if (auto my = dynamic_cast<SavedState*>(typeErasedState)) { if (auto my = dynamic_cast<SavedState*>(typeErasedState)) {
if (auto requestId = base::take(_preloadRequestId)) { if (auto requestId = base::take(_preloadRequestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
_allLoaded = my->allLoaded; _allLoaded = my->allLoaded;
_preloadGroupId = my->preloadGroupId; _preloadGroupId = my->preloadGroupId;

View File

@ -196,7 +196,7 @@ void Controller::updateSearchControllers(
auto searchQuery = memento->searchFieldQuery(); auto searchQuery = memento->searchFieldQuery();
if (isMedia) { if (isMedia) {
_searchController _searchController
= std::make_unique<Api::DelayedSearchController>(); = std::make_unique<Api::DelayedSearchController>(&session());
auto mediaMemento = dynamic_cast<Media::Memento*>(memento.get()); auto mediaMemento = dynamic_cast<Media::Memento*>(memento.get());
Assert(mediaMemento != nullptr); Assert(mediaMemento != nullptr);
_searchController->restoreState( _searchController->restoreState(

View File

@ -754,6 +754,7 @@ Widget::Widget(
not_null<Window::SessionController*> controller) not_null<Window::SessionController*> controller)
: RpWidget(parent) : RpWidget(parent)
, _controller(controller) , _controller(controller)
, _api(_controller->session().api().instance())
, _contentMaxHeight(st::emojiPanMaxHeight) , _contentMaxHeight(st::emojiPanMaxHeight)
, _contentHeight(_contentMaxHeight) , _contentHeight(_contentMaxHeight)
, _scroll(this, st::inlineBotsScroll) { , _scroll(this, st::inlineBotsScroll) {
@ -1133,9 +1134,16 @@ void Widget::onInlineRequest() {
} }
} }
Notify::inlineBotRequesting(true); Notify::inlineBotRequesting(true);
_inlineRequestId = request(MTPmessages_GetInlineBotResults(MTP_flags(0), _inlineBot->inputUser, _inlineQueryPeer->input, MTPInputGeoPoint(), MTP_string(_inlineQuery), MTP_string(nextOffset))).done([this](const MTPmessages_BotResults &result, mtpRequestId requestId) { _inlineRequestId = _api.request(MTPmessages_GetInlineBotResults(
MTP_flags(0),
_inlineBot->inputUser,
_inlineQueryPeer->input,
MTPInputGeoPoint(),
MTP_string(_inlineQuery),
MTP_string(nextOffset)
)).done([=](const MTPmessages_BotResults &result) {
inlineResultsDone(result); inlineResultsDone(result);
}).fail([this](const RPCError &error) { }).fail([=](const RPCError &error) {
// show error? // show error?
Notify::inlineBotRequesting(false); Notify::inlineBotRequesting(false);
_inlineRequestId = 0; _inlineRequestId = 0;

View File

@ -173,7 +173,7 @@ private:
} // namespace internal } // namespace internal
class Widget : public Ui::RpWidget, private MTP::Sender { class Widget : public Ui::RpWidget {
Q_OBJECT Q_OBJECT
public: public:
@ -246,6 +246,7 @@ private:
void inlineResultsDone(const MTPmessages_BotResults &result); void inlineResultsDone(const MTPmessages_BotResults &result);
not_null<Window::SessionController*> _controller; not_null<Window::SessionController*> _controller;
MTP::Sender _api;
int _contentMaxHeight = 0; int _contentMaxHeight = 0;
int _contentHeight = 0; int _contentHeight = 0;

View File

@ -170,12 +170,12 @@ QrWidget::QrWidget(
not_null<Main::Account*> account, not_null<Main::Account*> account,
not_null<Data*> data) not_null<Data*> data)
: Step(parent, account, data) : Step(parent, account, data)
, _api(account->mtp())
, _refreshTimer([=] { refreshCode(); }) { , _refreshTimer([=] { refreshCode(); }) {
setTitleText(rpl::single(QString())); setTitleText(rpl::single(QString()));
setDescriptionText(rpl::single(QString())); setDescriptionText(rpl::single(QString()));
setErrorCentered(true); setErrorCentered(true);
account->destroyStaleAuthorizationKeys();
account->mtpUpdates( account->mtpUpdates(
) | rpl::start_with_next([=](const MTPUpdates &updates) { ) | rpl::start_with_next([=](const MTPUpdates &updates) {
checkForTokenUpdate(updates); checkForTokenUpdate(updates);

View File

@ -52,9 +52,9 @@ private:
void showToken(const QByteArray &token); void showToken(const QByteArray &token);
void done(const MTPauth_Authorization &authorization); void done(const MTPauth_Authorization &authorization);
MTP::Sender _api;
rpl::event_stream<QByteArray> _qrCodes; rpl::event_stream<QByteArray> _qrCodes;
base::Timer _refreshTimer; base::Timer _refreshTimer;
MTP::Sender _api;
mtpRequestId _requestId = 0; mtpRequestId _requestId = 0;
bool _forceRefresh = false; bool _forceRefresh = false;

View File

@ -177,7 +177,6 @@ private:
object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _description; object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _description;
bool _errorCentered = false; bool _errorCentered = false;
bool _errorBelowLink = false;
rpl::variable<QString> _errorText; rpl::variable<QString> _errorText;
object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _error = { nullptr }; object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _error = { nullptr };

View File

@ -60,8 +60,6 @@ PhoneWidget::PhoneWidget(
_country->onChooseCountry(qsl("US")); _country->onChooseCountry(qsl("US"));
} }
_changed = false; _changed = false;
account->destroyStaleAuthorizationKeys();
} }
void PhoneWidget::resizeEvent(QResizeEvent *e) { void PhoneWidget::resizeEvent(QResizeEvent *e) {

View File

@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"
#include "ui/widgets/labels.h" #include "ui/widgets/labels.h"
#include "main/main_account.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "styles/style_intro.h" #include "styles/style_intro.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
@ -28,6 +29,7 @@ PwdCheckWidget::PwdCheckWidget(
not_null<Main::Account*> account, not_null<Main::Account*> account,
not_null<Data*> data) not_null<Data*> data)
: Step(parent, account, data) : Step(parent, account, data)
, _api(account->mtp())
, _request(getData()->pwdRequest) , _request(getData()->pwdRequest)
, _hasRecovery(getData()->hasRecovery) , _hasRecovery(getData()->hasRecovery)
, _notEmptyPassport(getData()->pwdNotEmptyPassport) , _notEmptyPassport(getData()->pwdNotEmptyPassport)
@ -115,7 +117,7 @@ void PwdCheckWidget::activate() {
} }
void PwdCheckWidget::cancelled() { void PwdCheckWidget::cancelled() {
request(base::take(_sentRequest)).cancel(); _api.request(base::take(_sentRequest)).cancel();
} }
void PwdCheckWidget::stopCheck() { void PwdCheckWidget::stopCheck() {
@ -127,7 +129,7 @@ void PwdCheckWidget::onCheckRequest() {
if (status < 0) { if (status < 0) {
auto leftms = -status; auto leftms = -status;
if (leftms >= 1000) { if (leftms >= 1000) {
request(base::take(_sentRequest)).cancel(); _api.request(base::take(_sentRequest)).cancel();
} }
} }
if (!_sentRequest && status == MTP::RequestSent) { if (!_sentRequest && status == MTP::RequestSent) {
@ -202,8 +204,8 @@ void PwdCheckWidget::checkPasswordHash() {
} }
void PwdCheckWidget::requestPasswordData() { void PwdCheckWidget::requestPasswordData() {
request(base::take(_sentRequest)).cancel(); _api.request(base::take(_sentRequest)).cancel();
_sentRequest = request( _sentRequest = _api.request(
MTPaccount_GetPassword() MTPaccount_GetPassword()
).done([=](const MTPaccount_Password &result) { ).done([=](const MTPaccount_Password &result) {
_sentRequest = 0; _sentRequest = 0;
@ -225,7 +227,7 @@ void PwdCheckWidget::passwordChecked() {
return serverError(); return serverError();
} }
_request.id = 0; _request.id = 0;
_sentRequest = request( _sentRequest = _api.request(
MTPauth_CheckPassword(check.result) MTPauth_CheckPassword(check.result)
).done([=](const MTPauth_Authorization &result) { ).done([=](const MTPauth_Authorization &result) {
pwdSubmitDone(false, result); pwdSubmitDone(false, result);
@ -289,7 +291,7 @@ void PwdCheckWidget::recoverStartFail(const RPCError &error) {
void PwdCheckWidget::onToRecover() { void PwdCheckWidget::onToRecover() {
if (_hasRecovery) { if (_hasRecovery) {
if (_sentRequest) { if (_sentRequest) {
request(base::take(_sentRequest)).cancel(); _api.request(base::take(_sentRequest)).cancel();
} }
hideError(); hideError();
_toRecover->hide(); _toRecover->hide();
@ -301,7 +303,7 @@ void PwdCheckWidget::onToRecover() {
_codeField->setFocus(); _codeField->setFocus();
updateDescriptionText(); updateDescriptionText();
if (_emailPattern.isEmpty()) { if (_emailPattern.isEmpty()) {
request( _api.request(
MTPauth_RequestPasswordRecovery() MTPauth_RequestPasswordRecovery()
).done([=](const MTPauth_PasswordRecovery &result) { ).done([=](const MTPauth_PasswordRecovery &result) {
recoverStarted(result); recoverStarted(result);
@ -320,7 +322,7 @@ void PwdCheckWidget::onToPassword() {
void PwdCheckWidget::showReset() { void PwdCheckWidget::showReset() {
if (_sentRequest) { if (_sentRequest) {
request(base::take(_sentRequest)).cancel(); _api.request(base::take(_sentRequest)).cancel();
} }
_toRecover->show(); _toRecover->show();
_toPassword->hide(); _toPassword->hide();
@ -355,7 +357,7 @@ void PwdCheckWidget::submit() {
return; return;
} }
const auto send = crl::guard(this, [=] { const auto send = crl::guard(this, [=] {
_sentRequest = request( _sentRequest = _api.request(
MTPauth_RecoverPassword(MTP_string(code)) MTPauth_RecoverPassword(MTP_string(code))
).done([=](const MTPauth_Authorization &result) { ).done([=](const MTPauth_Authorization &result) {
pwdSubmitDone(true, result); pwdSubmitDone(true, result);

View File

@ -21,7 +21,7 @@ class LinkButton;
namespace Intro { namespace Intro {
namespace details { namespace details {
class PwdCheckWidget : public Step, private MTP::Sender { class PwdCheckWidget : public Step {
Q_OBJECT Q_OBJECT
public: public:
@ -67,6 +67,7 @@ private:
void passwordChecked(); void passwordChecked();
void serverError(); void serverError();
MTP::Sender _api;
Core::CloudPasswordCheckRequest _request; Core::CloudPasswordCheckRequest _request;
crl::time _lastSrpIdInvalidTime = 0; crl::time _lastSrpIdInvalidTime = 0;
bytes::vector _passwordHash; bytes::vector _passwordHash;

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "intro/intro_qr.h" #include "intro/intro_qr.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/labels.h" #include "ui/widgets/labels.h"
#include "main/main_account.h"
namespace Intro { namespace Intro {
namespace details { namespace details {
@ -27,6 +28,7 @@ StartWidget::StartWidget(
} }
void StartWidget::submit() { void StartWidget::submit() {
account().destroyStaleAuthorizationKeys();
goNext<QrWidget>(); goNext<QrWidget>();
} }

View File

@ -50,30 +50,42 @@ Widget::Widget(QWidget *parent, not_null<Main::Account*> account)
st::defaultBoxButton)) st::defaultBoxButton))
, _next( , _next(
this, this,
object_ptr<Ui::RoundButton>( object_ptr<Ui::RoundButton>(this, nullptr, st::introNextButton))
, _connecting(std::make_unique<Window::ConnectionState>(
this, this,
nullptr, rpl::single(true))) {
st::introNextButton)) { appendStep(new StartWidget(this, _account, getData()));
fixOrder();
getData()->country = Platform::SystemCountry(); getData()->country = Platform::SystemCountry();
_account->mtpValue(
) | rpl::start_with_next([=](MTP::Instance *instance) {
if (instance) {
_api.emplace(instance);
createLanguageLink();
} else {
_api.reset();
}
}, lifetime());
subscribe(Lang::CurrentCloudManager().firstLanguageSuggestion(), [=] {
createLanguageLink();
});
_back->entity()->setClickedCallback([=] { _back->entity()->setClickedCallback([=] {
historyMove(Direction::Back); historyMove(Direction::Back);
}); });
_back->hide(anim::type::instant); _back->hide(anim::type::instant);
_next->entity()->setClickedCallback([this] { getStep()->submit(); }); _next->entity()->setClickedCallback([=] { getStep()->submit(); });
_settings->entity()->setClickedCallback([] { App::wnd()->showSettings(); }); _settings->entity()->setClickedCallback([] { App::wnd()->showSettings(); });
getNearestDC(); getNearestDC();
setupConnectingWidget();
appendStep(new StartWidget(this, _account, getData())); if (_changeLanguage) {
fixOrder(); _changeLanguage->finishAnimating();
}
subscribe(Lang::CurrentCloudManager().firstLanguageSuggestion(), [this] { createLanguageLink(); });
createLanguageLink();
if (_changeLanguage) _changeLanguage->finishAnimating();
subscribe(Lang::Current().updated(), [this] { refreshLang(); }); subscribe(Lang::Current().updated(), [this] { refreshLang(); });
@ -98,12 +110,6 @@ Widget::Widget(QWidget *parent, not_null<Main::Account*> account)
} }
} }
void Widget::setupConnectingWidget() {
_connecting = std::make_unique<Window::ConnectionState>(
this,
rpl::single(true));
}
void Widget::refreshLang() { void Widget::refreshLang() {
_changeLanguage.destroy(); _changeLanguage.destroy();
createLanguageLink(); createLanguageLink();
@ -111,9 +117,13 @@ void Widget::refreshLang() {
} }
void Widget::createLanguageLink() { void Widget::createLanguageLink() {
if (_changeLanguage) return; if (_changeLanguage) {
return;
}
auto createLink = [this](const QString &text, const QString &languageId) { const auto createLink = [=](
const QString &text,
const QString &languageId) {
_changeLanguage.create( _changeLanguage.create(
this, this,
object_ptr<Ui::LinkButton>(this, text)); object_ptr<Ui::LinkButton>(this, text));
@ -134,8 +144,8 @@ void Widget::createLanguageLink() {
createLink( createLink(
Lang::GetOriginalValue(tr::lng_switch_to_this.base), Lang::GetOriginalValue(tr::lng_switch_to_this.base),
defaultId); defaultId);
} else if (!suggested.isEmpty() && suggested != currentId) { } else if (!suggested.isEmpty() && suggested != currentId && _api) {
request(MTPlangpack_GetStrings( _api->request(MTPlangpack_GetStrings(
MTP_string(Lang::CloudLangPackName()), MTP_string(Lang::CloudLangPackName()),
MTP_string(suggested), MTP_string(suggested),
MTP_vector<MTPstring>(1, MTP_string("lng_switch_to_this")) MTP_vector<MTPstring>(1, MTP_string("lng_switch_to_this"))
@ -339,18 +349,24 @@ void Widget::acceptTerms(Fn<void()> callback) {
} }
void Widget::resetAccount() { void Widget::resetAccount() {
if (_resetRequest) return; if (_resetRequest || !_api) {
return;
}
Ui::show(Box<ConfirmBox>(tr::lng_signin_sure_reset(tr::now), tr::lng_signin_reset(tr::now), st::attentionBoxButton, crl::guard(this, [this] { Ui::show(Box<ConfirmBox>(tr::lng_signin_sure_reset(tr::now), tr::lng_signin_reset(tr::now), st::attentionBoxButton, crl::guard(this, [this] {
if (_resetRequest) return; if (_resetRequest) {
_resetRequest = request(MTPaccount_DeleteAccount(MTP_string("Forgot password"))).done([this](const MTPBool &result) { return;
}
_resetRequest = _api->request(MTPaccount_DeleteAccount(
MTP_string("Forgot password")
)).done([=](const MTPBool &result) {
_resetRequest = 0; _resetRequest = 0;
Ui::hideLayer(); Ui::hideLayer();
moveToStep( moveToStep(
new SignupWidget(this, _account, getData()), new SignupWidget(this, _account, getData()),
Direction::Replace); Direction::Replace);
}).fail([this](const RPCError &error) { }).fail([=](const RPCError &error) {
_resetRequest = 0; _resetRequest = 0;
const auto &type = error.type(); const auto &type = error.type();
@ -410,8 +426,12 @@ void Widget::resetAccount() {
} }
void Widget::getNearestDC() { void Widget::getNearestDC() {
request(MTPhelp_GetNearestDc()).done([this](const MTPNearestDc &result) { if (!_api) {
auto &nearest = result.c_nearestDc(); return;
}
_api->request(MTPhelp_GetNearestDc(
)).done([=](const MTPNearestDc &result) {
const auto &nearest = result.c_nearestDc();
DEBUG_LOG(("Got nearest dc, country: %1, nearest: %2, this: %3" DEBUG_LOG(("Got nearest dc, country: %1, nearest: %2, this: %3"
).arg(qs(nearest.vcountry()) ).arg(qs(nearest.vcountry())
).arg(nearest.vnearest_dc().v ).arg(nearest.vnearest_dc().v

View File

@ -72,10 +72,7 @@ class Step;
} // namespace details } // namespace details
class Widget class Widget : public Ui::RpWidget, private base::Subscriber {
: public Ui::RpWidget
, private MTP::Sender
, private base::Subscriber {
public: public:
Widget(QWidget *parent, not_null<Main::Account*> account); Widget(QWidget *parent, not_null<Main::Account*> account);
@ -91,7 +88,6 @@ protected:
void keyPressEvent(QKeyEvent *e) override; void keyPressEvent(QKeyEvent *e) override;
private: private:
void setupConnectingWidget();
void refreshLang(); void refreshLang();
void animationCallback(); void animationCallback();
void createLanguageLink(); void createLanguageLink();
@ -127,7 +123,8 @@ private:
void getNearestDC(); void getNearestDC();
void showTerms(Fn<void()> callback); void showTerms(Fn<void()> callback);
not_null<Main::Account*> _account; const not_null<Main::Account*> _account;
std::optional<MTP::Sender> _api;
Ui::Animations::Simple _a_show; Ui::Animations::Simple _a_show;
bool _showBack = false; bool _showBack = false;

View File

@ -13,8 +13,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/mtp_instance.h" #include "mtproto/mtp_instance.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "core/application.h" #include "core/application.h"
#include "apiwrap.h"
#include "main/main_session.h" #include "main/main_session.h"
#include "main/main_account.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "ui/wrap/padding_wrap.h" #include "ui/wrap/padding_wrap.h"
#include "ui/widgets/labels.h" #include "ui/widgets/labels.h"
@ -156,11 +156,17 @@ Language ParseLanguage(const MTPLangPackLanguage &data) {
}); });
} }
CloudManager::CloudManager( CloudManager::CloudManager(Instance &langpack)
Instance &langpack, : _langpack(langpack) {
not_null<MTP::Instance*> mtproto) Core::App().activeAccount().mtpValue(
: MTP::Sender() ) | rpl::start_with_next([=](MTP::Instance *instance) {
, _langpack(langpack) { if (instance) {
_api.emplace(instance);
resendRequests();
} else {
_api.reset();
}
}, _lifetime);
} }
Pack CloudManager::packTypeFromId(const QString &id) const { Pack CloudManager::packTypeFromId(const QString &id) const {
@ -195,7 +201,10 @@ mtpRequestId CloudManager::packRequestId(Pack pack) const {
} }
void CloudManager::requestLangPackDifference(Pack pack) { void CloudManager::requestLangPackDifference(Pack pack) {
request(base::take(packRequestId(pack))).cancel(); if (!_api) {
return;
}
_api->request(base::take(packRequestId(pack))).cancel();
if (_langpack.isCustom()) { if (_langpack.isCustom()) {
return; return;
} }
@ -206,7 +215,7 @@ void CloudManager::requestLangPackDifference(Pack pack) {
return; return;
} }
if (version > 0) { if (version > 0) {
packRequestId(pack) = request(MTPlangpack_GetDifference( packRequestId(pack) = _api->request(MTPlangpack_GetDifference(
MTP_string(CloudLangPackName()), MTP_string(CloudLangPackName()),
MTP_string(code), MTP_string(code),
MTP_int(version) MTP_int(version)
@ -217,7 +226,7 @@ void CloudManager::requestLangPackDifference(Pack pack) {
packRequestId(pack) = 0; packRequestId(pack) = 0;
}).send(); }).send();
} else { } else {
packRequestId(pack) = request(MTPlangpack_GetLangPack( packRequestId(pack) = _api->request(MTPlangpack_GetLangPack(
MTP_string(CloudLangPackName()), MTP_string(CloudLangPackName()),
MTP_string(code) MTP_string(code)
)).done([=](const MTPLangPackDifference &result) { )).done([=](const MTPLangPackDifference &result) {
@ -284,7 +293,12 @@ void CloudManager::applyLangPackDifference(
} }
void CloudManager::requestLanguageList() { void CloudManager::requestLanguageList() {
_languagesRequestId = request(MTPlangpack_GetLanguages( if (!_api) {
_languagesRequestId = -1;
return;
}
_api->request(base::take(_languagesRequestId)).cancel();
_languagesRequestId = _api->request(MTPlangpack_GetLanguages(
MTP_string(CloudLangPackName()) MTP_string(CloudLangPackName())
)).done([=](const MTPVector<MTPLangPackLanguage> &result) { )).done([=](const MTPVector<MTPLangPackLanguage> &result) {
auto languages = Languages(); auto languages = Languages();
@ -402,10 +416,20 @@ void CloudManager::requestLanguageAndSwitch(
return; return;
} }
request(_switchingToLanguageRequest).cancel(); _switchingToLanguageId = id;
_switchingToLanguageRequest = request(MTPlangpack_GetLanguage( _switchingToLanguageWarning = warning;
sendSwitchingToLanguageRequest();
}
void CloudManager::sendSwitchingToLanguageRequest() {
if (!_api) {
_switchingToLanguageId = -1;
return;
}
_api->request(_switchingToLanguageRequest).cancel();
_switchingToLanguageRequest = _api->request(MTPlangpack_GetLanguage(
MTP_string(Lang::CloudLangPackName()), MTP_string(Lang::CloudLangPackName()),
MTP_string(id) MTP_string(_switchingToLanguageId)
)).done([=](const MTPLangPackLanguage &result) { )).done([=](const MTPLangPackLanguage &result) {
_switchingToLanguageRequest = 0; _switchingToLanguageRequest = 0;
const auto language = Lang::ParseLanguage(result); const auto language = Lang::ParseLanguage(result);
@ -416,7 +440,7 @@ void CloudManager::requestLanguageAndSwitch(
performSwitchAndRestart(language); performSwitchAndRestart(language);
} }
}; };
if (!warning) { if (!_switchingToLanguageWarning) {
finalize(); finalize();
return; return;
} }
@ -438,9 +462,11 @@ void CloudManager::requestLanguageAndSwitch(
void CloudManager::switchToLanguage(const Language &data) { void CloudManager::switchToLanguage(const Language &data) {
if (_langpack.id() == data.id && data.id != qstr("#custom")) { if (_langpack.id() == data.id && data.id != qstr("#custom")) {
return; return;
} else if (!_api) {
return;
} }
request(_switchingToLanguageRequest).cancel(); _api->request(base::take(_getKeysForSwitchRequestId)).cancel();
if (data.id == qstr("#custom")) { if (data.id == qstr("#custom")) {
performSwitchToCustom(); performSwitchToCustom();
} else if (canApplyWithoutRestart(data.id)) { } else if (canApplyWithoutRestart(data.id)) {
@ -449,12 +475,12 @@ void CloudManager::switchToLanguage(const Language &data) {
QVector<MTPstring> keys; QVector<MTPstring> keys;
keys.reserve(3); keys.reserve(3);
keys.push_back(MTP_string("lng_sure_save_language")); keys.push_back(MTP_string("lng_sure_save_language"));
_switchingToLanguageRequest = request(MTPlangpack_GetStrings( _getKeysForSwitchRequestId = _api->request(MTPlangpack_GetStrings(
MTP_string(Lang::CloudLangPackName()), MTP_string(Lang::CloudLangPackName()),
MTP_string(data.id), MTP_string(data.id),
MTP_vector<MTPstring>(std::move(keys)) MTP_vector<MTPstring>(std::move(keys))
)).done([=](const MTPVector<MTPLangPackString> &result) { )).done([=](const MTPVector<MTPLangPackString> &result) {
_switchingToLanguageRequest = 0; _getKeysForSwitchRequestId = 0;
const auto values = Instance::ParseStrings(result); const auto values = Instance::ParseStrings(result);
const auto getValue = [&](ushort key) { const auto getValue = [&](ushort key) {
auto it = values.find(key); auto it = values.find(key);
@ -473,7 +499,7 @@ void CloudManager::switchToLanguage(const Language &data) {
[=] { performSwitchAndRestart(data); }), [=] { performSwitchAndRestart(data); }),
Ui::LayerOption::KeepOther); Ui::LayerOption::KeepOther);
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
_switchingToLanguageRequest = 0; _getKeysForSwitchRequestId = 0;
}).send(); }).send();
} }
} }
@ -481,7 +507,7 @@ void CloudManager::switchToLanguage(const Language &data) {
void CloudManager::performSwitchToCustom() { void CloudManager::performSwitchToCustom() {
auto filter = qsl("Language files (*.strings)"); auto filter = qsl("Language files (*.strings)");
auto title = qsl("Choose language .strings file"); auto title = qsl("Choose language .strings file");
FileDialog::GetOpenPath(Core::App().getFileDialogParent(), title, filter, [weak = base::make_weak(this)](const FileDialog::OpenResult &result) { FileDialog::GetOpenPath(Core::App().getFileDialogParent(), title, filter, [=, weak = base::make_weak(this)](const FileDialog::OpenResult &result) {
if (!weak || result.paths.isEmpty()) { if (!weak || result.paths.isEmpty()) {
return; return;
} }
@ -491,9 +517,13 @@ void CloudManager::performSwitchToCustom() {
filePath, filePath,
{ tr::lng_sure_save_language.base }); { tr::lng_sure_save_language.base });
if (loader.errors().isEmpty()) { if (loader.errors().isEmpty()) {
weak->request(weak->_switchingToLanguageRequest).cancel(); if (_api) {
if (weak->canApplyWithoutRestart(qsl("#custom"))) { _api->request(
weak->_langpack.switchToCustomFile(filePath); base::take(_switchingToLanguageRequest)
).cancel();
}
if (canApplyWithoutRestart(qsl("#custom"))) {
_langpack.switchToCustomFile(filePath);
} else { } else {
const auto values = loader.found(); const auto values = loader.found();
const auto getValue = [&](ushort key) { const auto getValue = [&](ushort key) {
@ -506,7 +536,7 @@ void CloudManager::performSwitchToCustom() {
+ "\n\n" + "\n\n"
+ getValue(tr::lng_sure_save_language.base); + getValue(tr::lng_sure_save_language.base);
const auto change = [=] { const auto change = [=] {
weak->_langpack.switchToCustomFile(filePath); _langpack.switchToCustomFile(filePath);
App::restart(); App::restart();
}; };
Ui::show( Ui::show(
@ -572,10 +602,26 @@ void CloudManager::switchLangPackId(const Language &data) {
void CloudManager::changeIdAndReInitConnection(const Language &data) { void CloudManager::changeIdAndReInitConnection(const Language &data) {
_langpack.switchToId(data); _langpack.switchToId(data);
if (_api) {
auto mtproto = requestMTP(); const auto mtproto = _api->instance();
mtproto->reInitConnection(mtproto->mainDcId()); mtproto->reInitConnection(mtproto->mainDcId());
} }
}
void CloudManager::resendRequests() {
if (packRequestId(Pack::Base)) {
requestLangPackDifference(Pack::Base);
}
if (packRequestId(Pack::Current)) {
requestLangPackDifference(Pack::Current);
}
if (_languagesRequestId) {
requestLanguageList();
}
if (_switchingToLanguageRequest) {
sendSwitchingToLanguageRequest();
}
}
CloudManager &CurrentCloudManager() { CloudManager &CurrentCloudManager() {
auto result = Core::App().langCloudManager(); auto result = Core::App().langCloudManager();

View File

@ -22,9 +22,9 @@ struct Language;
Language ParseLanguage(const MTPLangPackLanguage &data); Language ParseLanguage(const MTPLangPackLanguage &data);
class CloudManager : public base::has_weak_ptr, private MTP::Sender, private base::Subscriber { class CloudManager : public base::has_weak_ptr, private base::Subscriber {
public: public:
CloudManager(Instance &langpack, not_null<MTP::Instance*> mtproto); explicit CloudManager(Instance &langpack);
using Languages = std::vector<Language>; using Languages = std::vector<Language>;
@ -72,6 +72,10 @@ private:
void switchLangPackId(const Language &data); void switchLangPackId(const Language &data);
void changeIdAndReInitConnection(const Language &data); void changeIdAndReInitConnection(const Language &data);
void sendSwitchingToLanguageRequest();
void resendRequests();
std::optional<MTP::Sender> _api;
Instance &_langpack; Instance &_langpack;
Languages _languages; Languages _languages;
base::Observable<void> _languagesChanged; base::Observable<void> _languagesChanged;
@ -87,6 +91,12 @@ private:
base::Observable<void> _firstLanguageSuggestion; base::Observable<void> _firstLanguageSuggestion;
mtpRequestId _switchingToLanguageRequest = 0; mtpRequestId _switchingToLanguageRequest = 0;
QString _switchingToLanguageId;
bool _switchingToLanguageWarning = false;
mtpRequestId _getKeysForSwitchRequestId = 0;
rpl::lifetime _lifetime;
}; };

View File

@ -498,16 +498,16 @@ rpl::producer<> Account::configUpdates() const {
} }
void Account::resetAuthorizationKeys() { void Account::resetAuthorizationKeys() {
_mtpValue = nullptr;
_mtp = nullptr; _mtp = nullptr;
_mtpValue = _mtp.get();
startMtp(); startMtp();
Local::writeMtpData(); Local::writeMtpData();
} }
void Account::clearMtp() { void Account::clearMtp() {
_mtpValue = nullptr;
_mtp = nullptr; _mtp = nullptr;
_mtpForKeysDestroy = nullptr; _mtpForKeysDestroy = nullptr;
_mtpValue = _mtp.get();
} }
} // namespace Main } // namespace Main

View File

@ -29,7 +29,8 @@ LoaderMtproto::LoaderMtproto(
, _location(location) , _location(location)
, _dcId(location.dcId()) , _dcId(location.dcId())
, _size(size) , _size(size)
, _origin(origin) { , _origin(origin)
, _api(_owner->api().instance()) {
} }
LoaderMtproto::~LoaderMtproto() { LoaderMtproto::~LoaderMtproto() {
@ -68,7 +69,7 @@ void LoaderMtproto::stop() {
crl::on_main(this, [=] { crl::on_main(this, [=] {
ranges::for_each( ranges::for_each(
base::take(_requests), base::take(_requests),
_sender.requestCanceller(), _api.requestCanceller(),
&base::flat_map<int, mtpRequestId>::value_type::second); &base::flat_map<int, mtpRequestId>::value_type::second);
_requested.clear(); _requested.clear();
}); });
@ -82,7 +83,7 @@ void LoaderMtproto::cancel(int offset) {
void LoaderMtproto::cancelForOffset(int offset) { void LoaderMtproto::cancelForOffset(int offset) {
if (const auto requestId = _requests.take(offset)) { if (const auto requestId = _requests.take(offset)) {
_sender.request(*requestId).cancel(); _api.request(*requestId).cancel();
sendNext(); sendNext();
} else { } else {
_requested.remove(offset); _requested.remove(offset);
@ -122,7 +123,7 @@ void LoaderMtproto::sendNext() {
changeRequestedAmount(index, kPartSize); changeRequestedAmount(index, kPartSize);
const auto usedFileReference = _location.fileReference(); const auto usedFileReference = _location.fileReference();
const auto id = _sender.request(MTPupload_GetFile( const auto id = _api.request(MTPupload_GetFile(
MTP_flags(0), MTP_flags(0),
_location.tl(Auth().userId()), _location.tl(Auth().userId()),
MTP_int(offset), MTP_int(offset),

View File

@ -70,7 +70,7 @@ private:
const int _size = 0; const int _size = 0;
const Data::FileOrigin _origin; const Data::FileOrigin _origin;
MTP::Sender _sender; MTP::Sender _api;
PriorityQueue _requested; PriorityQueue _requested;
base::flat_map<int, mtpRequestId> _requests; base::flat_map<int, mtpRequestId> _requests;

View File

@ -262,7 +262,7 @@ Instance::Private::Private(
not_null<Instance*> instance, not_null<Instance*> instance,
not_null<DcOptions*> options, not_null<DcOptions*> options,
Instance::Mode mode) Instance::Mode mode)
: Sender() : Sender(instance)
, _instance(instance) , _instance(instance)
, _dcOptions(options) , _dcOptions(options)
, _mode(mode) { , _mode(mode) {

View File

@ -14,9 +14,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
namespace MTP { namespace MTP {
class Instance;
Instance *MainInstance();
class Sender { class Sender {
class RequestBuilder { class RequestBuilder {
public: public:
@ -104,11 +101,11 @@ class Sender {
bool operator()(mtpRequestId requestId, const RPCError &error) override { bool operator()(mtpRequestId requestId, const RPCError &error) override {
if (_skipPolicy == FailSkipPolicy::Simple) { if (_skipPolicy == FailSkipPolicy::Simple) {
if (MTP::isDefaultHandledError(error)) { if (isDefaultHandledError(error)) {
return false; return false;
} }
} else if (_skipPolicy == FailSkipPolicy::HandleFlood) { } else if (_skipPolicy == FailSkipPolicy::HandleFlood) {
if (MTP::isDefaultHandledError(error) && !MTP::isFloodError(error)) { if (isDefaultHandledError(error) && !isFloodError(error)) {
return false; return false;
} }
} }
@ -195,7 +192,12 @@ class Sender {
}; };
public: public:
Sender() noexcept { explicit Sender(not_null<Instance*> instance) noexcept
: _instance(instance) {
}
[[nodiscard]] not_null<Instance*> instance() const {
return _instance;
} }
template <typename Request> template <typename Request>
@ -245,7 +247,7 @@ public:
} }
mtpRequestId send() { mtpRequestId send() {
const auto id = MainInstance()->send( const auto id = sender()->instance()->send(
_request, _request,
takeOnDone(), takeOnDone(),
takeOnFail(), takeOnFail(),
@ -293,16 +295,13 @@ public:
} }
void requestSendDelayed() { void requestSendDelayed() {
MainInstance()->sendAnything(); _instance->sendAnything();
} }
void requestCancellingDiscard() { void requestCancellingDiscard() {
for (auto &request : _requests) { for (auto &request : _requests) {
request.handled(); request.handled();
} }
} }
not_null<Instance*> requestMTP() const {
return MainInstance();
}
private: private:
class RequestWrap { class RequestWrap {
@ -392,6 +391,7 @@ private:
} }
} }
const not_null<Instance*> _instance;
base::flat_set<RequestWrap, RequestWrapComparator> _requests; base::flat_set<RequestWrap, RequestWrapComparator> _requests;
}; };

View File

@ -30,6 +30,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/file_upload.h" #include "storage/file_upload.h"
#include "storage/file_download.h" #include "storage/file_download.h"
#include "app.h" #include "app.h"
#include "apiwrap.h"
#include <QtCore/QJsonDocument> #include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray> #include <QtCore/QJsonArray>
@ -620,6 +621,7 @@ FormController::FormController(
not_null<Window::SessionController*> controller, not_null<Window::SessionController*> controller,
const FormRequest &request) const FormRequest &request)
: _controller(controller) : _controller(controller)
, _api(_controller->session().api().instance())
, _request(PreprocessRequest(request)) , _request(PreprocessRequest(request))
, _shortPollTimer([=] { reloadPassword(); }) , _shortPollTimer([=] { reloadPassword(); })
, _view(std::make_unique<PanelController>(this)) { , _view(std::make_unique<PanelController>(this)) {
@ -741,7 +743,7 @@ std::vector<not_null<const Value*>> FormController::submitGetErrors() {
credentialsEncryptedData.secret, credentialsEncryptedData.secret,
bytes::make_span(_request.publicKey.toUtf8())); bytes::make_span(_request.publicKey.toUtf8()));
_submitRequestId = request(MTPaccount_AcceptAuthorization( _submitRequestId = _api.request(MTPaccount_AcceptAuthorization(
MTP_int(_request.botId), MTP_int(_request.botId),
MTP_string(_request.scope), MTP_string(_request.scope),
MTP_string(_request.publicKey), MTP_string(_request.publicKey),
@ -808,8 +810,8 @@ void FormController::requestPasswordData(mtpRequestId &guard) {
return passwordServerError(); return passwordServerError();
} }
request(base::take(guard)).cancel(); _api.request(base::take(guard)).cancel();
guard = request( guard = _api.request(
MTPaccount_GetPassword() MTPaccount_GetPassword()
).done([=, &guard](const MTPaccount_Password &result) { ).done([=, &guard](const MTPaccount_Password &result) {
guard = 0; guard = 0;
@ -843,7 +845,7 @@ void FormController::submitPassword(
const Core::CloudPasswordResult &check, const Core::CloudPasswordResult &check,
const QByteArray &password, const QByteArray &password,
bool submitSaved) { bool submitSaved) {
_passwordCheckRequestId = request(MTPaccount_GetPasswordSettings( _passwordCheckRequestId = _api.request(MTPaccount_GetPasswordSettings(
check.result check.result
)).handleFloodErrors( )).handleFloodErrors(
).done([=](const MTPaccount_PasswordSettings &result) { ).done([=](const MTPaccount_PasswordSettings &result) {
@ -936,7 +938,7 @@ void FormController::checkSavedPasswordSettings(
void FormController::checkSavedPasswordSettings( void FormController::checkSavedPasswordSettings(
const Core::CloudPasswordResult &check, const Core::CloudPasswordResult &check,
const SavedCredentials &credentials) { const SavedCredentials &credentials) {
_passwordCheckRequestId = request(MTPaccount_GetPasswordSettings( _passwordCheckRequestId = _api.request(MTPaccount_GetPasswordSettings(
check.result check.result
)).done([=](const MTPaccount_PasswordSettings &result) { )).done([=](const MTPaccount_PasswordSettings &result) {
Expects(result.type() == mtpc_account_passwordSettings); Expects(result.type() == mtpc_account_passwordSettings);
@ -982,7 +984,7 @@ void FormController::recoverPassword() {
} else if (_recoverRequestId) { } else if (_recoverRequestId) {
return; return;
} }
_recoverRequestId = request(MTPauth_RequestPasswordRecovery( _recoverRequestId = _api.request(MTPauth_RequestPasswordRecovery(
)).done([=](const MTPauth_PasswordRecovery &result) { )).done([=](const MTPauth_PasswordRecovery &result) {
Expects(result.type() == mtpc_auth_passwordRecovery); Expects(result.type() == mtpc_auth_passwordRecovery);
@ -1024,7 +1026,7 @@ void FormController::cancelPassword() {
if (_passwordRequestId) { if (_passwordRequestId) {
return; return;
} }
_passwordRequestId = request(MTPaccount_CancelPasswordEmail( _passwordRequestId = _api.request(MTPaccount_CancelPasswordEmail(
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
_passwordRequestId = 0; _passwordRequestId = 0;
reloadPassword(); reloadPassword();
@ -1093,7 +1095,7 @@ void FormController::resetSecret(
const Core::CloudPasswordResult &check, const Core::CloudPasswordResult &check,
const bytes::vector &password) { const bytes::vector &password) {
using Flag = MTPDaccount_passwordInputSettings::Flag; using Flag = MTPDaccount_passwordInputSettings::Flag;
_saveSecretRequestId = request(MTPaccount_UpdatePasswordSettings( _saveSecretRequestId = _api.request(MTPaccount_UpdatePasswordSettings(
check.result, check.result,
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(Flag::f_new_secure_settings), MTP_flags(Flag::f_new_secure_settings),
@ -1625,7 +1627,7 @@ void FormController::verify(
nonconst->verification.requestId = [&] { nonconst->verification.requestId = [&] {
switch (nonconst->type) { switch (nonconst->type) {
case Value::Type::Phone: case Value::Type::Phone:
return request(MTPaccount_VerifyPhone( return _api.request(MTPaccount_VerifyPhone(
MTP_string(getPhoneFromValue(nonconst)), MTP_string(getPhoneFromValue(nonconst)),
MTP_string(nonconst->verification.phoneCodeHash), MTP_string(nonconst->verification.phoneCodeHash),
MTP_string(prepared) MTP_string(prepared)
@ -1643,7 +1645,7 @@ void FormController::verify(
} }
}).send(); }).send();
case Value::Type::Email: case Value::Type::Email:
return request(MTPaccount_VerifyEmail( return _api.request(MTPaccount_VerifyEmail(
MTP_string(getEmailFromValue(nonconst)), MTP_string(getEmailFromValue(nonconst)),
MTP_string(prepared) MTP_string(prepared)
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
@ -1825,7 +1827,7 @@ void FormController::cancelValueVerification(not_null<const Value*> value) {
void FormController::clearValueVerification(not_null<Value*> value) { void FormController::clearValueVerification(not_null<Value*> value) {
const auto was = (value->verification.codeLength != 0); const auto was = (value->verification.codeLength != 0);
if (const auto requestId = base::take(value->verification.requestId)) { if (const auto requestId = base::take(value->verification.requestId)) {
request(requestId).cancel(); _api.request(requestId).cancel();
} }
value->verification = Verification(); value->verification = Verification();
if (was) { if (was) {
@ -1872,7 +1874,7 @@ void FormController::deleteValueEdit(not_null<const Value*> value) {
} }
const auto nonconst = findValue(value); const auto nonconst = findValue(value);
nonconst->saveRequestId = request(MTPaccount_DeleteSecureValue( nonconst->saveRequestId = _api.request(MTPaccount_DeleteSecureValue(
MTP_vector<MTPSecureValueType>(1, ConvertType(nonconst->type)) MTP_vector<MTPSecureValueType>(1, ConvertType(nonconst->type))
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
resetValue(*nonconst); resetValue(*nonconst);
@ -2019,7 +2021,7 @@ void FormController::sendSaveRequest(
const MTPInputSecureValue &data) { const MTPInputSecureValue &data) {
Expects(value->saveRequestId == 0); Expects(value->saveRequestId == 0);
value->saveRequestId = request(MTPaccount_SaveSecureValue( value->saveRequestId = _api.request(MTPaccount_SaveSecureValue(
data, data,
MTP_long(_secretId) MTP_long(_secretId)
)).done([=](const MTPSecureValue &result) { )).done([=](const MTPSecureValue &result) {
@ -2092,7 +2094,7 @@ QString FormController::getPlainTextFromValue(
} }
void FormController::startPhoneVerification(not_null<Value*> value) { void FormController::startPhoneVerification(not_null<Value*> value) {
value->verification.requestId = request(MTPaccount_SendVerifyPhoneCode( value->verification.requestId = _api.request(MTPaccount_SendVerifyPhoneCode(
MTP_string(getPhoneFromValue(value)), MTP_string(getPhoneFromValue(value)),
MTP_codeSettings(MTP_flags(0)) MTP_codeSettings(MTP_flags(0))
)).done([=](const MTPauth_SentCode &result) { )).done([=](const MTPauth_SentCode &result) {
@ -2149,7 +2151,7 @@ void FormController::startPhoneVerification(not_null<Value*> value) {
} }
void FormController::startEmailVerification(not_null<Value*> value) { void FormController::startEmailVerification(not_null<Value*> value) {
value->verification.requestId = request(MTPaccount_SendVerifyEmailCode( value->verification.requestId = _api.request(MTPaccount_SendVerifyEmailCode(
MTP_string(getEmailFromValue(value)) MTP_string(getEmailFromValue(value))
)).done([=](const MTPaccount_SentEmailCode &result) { )).done([=](const MTPaccount_SentEmailCode &result) {
Expects(result.type() == mtpc_account_sentEmailCode); Expects(result.type() == mtpc_account_sentEmailCode);
@ -2171,7 +2173,7 @@ void FormController::requestPhoneCall(not_null<Value*> value) {
value->verification.call->setStatus( value->verification.call->setStatus(
{ SentCodeCall::State::Calling, 0 }); { SentCodeCall::State::Calling, 0 });
request(MTPauth_ResendCode( _api.request(MTPauth_ResendCode(
MTP_string(getPhoneFromValue(value)), MTP_string(getPhoneFromValue(value)),
MTP_string(value->verification.phoneCodeHash) MTP_string(value->verification.phoneCodeHash)
)).done([=](const MTPauth_SentCode &code) { )).done([=](const MTPauth_SentCode &code) {
@ -2222,7 +2224,7 @@ void FormController::saveSecret(
saved.hashForSecret); saved.hashForSecret);
using Flag = MTPDaccount_passwordInputSettings::Flag; using Flag = MTPDaccount_passwordInputSettings::Flag;
_saveSecretRequestId = request(MTPaccount_UpdatePasswordSettings( _saveSecretRequestId = _api.request(MTPaccount_UpdatePasswordSettings(
check.result, check.result,
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(Flag::f_new_secure_settings), MTP_flags(Flag::f_new_secure_settings),
@ -2270,7 +2272,7 @@ void FormController::requestForm() {
formFail(NonceNameByScope(_request.scope).toUpper() + "_EMPTY"); formFail(NonceNameByScope(_request.scope).toUpper() + "_EMPTY");
return; return;
} }
_formRequestId = request(MTPaccount_GetAuthorizationForm( _formRequestId = _api.request(MTPaccount_GetAuthorizationForm(
MTP_int(_request.botId), MTP_int(_request.botId),
MTP_string(_request.scope), MTP_string(_request.scope),
MTP_string(_request.publicKey) MTP_string(_request.publicKey)
@ -2478,7 +2480,7 @@ void FormController::formDone(const MTPaccount_AuthorizationForm &result) {
void FormController::requestConfig() { void FormController::requestConfig() {
const auto hash = ConfigInstance().hash; const auto hash = ConfigInstance().hash;
_configRequestId = request(MTPhelp_GetPassportConfig( _configRequestId = _api.request(MTPhelp_GetPassportConfig(
MTP_int(hash) MTP_int(hash)
)).done([=](const MTPhelp_PassportConfig &result) { )).done([=](const MTPhelp_PassportConfig &result) {
_configRequestId = 0; _configRequestId = 0;
@ -2555,7 +2557,7 @@ void FormController::requestPassword() {
if (_passwordRequestId) { if (_passwordRequestId) {
return; return;
} }
_passwordRequestId = request(MTPaccount_GetPassword( _passwordRequestId = _api.request(MTPaccount_GetPassword(
)).done([=](const MTPaccount_Password &result) { )).done([=](const MTPaccount_Password &result) {
_passwordRequestId = 0; _passwordRequestId = 0;
passwordDone(result); passwordDone(result);

View File

@ -318,7 +318,7 @@ struct FileKey {
}; };
class FormController : private MTP::Sender, public base::has_weak_ptr { class FormController : public base::has_weak_ptr {
public: public:
FormController( FormController(
not_null<Window::SessionController*> controller, not_null<Window::SessionController*> controller,
@ -512,6 +512,7 @@ private:
void shortPollEmailConfirmation(); void shortPollEmailConfirmation();
not_null<Window::SessionController*> _controller; not_null<Window::SessionController*> _controller;
MTP::Sender _api;
FormRequest _request; FormRequest _request;
UserData *_bot = nullptr; UserData *_bot = nullptr;

View File

@ -180,7 +180,8 @@ AdminLog::OwnedItem GenerateForwardedItem(
BlockedBoxController::BlockedBoxController( BlockedBoxController::BlockedBoxController(
not_null<Window::SessionController*> window) not_null<Window::SessionController*> window)
: _window(window) { : _window(window)
, _api(_window->session().api().instance()) {
} }
Main::Session &BlockedBoxController::session() const { Main::Session &BlockedBoxController::session() const {
@ -220,7 +221,7 @@ void BlockedBoxController::loadMoreRows() {
return; return;
} }
_loadRequestId = request(MTPcontacts_GetBlocked( _loadRequestId = _api.request(MTPcontacts_GetBlocked(
MTP_int(_offset), MTP_int(_offset),
MTP_int(kBlockedPerPage) MTP_int(kBlockedPerPage)
)).done([=](const MTPcontacts_Blocked &result) { )).done([=](const MTPcontacts_Blocked &result) {

View File

@ -16,8 +16,7 @@ namespace Settings {
class BlockedBoxController class BlockedBoxController
: public PeerListController : public PeerListController
, private base::Subscriber , private base::Subscriber {
, private MTP::Sender {
public: public:
explicit BlockedBoxController( explicit BlockedBoxController(
not_null<Window::SessionController*> window); not_null<Window::SessionController*> window);
@ -39,6 +38,7 @@ private:
std::unique_ptr<PeerListRow> createRow(not_null<UserData*> user) const; std::unique_ptr<PeerListRow> createRow(not_null<UserData*> user) const;
const not_null<Window::SessionController*> _window; const not_null<Window::SessionController*> _window;
MTP::Sender _api;
int _offset = 0; int _offset = 0;
mtpRequestId _loadRequestId = 0; mtpRequestId _loadRequestId = 0;

View File

@ -288,10 +288,11 @@ TimeId OccupiedBySomeoneTill(History *history) {
Helper::Helper(not_null<Main::Session*> session) Helper::Helper(not_null<Main::Session*> session)
: _session(session) : _session(session)
, _api(_session->api().instance())
, _templates(_session) , _templates(_session)
, _reoccupyTimer([=] { reoccupy(); }) , _reoccupyTimer([=] { reoccupy(); })
, _checkOccupiedTimer([=] { checkOccupiedChats(); }) { , _checkOccupiedTimer([=] { checkOccupiedChats(); }) {
request(MTPhelp_GetSupportName( _api.request(MTPhelp_GetSupportName(
)).done([=](const MTPhelp_SupportName &result) { )).done([=](const MTPhelp_SupportName &result) {
result.match([&](const MTPDhelp_supportName &data) { result.match([&](const MTPDhelp_supportName &data) {
setSupportName(qs(data.vname())); setSupportName(qs(data.vname()));
@ -422,7 +423,7 @@ bool Helper::isOccupiedBySomeone(History *history) const {
} }
void Helper::refreshInfo(not_null<UserData*> user) { void Helper::refreshInfo(not_null<UserData*> user) {
request(MTPhelp_GetUserInfo( _api.request(MTPhelp_GetUserInfo(
user->inputUser user->inputUser
)).done([=](const MTPhelp_UserInfo &result) { )).done([=](const MTPhelp_UserInfo &result) {
applyInfo(user, result); applyInfo(user, result);
@ -531,7 +532,7 @@ void Helper::saveInfo(
return; return;
} else { } else {
i->second.data = text; i->second.data = text;
request(base::take(i->second.requestId)).cancel(); _api.request(base::take(i->second.requestId)).cancel();
} }
} else { } else {
_userInfoSaving.emplace(user, SavingInfo{ text }); _userInfoSaving.emplace(user, SavingInfo{ text });
@ -545,7 +546,7 @@ void Helper::saveInfo(
const auto entities = Api::EntitiesToMTP( const auto entities = Api::EntitiesToMTP(
text.entities, text.entities,
Api::ConvertOption::SkipLocal); Api::ConvertOption::SkipLocal);
_userInfoSaving[user].requestId = request(MTPhelp_EditUserInfo( _userInfoSaving[user].requestId = _api.request(MTPhelp_EditUserInfo(
user->inputUser, user->inputUser,
MTP_string(text.text), MTP_string(text.text),
entities entities

View File

@ -39,7 +39,7 @@ inline bool operator!=(const UserInfo &a, const UserInfo &b) {
return !(a == b); return !(a == b);
} }
class Helper : private MTP::Sender { class Helper final {
public: public:
explicit Helper(not_null<Main::Session*> session); explicit Helper(not_null<Main::Session*> session);
@ -87,6 +87,7 @@ private:
Fn<void(bool success)> done); Fn<void(bool success)> done);
not_null<Main::Session*> _session; not_null<Main::Session*> _session;
MTP::Sender _api;
Templates _templates; Templates _templates;
QString _supportName; QString _supportName;
QString _supportNameNormalized; QString _supportNameNormalized;