Remove App::app(), App::uploader(), App::api().

Also use Auth() instead of AuthSession::Current*().
This commit is contained in:
John Preston 2017-08-04 16:54:32 +02:00
parent 417f5684dc
commit ab35829358
72 changed files with 450 additions and 445 deletions

View file

@ -1601,7 +1601,7 @@ void ApiWrap::applyUpdatesNoPtsCheck(const MTPUpdates &updates) {
case mtpc_updateShortMessage: { case mtpc_updateShortMessage: {
auto &d = updates.c_updateShortMessage(); auto &d = updates.c_updateShortMessage();
auto flags = mtpCastFlags(d.vflags.v) | MTPDmessage::Flag::f_from_id; auto flags = mtpCastFlags(d.vflags.v) | MTPDmessage::Flag::f_from_id;
App::histories().addNewMessage(MTP_message(MTP_flags(flags), d.vid, d.is_out() ? MTP_int(AuthSession::CurrentUserId()) : d.vuser_id, MTP_peerUser(d.is_out() ? d.vuser_id : MTP_int(AuthSession::CurrentUserId())), d.vfwd_from, d.vvia_bot_id, d.vreply_to_msg_id, d.vdate, d.vmessage, MTP_messageMediaEmpty(), MTPnullMarkup, d.has_entities() ? d.ventities : MTPnullEntities, MTPint(), MTPint(), MTPstring()), NewMessageUnread); App::histories().addNewMessage(MTP_message(MTP_flags(flags), d.vid, d.is_out() ? MTP_int(Auth().userId()) : d.vuser_id, MTP_peerUser(d.is_out() ? d.vuser_id : MTP_int(Auth().userId())), d.vfwd_from, d.vvia_bot_id, d.vreply_to_msg_id, d.vdate, d.vmessage, MTP_messageMediaEmpty(), MTPnullMarkup, d.has_entities() ? d.ventities : MTPnullEntities, MTPint(), MTPint(), MTPstring()), NewMessageUnread);
} break; } break;
case mtpc_updateShortChatMessage: { case mtpc_updateShortChatMessage: {

View file

@ -158,12 +158,8 @@ namespace App {
return result; return result;
} }
Messenger *app() {
return Messenger::InstancePointer();
}
MainWindow *wnd() { MainWindow *wnd() {
if (auto instance = app()) { if (auto instance = Messenger::InstancePointer()) {
return instance->mainWindow(); return instance->mainWindow();
} }
return nullptr; return nullptr;
@ -183,14 +179,6 @@ namespace App {
return false; return false;
} }
FileUploader *uploader() {
return app() ? app()->uploader() : 0;
}
ApiWrap *api() {
return AuthSession::Exists() ? &AuthSession::Current().api() : nullptr;
}
namespace { namespace {
bool loggedOut() { bool loggedOut() {
if (Global::LocalPasscode()) { if (Global::LocalPasscode()) {
@ -211,7 +199,6 @@ namespace {
globalNotifyAllPtr = UnknownNotifySettings; globalNotifyAllPtr = UnknownNotifySettings;
globalNotifyUsersPtr = UnknownNotifySettings; globalNotifyUsersPtr = UnknownNotifySettings;
globalNotifyChatsPtr = UnknownNotifySettings; globalNotifyChatsPtr = UnknownNotifySettings;
if (App::uploader()) App::uploader()->clear();
clearStorageImages(); clearStorageImages();
if (auto w = wnd()) { if (auto w = wnd()) {
w->updateConnectingStatus(); w->updateConnectingStatus();
@ -473,7 +460,7 @@ namespace {
bool showPhoneChanged = !isServiceUser(data->id) && !d.is_self() && ((showPhone && data->contact) || (!showPhone && !data->contact)); bool showPhoneChanged = !isServiceUser(data->id) && !d.is_self() && ((showPhone && data->contact) || (!showPhone && !data->contact));
if (minimal) { if (minimal) {
showPhoneChanged = false; showPhoneChanged = false;
showPhone = !isServiceUser(data->id) && (data->id != AuthSession::CurrentUserPeerId()) && !data->contact; showPhone = !isServiceUser(data->id) && (data->id != Auth().userPeerId()) && !data->contact;
} }
// see also Local::readPeer // see also Local::readPeer
@ -534,14 +521,14 @@ namespace {
if (status && !minimal) { if (status && !minimal) {
auto oldOnlineTill = data->onlineTill; auto oldOnlineTill = data->onlineTill;
auto newOnlineTill = App::api()->onlineTillFromStatus(*status, oldOnlineTill); auto newOnlineTill = Auth().api().onlineTillFromStatus(*status, oldOnlineTill);
if (oldOnlineTill != newOnlineTill) { if (oldOnlineTill != newOnlineTill) {
data->onlineTill = newOnlineTill; data->onlineTill = newOnlineTill;
update.flags |= UpdateFlag::UserOnlineChanged; update.flags |= UpdateFlag::UserOnlineChanged;
} }
} }
if (data->contact < 0 && !data->phone().isEmpty() && data->id != AuthSession::CurrentUserPeerId()) { if (data->contact < 0 && !data->phone().isEmpty() && data->id != Auth().userPeerId()) {
data->contact = 0; data->contact = 0;
} }
if (App::main()) { if (App::main()) {
@ -839,7 +826,7 @@ namespace {
UserData *user = App::userLoaded(uid); UserData *user = App::userLoaded(uid);
if (user) { if (user) {
chat->participants[user] = pversion; chat->participants[user] = pversion;
if (inviter == AuthSession::CurrentUserId()) { if (inviter == Auth().userId()) {
chat->invitedByMe.insert(user); chat->invitedByMe.insert(user);
} }
if (i->type() == mtpc_chatParticipantAdmin) { if (i->type() == mtpc_chatParticipantAdmin) {
@ -863,7 +850,9 @@ namespace {
} else { } else {
if (i.key()->botInfo) { if (i.key()->botInfo) {
botStatus = 2;// (botStatus > 0/* || !i.key()->botInfo->readsAllHistory*/) ? 2 : 1; botStatus = 2;// (botStatus > 0/* || !i.key()->botInfo->readsAllHistory*/) ? 2 : 1;
if (requestBotInfos && !i.key()->botInfo->inited && App::api()) App::api()->requestFullPeer(i.key()); if (requestBotInfos && !i.key()->botInfo->inited) {
Auth().api().requestFullPeer(i.key());
}
} }
if (!found && i.key()->id == h->lastKeyboardFrom) { if (!found && i.key()->id == h->lastKeyboardFrom) {
found = true; found = true;
@ -897,7 +886,7 @@ namespace {
if (chat->version + 1 < d.vversion.v) { if (chat->version + 1 < d.vversion.v) {
chat->version = d.vversion.v; chat->version = d.vversion.v;
chat->invalidateParticipants(); chat->invalidateParticipants();
App::api()->requestPeer(chat); Auth().api().requestPeer(chat);
if (App::main()) { if (App::main()) {
if (emitPeerUpdated) { if (emitPeerUpdated) {
App::main()->peerUpdated(chat); App::main()->peerUpdated(chat);
@ -914,7 +903,7 @@ namespace {
chat->botStatus = 0; chat->botStatus = 0;
} else if (chat->participants.find(user) == chat->participants.end()) { } else if (chat->participants.find(user) == chat->participants.end()) {
chat->participants[user] = (chat->participants.isEmpty() ? 1 : chat->participants.begin().value()); chat->participants[user] = (chat->participants.isEmpty() ? 1 : chat->participants.begin().value());
if (d.vinviter_id.v == AuthSession::CurrentUserId()) { if (d.vinviter_id.v == Auth().userId()) {
chat->invitedByMe.insert(user); chat->invitedByMe.insert(user);
} else { } else {
chat->invitedByMe.remove(user); chat->invitedByMe.remove(user);
@ -922,7 +911,9 @@ namespace {
chat->count++; chat->count++;
if (user->botInfo) { if (user->botInfo) {
chat->botStatus = 2;// (chat->botStatus > 0/* || !user->botInfo->readsAllHistory*/) ? 2 : 1; chat->botStatus = 2;// (chat->botStatus > 0/* || !user->botInfo->readsAllHistory*/) ? 2 : 1;
if (!user->botInfo->inited && App::api()) App::api()->requestFullPeer(user); if (!user->botInfo->inited) {
Auth().api().requestFullPeer(user);
}
} }
} }
} else { } else {
@ -945,7 +936,7 @@ namespace {
if (chat->version + 1 < d.vversion.v) { if (chat->version + 1 < d.vversion.v) {
chat->version = d.vversion.v; chat->version = d.vversion.v;
chat->invalidateParticipants(); chat->invalidateParticipants();
App::api()->requestPeer(chat); Auth().api().requestPeer(chat);
if (App::main()) { if (App::main()) {
if (emitPeerUpdated) { if (emitPeerUpdated) {
App::main()->peerUpdated(chat); App::main()->peerUpdated(chat);
@ -1016,7 +1007,7 @@ namespace {
bool badVersion = (chat->version + 1 < d.vversion.v); bool badVersion = (chat->version + 1 < d.vversion.v);
if (badVersion) { if (badVersion) {
chat->invalidateParticipants(); chat->invalidateParticipants();
App::api()->requestPeer(chat); Auth().api().requestPeer(chat);
} }
chat->version = d.vversion.v; chat->version = d.vversion.v;
if (mtpIsTrue(d.venabled)) { if (mtpIsTrue(d.venabled)) {
@ -1041,7 +1032,7 @@ namespace {
if (chat->version + 1 < d.vversion.v) { if (chat->version + 1 < d.vversion.v) {
chat->version = d.vversion.v; chat->version = d.vversion.v;
chat->invalidateParticipants(); chat->invalidateParticipants();
App::api()->requestPeer(chat); Auth().api().requestPeer(chat);
if (App::main()) { if (App::main()) {
if (emitPeerUpdated) { if (emitPeerUpdated) {
App::main()->peerUpdated(chat); App::main()->peerUpdated(chat);
@ -1059,7 +1050,7 @@ namespace {
chat->flags |= MTPDchat::Flag::f_admin; chat->flags |= MTPDchat::Flag::f_admin;
} }
if (chat->noParticipantInfo()) { if (chat->noParticipantInfo()) {
App::api()->requestFullPeer(chat); Auth().api().requestFullPeer(chat);
} else { } else {
chat->admins.insert(user); chat->admins.insert(user);
} }
@ -1088,7 +1079,7 @@ namespace {
bool checkEntitiesAndViewsUpdate(const MTPDmessage &m) { bool checkEntitiesAndViewsUpdate(const MTPDmessage &m) {
auto peerId = peerFromMTP(m.vto_id); auto peerId = peerFromMTP(m.vto_id);
if (m.has_from_id() && peerId == AuthSession::CurrentUserPeerId()) { if (m.has_from_id() && peerId == Auth().userPeerId()) {
peerId = peerFromUser(m.vfrom_id); peerId = peerFromUser(m.vfrom_id);
} }
if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) { if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) {
@ -1113,7 +1104,7 @@ namespace {
template <typename TMTPDclass> template <typename TMTPDclass>
void updateEditedMessage(const TMTPDclass &m) { void updateEditedMessage(const TMTPDclass &m) {
auto peerId = peerFromMTP(m.vto_id); auto peerId = peerFromMTP(m.vto_id);
if (m.has_from_id() && peerId == AuthSession::CurrentUserPeerId()) { if (m.has_from_id() && peerId == Auth().userPeerId()) {
peerId = peerFromUser(m.vfrom_id); peerId = peerFromUser(m.vfrom_id);
} }
if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) { if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) {
@ -1138,9 +1129,9 @@ namespace {
if (saved.size() > Global::SavedGifsLimit()) saved.pop_back(); if (saved.size() > Global::SavedGifsLimit()) saved.pop_back();
Local::writeSavedGifs(); Local::writeSavedGifs();
AuthSession::Current().data().savedGifsUpdated().notify(); Auth().data().savedGifsUpdated().notify();
cSetLastSavedGifsUpdate(0); cSetLastSavedGifsUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} }
} }
@ -1316,7 +1307,7 @@ namespace {
break; break;
} }
if (user->contact < 1) { if (user->contact < 1) {
if (user->contact < 0 && !user->phone().isEmpty() && user->id != AuthSession::CurrentUserPeerId()) { if (user->contact < 0 && !user->phone().isEmpty() && user->id != Auth().userPeerId()) {
user->contact = 0; user->contact = 0;
} }
} }
@ -1808,7 +1799,9 @@ namespace {
convert->document = document; convert->document = document;
convert->duration = duration; convert->duration = duration;
convert->author = TextUtilities::Clean(author); convert->author = TextUtilities::Clean(author);
if (convert->pendingTill > 0 && pendingTill <= 0 && api()) api()->clearWebPageRequest(convert); if (convert->pendingTill > 0 && pendingTill <= 0) {
Auth().api().clearWebPageRequest(convert);
}
convert->pendingTill = pendingTill; convert->pendingTill = pendingTill;
if (App::main()) App::main()->webPageUpdated(convert); if (App::main()) App::main()->webPageUpdated(convert);
} }
@ -1820,8 +1813,8 @@ namespace {
result = convert; result = convert;
} else { } else {
result = new WebPageData(webPage, toWebPageType(type), url, displayUrl, siteName, title, description, document, photo, duration, author, (pendingTill >= -1) ? pendingTill : -1); result = new WebPageData(webPage, toWebPageType(type), url, displayUrl, siteName, title, description, document, photo, duration, author, (pendingTill >= -1) ? pendingTill : -1);
if (pendingTill > 0 && api()) { if (pendingTill > 0) {
api()->requestWebPageDelayed(result); Auth().api().requestWebPageDelayed(result);
} }
} }
webPagesData.insert(webPage, result); webPagesData.insert(webPage, result);
@ -1839,7 +1832,9 @@ namespace {
result->document = document; result->document = document;
result->duration = duration; result->duration = duration;
result->author = TextUtilities::Clean(author); result->author = TextUtilities::Clean(author);
if (result->pendingTill > 0 && pendingTill <= 0 && api()) api()->clearWebPageRequest(result); if (result->pendingTill > 0 && pendingTill <= 0) {
Auth().api().clearWebPageRequest(result);
}
result->pendingTill = pendingTill; result->pendingTill = pendingTill;
if (App::main()) App::main()->webPageUpdated(result); if (App::main()) App::main()->webPageUpdated(result);
} }
@ -2024,7 +2019,7 @@ namespace {
dependent->dependencyItemRemoved(item); dependent->dependencyItemRemoved(item);
} }
} }
AuthSession::Current().notifications().clearFromItem(item); Auth().notifications().clearFromItem(item);
if (Global::started() && !App::quitting()) { if (Global::started() && !App::quitting()) {
Global::RefItemRemoved().notify(item, true); Global::RefItemRemoved().notify(item, true);
} }
@ -2097,7 +2092,9 @@ namespace {
} }
::documentsData.clear(); ::documentsData.clear();
if (api()) api()->clearWebPageRequests(); if (AuthSession::Exists()) {
Auth().api().clearWebPageRequests();
}
cSetRecentStickers(RecentStickerPack()); cSetRecentStickers(RecentStickerPack());
Global::SetStickerSets(Stickers::Sets()); Global::SetStickerSets(Stickers::Sets());
Global::SetStickerSetsOrder(Stickers::Order()); Global::SetStickerSetsOrder(Stickers::Order());
@ -2325,7 +2322,7 @@ namespace {
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
// Clear notifications to prevent any showNotification() calls while destroying items. // Clear notifications to prevent any showNotification() calls while destroying items.
AuthSession::Current().notifications().clearAllFast(); Auth().notifications().clearAllFast();
} }
histories().clear(); histories().clear();

View file

@ -28,8 +28,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
class Messenger; class Messenger;
class MainWindow; class MainWindow;
class MainWidget; class MainWidget;
class ApiWrap;
class FileUploader;
using HistoryItemsMap = OrderedSet<HistoryItem*>; using HistoryItemsMap = OrderedSet<HistoryItem*>;
using PhotoItems = QHash<PhotoData*, HistoryItemsMap>; using PhotoItems = QHash<PhotoData*, HistoryItemsMap>;
@ -46,12 +44,9 @@ class LocationCoords;
struct LocationData; struct LocationData;
namespace App { namespace App {
Messenger *app();
MainWindow *wnd(); MainWindow *wnd();
MainWidget *main(); MainWidget *main();
bool passcoded(); bool passcoded();
FileUploader *uploader();
ApiWrap *api();
void logOut(); void logOut();

View file

@ -23,6 +23,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h" #include "messenger.h"
#include "storage/file_download.h" #include "storage/file_download.h"
#include "storage/file_upload.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "storage/serialize_common.h" #include "storage/serialize_common.h"
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
@ -152,12 +153,19 @@ QString AuthSessionData::getSoundPath(const QString &key) const {
return qsl(":/sounds/") + key + qsl(".mp3"); return qsl(":/sounds/") + key + qsl(".mp3");
} }
AuthSession &Auth() {
auto result = Messenger::Instance().authSession();
t_assert(result != nullptr);
return *result;
}
AuthSession::AuthSession(UserId userId) AuthSession::AuthSession(UserId userId)
: _userId(userId) : _userId(userId)
, _autoLockTimer([this] { checkAutoLock(); }) , _autoLockTimer([this] { checkAutoLock(); })
, _api(std::make_unique<ApiWrap>(this)) , _api(std::make_unique<ApiWrap>(this))
, _calls(std::make_unique<Calls::Instance>()) , _calls(std::make_unique<Calls::Instance>())
, _downloader(std::make_unique<Storage::Downloader>()) , _downloader(std::make_unique<Storage::Downloader>())
, _uploader(std::make_unique<Storage::Uploader>())
, _notifications(std::make_unique<Window::Notifications::System>(this)) { , _notifications(std::make_unique<Window::Notifications::System>(this)) {
Expects(_userId != 0); Expects(_userId != 0);
_saveDataTimer.setCallback([this] { _saveDataTimer.setCallback([this] {
@ -177,18 +185,12 @@ bool AuthSession::Exists() {
return false; return false;
} }
AuthSession &AuthSession::Current() { UserData *AuthSession::user() const {
auto result = Messenger::Instance().authSession(); return App::user(userId());
t_assert(result != nullptr);
return *result;
} }
UserData *AuthSession::CurrentUser() { base::Observable<void> &AuthSession::downloaderTaskFinished() {
return App::user(CurrentUserId()); return downloader().taskFinished();
}
base::Observable<void> &AuthSession::CurrentDownloaderTaskFinished() {
return Current().downloader().taskFinished();
} }
bool AuthSession::validateSelf(const MTPUser &user) { bool AuthSession::validateSelf(const MTPUser &user) {
@ -201,7 +203,7 @@ bool AuthSession::validateSelf(const MTPUser &user) {
} }
void AuthSession::saveDataDelayed(TimeMs delay) { void AuthSession::saveDataDelayed(TimeMs delay) {
Expects(this == &AuthSession::Current()); Expects(this == &Auth());
_saveDataTimer.callOnce(delay); _saveDataTimer.callOnce(delay);
} }

View file

@ -24,6 +24,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
namespace Storage { namespace Storage {
class Downloader; class Downloader;
class Uploader;
} // namespace Storage } // namespace Storage
namespace Window { namespace Window {
@ -156,6 +157,10 @@ private:
}; };
// One per Messenger.
class AuthSession;
AuthSession &Auth();
class AuthSession final : private base::Subscriber { class AuthSession final : private base::Subscriber {
public: public:
AuthSession(UserId userId); AuthSession(UserId userId);
@ -165,25 +170,23 @@ public:
static bool Exists(); static bool Exists();
static AuthSession &Current();
static UserId CurrentUserId() {
return Current().userId();
}
static PeerId CurrentUserPeerId() {
return peerFromUser(CurrentUserId());
}
static UserData *CurrentUser();
UserId userId() const { UserId userId() const {
return _userId; return _userId;
} }
PeerId userPeerId() const {
return peerFromUser(userId());
}
UserData *user() const;
bool validateSelf(const MTPUser &user); bool validateSelf(const MTPUser &user);
Storage::Downloader &downloader() { Storage::Downloader &downloader() {
return *_downloader; return *_downloader;
} }
Storage::Uploader &uploader() {
return *_uploader;
}
static base::Observable<void> &CurrentDownloaderTaskFinished(); base::Observable<void> &downloaderTaskFinished();
Window::Notifications::System &notifications() { Window::Notifications::System &notifications() {
return *_notifications; return *_notifications;
@ -218,6 +221,7 @@ private:
const std::unique_ptr<ApiWrap> _api; const std::unique_ptr<ApiWrap> _api;
const std::unique_ptr<Calls::Instance> _calls; const std::unique_ptr<Calls::Instance> _calls;
const std::unique_ptr<Storage::Downloader> _downloader; const std::unique_ptr<Storage::Downloader> _downloader;
const std::unique_ptr<Storage::Uploader> _uploader;
const std::unique_ptr<Window::Notifications::System> _notifications; const std::unique_ptr<Window::Notifications::System> _notifications;
}; };

View file

@ -413,7 +413,7 @@ void GroupInfoBox::creationDone(const MTPUpdates &updates) {
channel = App::channel(v->front().c_channel().vid.v); channel = App::channel(v->front().c_channel().vid.v);
if (channel) { if (channel) {
if (!_photoImage.isNull()) { if (!_photoImage.isNull()) {
App::app()->uploadProfilePhoto(_photoImage, channel->id); Messenger::Instance().uploadProfilePhoto(_photoImage, channel->id);
} }
_createdChannel = channel; _createdChannel = channel;
_creationRequestId = MTP::send(MTPchannels_ExportInvite(_createdChannel->inputChannel), rpcDone(&GroupInfoBox::exportDone)); _creationRequestId = MTP::send(MTPchannels_ExportInvite(_createdChannel->inputChannel), rpcDone(&GroupInfoBox::exportDone));
@ -594,7 +594,7 @@ void SetupChannelBox::mouseMoveEvent(QMouseEvent *e) {
void SetupChannelBox::mousePressEvent(QMouseEvent *e) { void SetupChannelBox::mousePressEvent(QMouseEvent *e) {
if (_linkOver) { if (_linkOver) {
if (_channel->inviteLink().isEmpty()) { if (_channel->inviteLink().isEmpty()) {
App::api()->exportInviteLink(_channel); Auth().api().exportInviteLink(_channel);
} else { } else {
QGuiApplication::clipboard()->setText(_channel->inviteLink()); QGuiApplication::clipboard()->setText(_channel->inviteLink());
Ui::Toast::Show(lang(lng_create_channel_link_copied)); Ui::Toast::Show(lang(lng_create_channel_link_copied));
@ -1234,9 +1234,7 @@ bool EditChannelBox::onSaveFail(const RPCError &error, mtpRequestId req) {
_saveDescriptionRequestId = 0; _saveDescriptionRequestId = 0;
if (err == qstr("CHAT_ABOUT_NOT_MODIFIED")) { if (err == qstr("CHAT_ABOUT_NOT_MODIFIED")) {
if (_channel->setAbout(_sentDescription)) { if (_channel->setAbout(_sentDescription)) {
if (App::api()) { Auth().api().fullPeerUpdated().notify(_channel);
App::api()->fullPeerUpdated().notify(_channel);
}
} }
saveSign(); saveSign();
return true; return true;
@ -1261,29 +1259,27 @@ bool EditChannelBox::onSaveFail(const RPCError &error, mtpRequestId req) {
void EditChannelBox::onSaveTitleDone(const MTPUpdates &result) { void EditChannelBox::onSaveTitleDone(const MTPUpdates &result) {
_saveTitleRequestId = 0; _saveTitleRequestId = 0;
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
saveDescription(); saveDescription();
} }
void EditChannelBox::onSaveDescriptionDone(const MTPBool &result) { void EditChannelBox::onSaveDescriptionDone(const MTPBool &result) {
_saveDescriptionRequestId = 0; _saveDescriptionRequestId = 0;
if (_channel->setAbout(_sentDescription)) { if (_channel->setAbout(_sentDescription)) {
if (App::api()) { Auth().api().fullPeerUpdated().notify(_channel);
App::api()->fullPeerUpdated().notify(_channel);
}
} }
saveSign(); saveSign();
} }
void EditChannelBox::onSaveSignDone(const MTPUpdates &result) { void EditChannelBox::onSaveSignDone(const MTPUpdates &result) {
_saveSignRequestId = 0; _saveSignRequestId = 0;
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
saveInvites(); saveInvites();
} }
void EditChannelBox::onSaveInvitesDone(const MTPUpdates &result) { void EditChannelBox::onSaveInvitesDone(const MTPUpdates &result) {
_saveSignRequestId = 0; _saveSignRequestId = 0;
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
closeBox(); closeBox();
} }
@ -1332,7 +1328,7 @@ void RevokePublicLinkBox::prepare() {
addButton(langFactory(lng_cancel), [this] { closeBox(); }); addButton(langFactory(lng_cancel), [this] { closeBox(); });
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
_inner->resizeToWidth(st::boxWideWidth); _inner->resizeToWidth(st::boxWideWidth);
setDimensions(st::boxWideWidth, _innerTop + _inner->height()); setDimensions(st::boxWideWidth, _innerTop + _inner->height());

View file

@ -52,6 +52,6 @@ void AutoLockBox::durationChanged(int seconds) {
Local::writeUserSettings(); Local::writeUserSettings();
Global::RefLocalPasscodeChanged().notify(); Global::RefLocalPasscodeChanged().notify();
AuthSession::Current().checkAutoLock(); Auth().checkAutoLock();
closeBox(); closeBox();
} }

View file

@ -94,7 +94,7 @@ BackgroundBox::Inner::Inner(QWidget *parent) : TWidget(parent)
updateWallpapers(); updateWallpapers();
} }
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &update) { subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &update) {
if (update.paletteChanged()) { if (update.paletteChanged()) {
_check->invalidateCache(); _check->invalidateCache();

View file

@ -246,7 +246,7 @@ void MaxInviteBox::mousePressEvent(QMouseEvent *e) {
mouseMoveEvent(e); mouseMoveEvent(e);
if (_linkOver) { if (_linkOver) {
if (_channel->inviteLink().isEmpty()) { if (_channel->inviteLink().isEmpty()) {
App::api()->exportInviteLink(_channel); Auth().api().exportInviteLink(_channel);
} else { } else {
QGuiApplication::clipboard()->setText(_channel->inviteLink()); QGuiApplication::clipboard()->setText(_channel->inviteLink());
Ui::Toast::Show(lang(lng_create_channel_link_copied)); Ui::Toast::Show(lang(lng_create_channel_link_copied));
@ -329,7 +329,7 @@ void ConvertToSupergroupBox::convertDone(const MTPUpdates &updates) {
if (mtpChat.type() == mtpc_channel) { if (mtpChat.type() == mtpc_channel) {
auto channel = App::channel(mtpChat.c_channel().vid.v); auto channel = App::channel(mtpChat.c_channel().vid.v);
Ui::showPeerHistory(channel, ShowAtUnreadMsgId); Ui::showPeerHistory(channel, ShowAtUnreadMsgId);
App::api()->requestParticipantsCountDelayed(channel); Auth().api().requestParticipantsCountDelayed(channel);
} }
} }
}; };
@ -543,7 +543,7 @@ void DeleteMessagesBox::deleteAndClear() {
if (_moderateFrom) { if (_moderateFrom) {
if (_banUser && _banUser->checked()) { if (_banUser && _banUser->checked()) {
App::api()->kickParticipant(_moderateInChannel, _moderateFrom, MTP_channelBannedRights(MTP_flags(0), MTP_int(0))); Auth().api().kickParticipant(_moderateInChannel, _moderateFrom, MTP_channelBannedRights(MTP_flags(0), MTP_int(0)));
} }
if (_reportSpam->checked()) { if (_reportSpam->checked()) {
MTP::send(MTPchannels_ReportSpam(_moderateInChannel->inputChannel, _moderateFrom->inputUser, MTP_vector<MTPint>(1, MTP_int(_ids[0].msg)))); MTP::send(MTPchannels_ReportSpam(_moderateInChannel->inputChannel, _moderateFrom->inputUser, MTP_vector<MTPint>(1, MTP_int(_ids[0].msg))));
@ -602,7 +602,7 @@ ConfirmInviteBox::ConfirmInviteBox(QWidget*, const QString &title, bool isChanne
if (!location.isNull()) { if (!location.isNull()) {
_photo = ImagePtr(location); _photo = ImagePtr(location);
if (!_photo->loaded()) { if (!_photo->loaded()) {
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
_photo->load(); _photo->load();
} }
} }

View file

@ -426,7 +426,7 @@ void ContactsBox::saveSelectedAdmins() {
} }
void ContactsBox::getAdminsDone(const MTPmessages_ChatFull &result) { void ContactsBox::getAdminsDone(const MTPmessages_ChatFull &result) {
App::api()->processFullPeer(_inner->chat(), result); Auth().api().processFullPeer(_inner->chat(), result);
if (_inner->allAdmins()) { if (_inner->allAdmins()) {
closeBox(); closeBox();
return; return;
@ -466,7 +466,7 @@ void ContactsBox::getAdminsDone(const MTPmessages_ChatFull &result) {
void ContactsBox::setAdminDone(gsl::not_null<UserData*> user, const MTPBool &result) { void ContactsBox::setAdminDone(gsl::not_null<UserData*> user, const MTPBool &result) {
if (mtpIsTrue(result)) { if (mtpIsTrue(result)) {
if (_inner->chat()->noParticipantInfo()) { if (_inner->chat()->noParticipantInfo()) {
App::api()->requestFullPeer(_inner->chat()); Auth().api().requestFullPeer(_inner->chat());
} else { } else {
_inner->chat()->admins.insert(user); _inner->chat()->admins.insert(user);
} }
@ -529,7 +529,7 @@ void ContactsBox::creationDone(const MTPUpdates &updates) {
peer = App::chat(v->front().c_chat().vid.v); peer = App::chat(v->front().c_chat().vid.v);
if (peer) { if (peer) {
if (!_creationPhoto.isNull()) { if (!_creationPhoto.isNull()) {
App::app()->uploadProfilePhoto(_creationPhoto, peer->id); Messenger::Instance().uploadProfilePhoto(_creationPhoto, peer->id);
} }
Ui::showPeerHistory(peer, ShowAtUnreadMsgId); Ui::showPeerHistory(peer, ShowAtUnreadMsgId);
} }
@ -608,7 +608,7 @@ ContactsBox::Inner::Inner(QWidget *parent, ChatData *chat, MembersFilter members
if (membersFilter == MembersFilter::Admins) { if (membersFilter == MembersFilter::Admins) {
_aboutHeight = st::contactsAboutTop + qMax(_aboutAllAdmins.countHeight(_aboutWidth), _aboutAdmins.countHeight(_aboutWidth)) + st::contactsAboutBottom; _aboutHeight = st::contactsAboutTop + qMax(_aboutAllAdmins.countHeight(_aboutWidth), _aboutAdmins.countHeight(_aboutWidth)) + st::contactsAboutBottom;
if (_contacts->isEmpty()) { if (_contacts->isEmpty()) {
App::api()->requestFullPeer(_chat); Auth().api().requestFullPeer(_chat);
} }
} }
init(); init();
@ -656,7 +656,7 @@ ContactsBox::Inner::Inner(QWidget *parent, UserData *bot) : TWidget(parent)
} }
void ContactsBox::Inner::init() { void ContactsBox::Inner::init() {
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
connect(_addContactLnk, SIGNAL(clicked()), App::wnd(), SLOT(onShowAddContact())); connect(_addContactLnk, SIGNAL(clicked()), App::wnd(), SLOT(onShowAddContact()));
subscribe(_allAdmins->checkedChanged, [this](bool checked) { onAllAdminsChanged(); }); subscribe(_allAdmins->checkedChanged, [this](bool checked) { onAllAdminsChanged(); });
@ -835,7 +835,7 @@ void ContactsBox::Inner::loadProfilePhotos() {
auto yFrom = _visibleTop - _rowsTop; auto yFrom = _visibleTop - _rowsTop;
auto yTo = yFrom + (_visibleBottom - _visibleTop) * 5; auto yTo = yFrom + (_visibleBottom - _visibleTop) * 5;
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
if (yTo < 0) return; if (yTo < 0) return;
if (yFrom < 0) yFrom = 0; if (yFrom < 0) yFrom = 0;
@ -878,9 +878,9 @@ ContactsBox::Inner::ContactData *ContactsBox::Inner::contactData(Dialogs::Row *r
data->disabledChecked = _chat->participants.contains(peer->asUser()); data->disabledChecked = _chat->participants.contains(peer->asUser());
} }
} else if (_creating == CreatingGroupGroup) { } else if (_creating == CreatingGroupGroup) {
data->disabledChecked = (peer->id == AuthSession::CurrentUserPeerId()); data->disabledChecked = (peer->id == Auth().userPeerId());
} else if (_channel) { } else if (_channel) {
data->disabledChecked = (peer->id == AuthSession::CurrentUserPeerId()) || _already.contains(peer->asUser()); data->disabledChecked = (peer->id == Auth().userPeerId()) || _already.contains(peer->asUser());
} }
} }
if (usingMultiSelect() && _checkedContacts.contains(peer)) { if (usingMultiSelect() && _checkedContacts.contains(peer)) {
@ -1090,7 +1090,7 @@ void ContactsBox::Inner::paintEvent(QPaintEvent *e) {
QString text; QString text;
skip = 0; skip = 0;
if (bot()) { if (bot()) {
text = lang((AuthSession::Current().data().allChatsLoaded().value() && !_searching) ? (sharingBotGame() ? lng_bot_no_chats : lng_bot_no_groups) : lng_contacts_loading); text = lang((Auth().data().allChatsLoaded().value() && !_searching) ? (sharingBotGame() ? lng_bot_no_chats : lng_bot_no_groups) : lng_contacts_loading);
} else if (_chat && _membersFilter == MembersFilter::Admins) { } else if (_chat && _membersFilter == MembersFilter::Admins) {
text = lang(lng_contacts_loading); text = lang(lng_contacts_loading);
p.fillRect(0, 0, width(), _aboutHeight - st::contactsPadding.bottom() - st::lineWidth, st::contactsAboutBg); p.fillRect(0, 0, width(), _aboutHeight - st::contactsPadding.bottom() - st::lineWidth, st::contactsAboutBg);
@ -1099,7 +1099,7 @@ void ContactsBox::Inner::paintEvent(QPaintEvent *e) {
int aboutw = width() - st::contactsPadding.left() - st::contactsPadding.right(); int aboutw = width() - st::contactsPadding.left() - st::contactsPadding.right();
(_allAdmins->checked() ? _aboutAllAdmins : _aboutAdmins).draw(p, st::contactsPadding.left(), st::contactsAboutTop, aboutw); (_allAdmins->checked() ? _aboutAllAdmins : _aboutAdmins).draw(p, st::contactsPadding.left(), st::contactsAboutTop, aboutw);
p.translate(0, _aboutHeight); p.translate(0, _aboutHeight);
} else if (AuthSession::Current().data().contactsLoaded().value() && !_searching) { } else if (Auth().data().contactsLoaded().value() && !_searching) {
text = lang(lng_no_contacts); text = lang(lng_no_contacts);
skip = st::noContactsFont->height; skip = st::noContactsFont->height;
} else { } else {
@ -1115,11 +1115,11 @@ void ContactsBox::Inner::paintEvent(QPaintEvent *e) {
p.setPen(st::noContactsColor); p.setPen(st::noContactsColor);
QString text; QString text;
if (bot()) { if (bot()) {
text = lang((AuthSession::Current().data().allChatsLoaded().value() && !_searching) ? (sharingBotGame() ? lng_bot_chats_not_found : lng_bot_groups_not_found) : lng_contacts_loading); text = lang((Auth().data().allChatsLoaded().value() && !_searching) ? (sharingBotGame() ? lng_bot_chats_not_found : lng_bot_groups_not_found) : lng_contacts_loading);
} else if (_chat && _membersFilter == MembersFilter::Admins) { } else if (_chat && _membersFilter == MembersFilter::Admins) {
text = lang(_chat->participants.isEmpty() ? lng_contacts_loading : lng_contacts_not_found); text = lang(_chat->participants.isEmpty() ? lng_contacts_loading : lng_contacts_not_found);
} else { } else {
text = lang((AuthSession::Current().data().contactsLoaded().value() && !_searching) ? lng_contacts_not_found : lng_contacts_loading); text = lang((Auth().data().contactsLoaded().value() && !_searching) ? lng_contacts_not_found : lng_contacts_loading);
} }
p.drawText(QRect(0, 0, width(), st::noContactsHeight), text, style::al_center); p.drawText(QRect(0, 0, width(), st::noContactsHeight), text, style::al_center);
} else { } else {
@ -1775,7 +1775,7 @@ void ContactsBox::Inner::refresh() {
if (!_addContactLnk->isHidden()) _addContactLnk->hide(); if (!_addContactLnk->isHidden()) _addContactLnk->hide();
resize(width(), _rowsTop + _aboutHeight + st::noContactsHeight + st::contactsMarginBottom); resize(width(), _rowsTop + _aboutHeight + st::noContactsHeight + st::contactsMarginBottom);
} else { } else {
if (AuthSession::Current().data().contactsLoaded().value() && !bot()) { if (Auth().data().contactsLoaded().value() && !bot()) {
if (_addContactLnk->isHidden()) _addContactLnk->show(); if (_addContactLnk->isHidden()) _addContactLnk->show();
} else { } else {
if (!_addContactLnk->isHidden()) _addContactLnk->hide(); if (!_addContactLnk->isHidden()) _addContactLnk->hide();

View file

@ -27,6 +27,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "ui/effects/widget_slide_wrap.h" #include "ui/effects/widget_slide_wrap.h"
#include "boxes/peer_list_box.h" #include "boxes/peer_list_box.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
namespace { namespace {
@ -302,7 +303,7 @@ void EditPrivacyBox::createWidgets() {
addButton(langFactory(lng_settings_save), [this] { addButton(langFactory(lng_settings_save), [this] {
auto someAreDisallowed = (_option != Option::Everyone) || !_neverUsers.empty(); auto someAreDisallowed = (_option != Option::Everyone) || !_neverUsers.empty();
_controller->confirmSave(someAreDisallowed, base::lambda_guarded(this, [this] { _controller->confirmSave(someAreDisallowed, base::lambda_guarded(this, [this] {
App::api()->savePrivacy(_controller->key(), collectResult()); Auth().api().savePrivacy(_controller->key(), collectResult());
closeBox(); closeBox();
})); }));
}); });

View file

@ -41,7 +41,7 @@ void LocalStorageBox::prepare() {
connect(App::wnd(), SIGNAL(tempDirCleared(int)), this, SLOT(onTempDirCleared(int))); connect(App::wnd(), SIGNAL(tempDirCleared(int)), this, SLOT(onTempDirCleared(int)));
connect(App::wnd(), SIGNAL(tempDirClearFailed(int)), this, SLOT(onTempDirClearFailed(int))); connect(App::wnd(), SIGNAL(tempDirClearFailed(int)), this, SLOT(onTempDirClearFailed(int)));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
updateControls(); updateControls();

View file

@ -195,7 +195,7 @@ void NotificationsBox::countChanged() {
if (currentCount() != Global::NotificationsCount()) { if (currentCount() != Global::NotificationsCount()) {
Global::SetNotificationsCount(currentCount()); Global::SetNotificationsCount(currentCount());
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::MaxCount); Auth().notifications().settingsChanged().notify(ChangeType::MaxCount);
Local::writeUserSettings(); Local::writeUserSettings();
} }
} }
@ -352,7 +352,7 @@ void NotificationsBox::setOverCorner(Notify::ScreenCorner corner) {
_isOverCorner = true; _isOverCorner = true;
setCursor(style::cur_pointer); setCursor(style::cur_pointer);
Global::SetNotificationsDemoIsShown(true); Global::SetNotificationsDemoIsShown(true);
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::DemoIsShown); Auth().notifications().settingsChanged().notify(ChangeType::DemoIsShown);
} }
_overCorner = corner; _overCorner = corner;
@ -387,7 +387,7 @@ void NotificationsBox::clearOverCorner() {
_isOverCorner = false; _isOverCorner = false;
setCursor(style::cur_default); setCursor(style::cur_default);
Global::SetNotificationsDemoIsShown(false); Global::SetNotificationsDemoIsShown(false);
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::DemoIsShown); Auth().notifications().settingsChanged().notify(ChangeType::DemoIsShown);
for_const (auto &samples, _cornerSamples) { for_const (auto &samples, _cornerSamples) {
for_const (auto widget, samples) { for_const (auto widget, samples) {
@ -414,7 +414,7 @@ void NotificationsBox::mouseReleaseEvent(QMouseEvent *e) {
if (_chosenCorner != Global::NotificationsCorner()) { if (_chosenCorner != Global::NotificationsCorner()) {
Global::SetNotificationsCorner(_chosenCorner); Global::SetNotificationsCorner(_chosenCorner);
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::Corner); Auth().notifications().settingsChanged().notify(ChangeType::Corner);
Local::writeUserSettings(); Local::writeUserSettings();
} }
} }

View file

@ -345,7 +345,7 @@ void PasscodeBox::onSave(bool force) {
} else { } else {
cSetPasscodeBadTries(0); cSetPasscodeBadTries(0);
Local::setPasscode(pwd.toUtf8()); Local::setPasscode(pwd.toUtf8());
AuthSession::Current().checkAutoLock(); Auth().checkAutoLock();
closeBox(); closeBox();
} }
} }

View file

@ -493,7 +493,7 @@ void PeerListRow::setCheckedInternal(bool checked, SetStyle style) {
PeerListBox::Inner::Inner(QWidget *parent, gsl::not_null<PeerListController*> controller) : TWidget(parent) PeerListBox::Inner::Inner(QWidget *parent, gsl::not_null<PeerListController*> controller) : TWidget(parent)
, _controller(controller) , _controller(controller)
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) { , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) {
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
connect(App::main(), SIGNAL(peerNameChanged(PeerData*, const PeerData::Names&, const PeerData::NameFirstChars&)), this, SLOT(onPeerNameChanged(PeerData*, const PeerData::Names&, const PeerData::NameFirstChars&))); connect(App::main(), SIGNAL(peerNameChanged(PeerData*, const PeerData::Names&, const PeerData::NameFirstChars&)), this, SLOT(onPeerNameChanged(PeerData*, const PeerData::Names&, const PeerData::NameFirstChars&)));
connect(App::main(), SIGNAL(peerPhotoChanged(PeerData*)), this, SLOT(peerUpdated(PeerData*))); connect(App::main(), SIGNAL(peerPhotoChanged(PeerData*)), this, SLOT(peerUpdated(PeerData*)));
@ -1009,7 +1009,7 @@ void PeerListBox::Inner::loadProfilePhotos() {
auto yFrom = _visibleTop; auto yFrom = _visibleTop;
auto yTo = _visibleBottom + (_visibleBottom - _visibleTop) * PreloadHeightsCount; auto yTo = _visibleBottom + (_visibleBottom - _visibleTop) * PreloadHeightsCount;
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
if (yTo < 0) return; if (yTo < 0) return;
if (yFrom < 0) yFrom = 0; if (yFrom < 0) yFrom = 0;
@ -1372,7 +1372,7 @@ void ChatsListBoxController::prepare() {
rebuildRows(); rebuildRows();
auto &sessionData = AuthSession::Current().data(); auto &sessionData = Auth().data();
subscribe(sessionData.contactsLoaded(), [this](bool loaded) { subscribe(sessionData.contactsLoaded(), [this](bool loaded) {
rebuildRows(); rebuildRows();
}); });
@ -1416,7 +1416,7 @@ void ChatsListBoxController::checkForEmptyRows() {
if (delegate()->peerListFullRowsCount()) { if (delegate()->peerListFullRowsCount()) {
setDescriptionText(QString()); setDescriptionText(QString());
} else { } else {
auto &sessionData = AuthSession::Current().data(); auto &sessionData = Auth().data();
auto loaded = sessionData.contactsLoaded().value() && sessionData.allChatsLoaded().value(); auto loaded = sessionData.contactsLoaded().value() && sessionData.allChatsLoaded().value();
setDescriptionText(lang(loaded ? lng_contacts_not_found : lng_contacts_loading)); setDescriptionText(lang(loaded ? lng_contacts_not_found : lng_contacts_loading));
} }

View file

@ -293,5 +293,5 @@ void PhotoCropBox::sendPhoto() {
} }
void PhotoCropBox::onReady(const QImage &tosend) { void PhotoCropBox::onReady(const QImage &tosend) {
App::app()->uploadProfilePhoto(tosend, _peerId); Messenger::Instance().uploadProfilePhoto(tosend, _peerId);
} }

View file

@ -296,7 +296,7 @@ ShareBox::Inner::Inner(QWidget *parent, ShareBox::FilterCallback &&filterCallbac
subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(observeEvents, [this](const Notify::PeerUpdate &update) { subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(observeEvents, [this](const Notify::PeerUpdate &update) {
notifyPeerUpdated(update); notifyPeerUpdated(update);
})); }));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &update) { subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &update) {
if (update.paletteChanged()) { if (update.paletteChanged()) {
@ -437,7 +437,7 @@ void ShareBox::Inner::loadProfilePhotos(int yFrom) {
yFrom *= _columnCount; yFrom *= _columnCount;
yTo *= _columnCount; yTo *= _columnCount;
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
if (_filter.isEmpty()) { if (_filter.isEmpty()) {
if (!_chatsIndexed->isEmpty()) { if (!_chatsIndexed->isEmpty()) {
auto i = _chatsIndexed->cfind(yFrom, _rowHeight); auto i = _chatsIndexed->cfind(yFrom, _rowHeight);
@ -804,7 +804,7 @@ QString AppendShareGameScoreUrl(const QString &url, const FullMsgId &fullId) {
auto channel = fullId.channel ? App::channelLoaded(fullId.channel) : static_cast<ChannelData*>(nullptr); auto channel = fullId.channel ? App::channelLoaded(fullId.channel) : static_cast<ChannelData*>(nullptr);
auto channelAccessHash = channel ? channel->access : 0ULL; auto channelAccessHash = channel ? channel->access : 0ULL;
auto channelAccessHashInts = reinterpret_cast<int32*>(&channelAccessHash); auto channelAccessHashInts = reinterpret_cast<int32*>(&channelAccessHash);
shareHashDataInts[0] = AuthSession::CurrentUserId(); shareHashDataInts[0] = Auth().userId();
shareHashDataInts[1] = fullId.channel; shareHashDataInts[1] = fullId.channel;
shareHashDataInts[2] = fullId.msg; shareHashDataInts[2] = fullId.msg;
shareHashDataInts[3] = channelAccessHashInts[0]; shareHashDataInts[3] = channelAccessHashInts[0];
@ -871,7 +871,7 @@ void ShareGameScoreByHash(const QString &hash) {
} }
auto hashDataInts = reinterpret_cast<int32*>(hashData.data()); auto hashDataInts = reinterpret_cast<int32*>(hashData.data());
if (!AuthSession::Exists() || hashDataInts[0] != AuthSession::CurrentUserId()) { if (!AuthSession::Exists() || hashDataInts[0] != Auth().userId()) {
Ui::show(Box<InformBox>(lang(lng_share_wrong_user))); Ui::show(Box<InformBox>(lang(lng_share_wrong_user)));
return; return;
} }
@ -893,9 +893,9 @@ void ShareGameScoreByHash(const QString &hash) {
if (auto item = App::histItemById(channelId, msgId)) { if (auto item = App::histItemById(channelId, msgId)) {
FastShareMessage(item); FastShareMessage(item);
} else if (App::api()) { } else {
auto resolveMessageAndShareScore = [msgId](ChannelData *channel) { auto resolveMessageAndShareScore = [msgId](ChannelData *channel) {
App::api()->requestMessageData(channel, msgId, [](ChannelData *channel, MsgId msgId) { Auth().api().requestMessageData(channel, msgId, [](ChannelData *channel, MsgId msgId) {
if (auto item = App::histItemById(channel, msgId)) { if (auto item = App::histItemById(channel, msgId)) {
FastShareMessage(item); FastShareMessage(item);
} else { } else {

View file

@ -115,9 +115,9 @@ StickerSetBox::Inner::Inner(QWidget *parent, const MTPInputStickerSet &set) : TW
case mtpc_inputStickerSetShortName: _setShortName = qs(set.c_inputStickerSetShortName().vshort_name); break; case mtpc_inputStickerSetShortName: _setShortName = qs(set.c_inputStickerSetShortName().vshort_name); break;
} }
MTP::send(MTPmessages_GetStickerSet(_input), rpcDone(&Inner::gotSet), rpcFail(&Inner::failedSet)); MTP::send(MTPmessages_GetStickerSet(_input), rpcDone(&Inner::gotSet), rpcFail(&Inner::failedSet));
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
setMouseTracking(true); setMouseTracking(true);

View file

@ -203,7 +203,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
if (_archived.widget()->appendSet(*set)) { if (_archived.widget()->appendSet(*set)) {
addedSet = true; addedSet = true;
if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
App::api()->scheduleStickerSetRequest(set->id, set->access); Auth().api().scheduleStickerSetRequest(set->id, set->access);
} }
} }
} }
@ -220,7 +220,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
refreshTabs(); refreshTabs();
_someArchivedLoaded = true; _someArchivedLoaded = true;
if (_section == Section::Archived && addedSet) { if (_section == Section::Archived && addedSet) {
App::api()->requestStickerSets(); Auth().api().requestStickerSets();
} }
} }
@ -269,7 +269,7 @@ void StickersBox::prepare() {
setDimensions(st::boxWideWidth, (_section == Section::ArchivedPart) ? st::sessionsHeight : st::boxMaxListHeight); setDimensions(st::boxWideWidth, (_section == Section::ArchivedPart) ? st::sessionsHeight : st::boxMaxListHeight);
connect(App::main(), SIGNAL(stickersUpdated()), this, SLOT(onStickersUpdated())); connect(App::main(), SIGNAL(stickersUpdated()), this, SLOT(onStickersUpdated()));
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
if (_installed.widget()) { if (_installed.widget()) {
connect(_installed.widget(), SIGNAL(draggingScrollDelta(int)), this, SLOT(onDraggingScrollDelta(int))); connect(_installed.widget(), SIGNAL(draggingScrollDelta(int)), this, SLOT(onDraggingScrollDelta(int)));
@ -493,11 +493,11 @@ void StickersBox::requestArchivedSets() {
auto it = sets.constFind(setId); auto it = sets.constFind(setId);
if (it != sets.cend()) { if (it != sets.cend()) {
if (it->stickers.isEmpty() && (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it->stickers.isEmpty() && (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
App::api()->scheduleStickerSetRequest(setId, it->access); Auth().api().scheduleStickerSetRequest(setId, it->access);
} }
} }
} }
App::api()->requestStickerSets(); Auth().api().requestStickerSets();
} }
void StickersBox::resizeEvent(QResizeEvent *e) { void StickersBox::resizeEvent(QResizeEvent *e) {
@ -552,8 +552,8 @@ void StickersBox::closeHook() {
if (_someArchivedLoaded) { if (_someArchivedLoaded) {
Local::writeArchivedStickers(); Local::writeArchivedStickers();
} }
if (auto api = App::api()) { if (AuthSession::Exists()) {
api->saveStickerSets(_installed.widget()->getOrder(), _installed.widget()->getRemovedSets()); Auth().api().saveStickerSets(_installed.widget()->getOrder(), _installed.widget()->getRemovedSets());
} }
} }
@ -583,7 +583,7 @@ StickersBox::Inner::Inner(QWidget *parent, const Stickers::Order &archivedIds) :
} }
void StickersBox::Inner::setup() { void StickersBox::Inner::setup() {
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
update(); update();
readVisibleSets(); readVisibleSets();
}); });
@ -1097,10 +1097,10 @@ void StickersBox::Inner::rebuild() {
rebuildAppendSet(it.value(), maxNameWidth); rebuildAppendSet(it.value(), maxNameWidth);
if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
App::api()->scheduleStickerSetRequest(it->id, it->access); Auth().api().scheduleStickerSetRequest(it->id, it->access);
} }
} }
App::api()->requestStickerSets(); Auth().api().requestStickerSets();
updateSize(); updateSize();
} }

View file

@ -261,7 +261,7 @@ QString Call::getDebugLog() const {
void Call::startWaitingTrack() { void Call::startWaitingTrack() {
_waitingTrack = Media::Audio::Current().createTrack(); _waitingTrack = Media::Audio::Current().createTrack();
auto trackFileName = AuthSession::Current().data().getSoundPath((_type == Type::Outgoing) ? qsl("call_outgoing") : qsl("call_incoming")); auto trackFileName = Auth().data().getSoundPath((_type == Type::Outgoing) ? qsl("call_outgoing") : qsl("call_incoming"));
_waitingTrack->samplePeakEach(kSoundSampleMs); _waitingTrack->samplePeakEach(kSoundSampleMs);
_waitingTrack->fillFromFile(trackFileName); _waitingTrack->fillFromFile(trackFileName);
_waitingTrack->playInLoop(); _waitingTrack->playInLoop();
@ -297,8 +297,8 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
|| peerToUser(_user->id) != data.vadmin_id.v) { || peerToUser(_user->id) != data.vadmin_id.v) {
Unexpected("phoneCallRequested call inside an existing call handleUpdate()"); Unexpected("phoneCallRequested call inside an existing call handleUpdate()");
} }
if (AuthSession::CurrentUserId() != data.vparticipant_id.v) { if (Auth().userId() != data.vparticipant_id.v) {
LOG(("Call Error: Wrong call participant_id %1, expected %2.").arg(data.vparticipant_id.v).arg(AuthSession::CurrentUserId())); LOG(("Call Error: Wrong call participant_id %1, expected %2.").arg(data.vparticipant_id.v).arg(Auth().userId()));
finish(FinishType::Failed); finish(FinishType::Failed);
return true; return true;
} }
@ -531,8 +531,8 @@ bool Call::checkCallCommonFields(const T &call) {
LOG(("Call Error: Wrong call access_hash.")); LOG(("Call Error: Wrong call access_hash."));
return checkFailed(); return checkFailed();
} }
auto adminId = (_type == Type::Outgoing) ? AuthSession::CurrentUserId() : peerToUser(_user->id); auto adminId = (_type == Type::Outgoing) ? Auth().userId() : peerToUser(_user->id);
auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : AuthSession::CurrentUserId(); auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : Auth().userId();
if (call.vadmin_id.v != adminId) { if (call.vadmin_id.v != adminId) {
LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id.v).arg(adminId)); LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id.v).arg(adminId));
return checkFailed(); return checkFailed();

View file

@ -47,7 +47,7 @@ void Instance::startOutgoingCall(gsl::not_null<UserData*> user) {
} }
if (user->callsStatus() == UserData::CallsStatus::Private) { if (user->callsStatus() == UserData::CallsStatus::Private) {
// Request full user once more to refresh the setting in case it was changed. // Request full user once more to refresh the setting in case it was changed.
AuthSession::Current().api().requestFullPeer(user); Auth().api().requestFullPeer(user);
Ui::show(Box<InformBox>(lng_call_error_not_available(lt_user, App::peerName(user)))); Ui::show(Box<InformBox>(lng_call_error_not_available(lt_user, App::peerName(user))));
return; return;
} }
@ -73,7 +73,7 @@ void Instance::playSound(Sound sound) {
case Sound::Busy: { case Sound::Busy: {
if (!_callBusyTrack) { if (!_callBusyTrack) {
_callBusyTrack = Media::Audio::Current().createTrack(); _callBusyTrack = Media::Audio::Current().createTrack();
_callBusyTrack->fillFromFile(AuthSession::Current().data().getSoundPath(qsl("call_busy"))); _callBusyTrack->fillFromFile(Auth().data().getSoundPath(qsl("call_busy")));
} }
_callBusyTrack->playOnce(); _callBusyTrack->playOnce();
} break; } break;
@ -81,7 +81,7 @@ void Instance::playSound(Sound sound) {
case Sound::Ended: { case Sound::Ended: {
if (!_callEndedTrack) { if (!_callEndedTrack) {
_callEndedTrack = Media::Audio::Current().createTrack(); _callEndedTrack = Media::Audio::Current().createTrack();
_callEndedTrack->fillFromFile(AuthSession::Current().data().getSoundPath(qsl("call_end"))); _callEndedTrack->fillFromFile(Auth().data().getSoundPath(qsl("call_end")));
} }
_callEndedTrack->playOnce(); _callEndedTrack->playOnce();
} break; } break;
@ -89,7 +89,7 @@ void Instance::playSound(Sound sound) {
case Sound::Connecting: { case Sound::Connecting: {
if (!_callConnectingTrack) { if (!_callConnectingTrack) {
_callConnectingTrack = Media::Audio::Current().createTrack(); _callConnectingTrack = Media::Audio::Current().createTrack();
_callConnectingTrack->fillFromFile(AuthSession::Current().data().getSoundPath(qsl("call_connect"))); _callConnectingTrack->fillFromFile(Auth().data().getSoundPath(qsl("call_connect")));
} }
_callConnectingTrack->playOnce(); _callConnectingTrack->playOnce();
} break; } break;
@ -299,7 +299,7 @@ Instance::~Instance() {
} }
Instance &Current() { Instance &Current() {
return AuthSession::Current().calls(); return Auth().calls();
} }
} // namespace Calls } // namespace Calls

View file

@ -361,12 +361,12 @@ void Panel::initLayout() {
initGeometry(); initGeometry();
processUserPhoto(); processUserPhoto();
subscribe(AuthSession::Current().api().fullPeerUpdated(), [this](PeerData *peer) { subscribe(Auth().api().fullPeerUpdated(), [this](PeerData *peer) {
if (peer == _user) { if (peer == _user) {
processUserPhoto(); processUserPhoto();
} }
}); });
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
refreshUserPhoto(); refreshUserPhoto();
}); });
createDefaultCacheImage(); createDefaultCacheImage();
@ -439,7 +439,7 @@ void Panel::processUserPhoto() {
photo->full->load(true); photo->full->load(true);
} else { } else {
if ((_user->photoId == UnknownPeerPhotoId) || (_user->photoId && (!photo || !photo->date))) { if ((_user->photoId == UnknownPeerPhotoId) || (_user->photoId && (!photo || !photo->date))) {
App::api()->requestFullPeer(_user); Auth().api().requestFullPeer(_user);
} }
} }
refreshUserPhoto(); refreshUserPhoto();

View file

@ -193,7 +193,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) {
QMultiMap<int32, UserData*> ordered; QMultiMap<int32, UserData*> ordered;
mrows.reserve(mrows.size() + (_chat->participants.isEmpty() ? _chat->lastAuthors.size() : _chat->participants.size())); mrows.reserve(mrows.size() + (_chat->participants.isEmpty() ? _chat->lastAuthors.size() : _chat->participants.size()));
if (_chat->noParticipantInfo()) { if (_chat->noParticipantInfo()) {
if (App::api()) App::api()->requestFullPeer(_chat); Auth().api().requestFullPeer(_chat);
} else if (!_chat->participants.isEmpty()) { } else if (!_chat->participants.isEmpty()) {
for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) { for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) {
auto user = i.key(); auto user = i.key();
@ -221,7 +221,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) {
} else if (_channel && _channel->isMegagroup()) { } else if (_channel && _channel->isMegagroup()) {
QMultiMap<int32, UserData*> ordered; QMultiMap<int32, UserData*> ordered;
if (_channel->mgInfo->lastParticipants.isEmpty() || _channel->lastParticipantsCountOutdated()) { if (_channel->mgInfo->lastParticipants.isEmpty() || _channel->lastParticipantsCountOutdated()) {
if (App::api()) App::api()->requestLastParticipants(_channel); Auth().api().requestLastParticipants(_channel);
} else { } else {
mrows.reserve(mrows.size() + _channel->mgInfo->lastParticipants.size()); mrows.reserve(mrows.size() + _channel->mgInfo->lastParticipants.size());
for_const (auto user, _channel->mgInfo->lastParticipants) { for_const (auto user, _channel->mgInfo->lastParticipants) {
@ -249,28 +249,36 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) {
int32 cnt = 0; int32 cnt = 0;
if (_chat) { if (_chat) {
if (_chat->noParticipantInfo()) { if (_chat->noParticipantInfo()) {
if (App::api()) App::api()->requestFullPeer(_chat); Auth().api().requestFullPeer(_chat);
} else if (!_chat->participants.isEmpty()) { } else if (!_chat->participants.isEmpty()) {
for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) { for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) {
auto user = i.key(); auto user = i.key();
if (!user->botInfo) continue; if (!user->botInfo) continue;
if (!user->botInfo->inited && App::api()) App::api()->requestFullPeer(user); if (!user->botInfo->inited) {
Auth().api().requestFullPeer(user);
}
if (user->botInfo->commands.isEmpty()) continue; if (user->botInfo->commands.isEmpty()) continue;
bots.insert(user, true); bots.insert(user, true);
cnt += user->botInfo->commands.size(); cnt += user->botInfo->commands.size();
} }
} }
} else if (_user && _user->botInfo) { } else if (_user && _user->botInfo) {
if (!_user->botInfo->inited && App::api()) App::api()->requestFullPeer(_user); if (!_user->botInfo->inited) {
Auth().api().requestFullPeer(_user);
}
cnt = _user->botInfo->commands.size(); cnt = _user->botInfo->commands.size();
bots.insert(_user, true); bots.insert(_user, true);
} else if (_channel && _channel->isMegagroup()) { } else if (_channel && _channel->isMegagroup()) {
if (_channel->mgInfo->bots.isEmpty()) { if (_channel->mgInfo->bots.isEmpty()) {
if (!_channel->mgInfo->botStatus && App::api()) App::api()->requestBots(_channel); if (!_channel->mgInfo->botStatus) {
Auth().api().requestBots(_channel);
}
} else { } else {
for_const (auto user, _channel->mgInfo->bots) { for_const (auto user, _channel->mgInfo->bots) {
if (!user->botInfo) continue; if (!user->botInfo) continue;
if (!user->botInfo->inited && App::api()) App::api()->requestFullPeer(user); if (!user->botInfo->inited) {
Auth().api().requestFullPeer(user);
}
if (user->botInfo->commands.isEmpty()) continue; if (user->botInfo->commands.isEmpty()) continue;
bots.insert(user, true); bots.insert(user, true);
cnt += user->botInfo->commands.size(); cnt += user->botInfo->commands.size();
@ -285,7 +293,9 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) {
auto user = *i; auto user = *i;
if (!user->botInfo) continue; if (!user->botInfo) continue;
if (!bots.contains(user)) continue; if (!bots.contains(user)) continue;
if (!user->botInfo->inited && App::api()) App::api()->requestFullPeer(user); if (!user->botInfo->inited) {
Auth().api().requestFullPeer(user);
}
if (user->botInfo->commands.isEmpty()) continue; if (user->botInfo->commands.isEmpty()) continue;
bots.remove(user); bots.remove(user);
for (auto j = 0, l = user->botInfo->commands.size(); j != l; ++j) { for (auto j = 0, l = user->botInfo->commands.size(); j != l; ++j) {
@ -512,7 +522,7 @@ FieldAutocompleteInner::FieldAutocompleteInner(FieldAutocomplete *parent, Mentio
, _previewShown(false) { , _previewShown(false) {
_previewTimer.setSingleShot(true); _previewTimer.setSingleShot(true);
connect(&_previewTimer, SIGNAL(timeout()), this, SLOT(onPreview())); connect(&_previewTimer, SIGNAL(timeout()), this, SLOT(onPreview()));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
} }
void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { void FieldAutocompleteInner::paintEvent(QPaintEvent *e) {

View file

@ -136,10 +136,10 @@ GifsListWidget::GifsListWidget(QWidget *parent, gsl::not_null<Window::Controller
_inlineRequestTimer.setSingleShot(true); _inlineRequestTimer.setSingleShot(true);
connect(&_inlineRequestTimer, &QTimer::timeout, this, [this] { sendInlineRequest(); }); connect(&_inlineRequestTimer, &QTimer::timeout, this, [this] { sendInlineRequest(); });
subscribe(AuthSession::Current().data().savedGifsUpdated(), [this] { subscribe(Auth().data().savedGifsUpdated(), [this] {
refreshSavedGifs(); refreshSavedGifs();
}); });
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
update(); update();
}); });
subscribe(controller->gifPauseLevelChanged(), [this] { subscribe(controller->gifPauseLevelChanged(), [this] {

View file

@ -39,7 +39,7 @@ public:
QString tagFromMimeTag(const QString &mimeTag) override { QString tagFromMimeTag(const QString &mimeTag) override {
if (mimeTag.startsWith(qstr("mention://"))) { if (mimeTag.startsWith(qstr("mention://"))) {
auto match = QRegularExpression(":(\\d+)$").match(mimeTag); auto match = QRegularExpression(":(\\d+)$").match(mimeTag);
if (!match.hasMatch() || match.capturedRef(1).toInt() != AuthSession::CurrentUserId()) { if (!match.hasMatch() || match.capturedRef(1).toInt() != Auth().userId()) {
return QString(); return QString();
} }
return mimeTag.mid(0, mimeTag.size() - match.capturedLength()); return mimeTag.mid(0, mimeTag.size() - match.capturedLength());
@ -53,7 +53,7 @@ public:
QString ConvertTagToMimeTag(const QString &tagId) { QString ConvertTagToMimeTag(const QString &tagId) {
if (tagId.startsWith(qstr("mention://"))) { if (tagId.startsWith(qstr("mention://"))) {
return tagId + ':' + QString::number(AuthSession::CurrentUserId()); return tagId + ':' + QString::number(Auth().userId());
} }
return tagId; return tagId;
} }

View file

@ -74,9 +74,9 @@ void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) {
} }
if (!setsToRequest.isEmpty()) { if (!setsToRequest.isEmpty()) {
for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) { for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) {
App::api()->scheduleStickerSetRequest(i.key(), i.value()); Auth().api().scheduleStickerSetRequest(i.key(), i.value());
} }
App::api()->requestStickerSets(); Auth().api().requestStickerSets();
} }
Local::writeInstalledStickers(); Local::writeInstalledStickers();
Local::writeArchivedStickers(); Local::writeArchivedStickers();
@ -342,7 +342,7 @@ void SetsReceived(const QVector<MTPStickerSet> &data, int32 hash) {
} }
if (!setsToRequest.isEmpty()) { if (!setsToRequest.isEmpty()) {
auto &api = AuthSession::Current().api(); auto &api = Auth().api();
for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) { for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) {
api.scheduleStickerSetRequest(i.key(), i.value()); api.scheduleStickerSetRequest(i.key(), i.value());
} }
@ -551,7 +551,7 @@ void FeaturedSetsReceived(const QVector<MTPStickerSetCovered> &data, const QVect
} }
if (!setsToRequest.isEmpty()) { if (!setsToRequest.isEmpty()) {
auto &api = AuthSession::Current().api(); auto &api = Auth().api();
for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) { for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) {
api.scheduleStickerSetRequest(i.key(), i.value()); api.scheduleStickerSetRequest(i.key(), i.value());
} }
@ -583,7 +583,7 @@ void GifsReceived(const QVector<MTPDocument> &items, int32 hash) {
Local::writeSavedGifs(); Local::writeSavedGifs();
AuthSession::Current().data().savedGifsUpdated().notify(); Auth().data().savedGifsUpdated().notify();
} }
StickerPack GetListByEmoji(gsl::not_null<EmojiPtr> emoji) { StickerPack GetListByEmoji(gsl::not_null<EmojiPtr> emoji) {
@ -623,9 +623,9 @@ StickerPack GetListByEmoji(gsl::not_null<EmojiPtr> emoji) {
} }
if (!setsToRequest.isEmpty()) { if (!setsToRequest.isEmpty()) {
for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) { for (auto i = setsToRequest.cbegin(), e = setsToRequest.cend(); i != e; ++i) {
AuthSession::Current().api().scheduleStickerSetRequest(i.key(), i.value()); Auth().api().scheduleStickerSetRequest(i.key(), i.value());
} }
AuthSession::Current().api().requestStickerSets(); Auth().api().requestStickerSets();
} }
return result; return result;
} }

View file

@ -118,7 +118,7 @@ StickersListWidget::Footer::Footer(gsl::not_null<StickersListWidget*> parent) :
_iconsLeft = (st::emojiPanWidth - kVisibleIconsCount * st::emojiCategory.width) / 2; _iconsLeft = (st::emojiPanWidth - kVisibleIconsCount * st::emojiCategory.width) / 2;
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
update(); update();
}); });
} }
@ -450,7 +450,7 @@ StickersListWidget::StickersListWidget(QWidget *parent, gsl::not_null<Window::Co
_previewTimer.setSingleShot(true); _previewTimer.setSingleShot(true);
connect(&_previewTimer, SIGNAL(timeout()), this, SLOT(onPreview())); connect(&_previewTimer, SIGNAL(timeout()), this, SLOT(onPreview()));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
update(); update();
readVisibleSets(); readVisibleSets();
}); });

View file

@ -295,7 +295,7 @@ TabbedSelector::TabbedSelector(QWidget *parent, gsl::not_null<Window::Controller
Tab { SelectorTab::Stickers, object_ptr<StickersListWidget>(this, controller) }, Tab { SelectorTab::Stickers, object_ptr<StickersListWidget>(this, controller) },
Tab { SelectorTab::Gifs, object_ptr<GifsListWidget>(this, controller) }, Tab { SelectorTab::Gifs, object_ptr<GifsListWidget>(this, controller) },
} } } }
, _currentTabType(AuthSession::Current().data().selectorTab()) { , _currentTabType(Auth().data().selectorTab()) {
resize(st::emojiPanWidth, st::emojiPanMaxHeight); resize(st::emojiPanWidth, st::emojiPanMaxHeight);
for (auto &tab : _tabs) { for (auto &tab : _tabs) {
@ -487,7 +487,7 @@ void TabbedSelector::hideFinished() {
} }
void TabbedSelector::showStarted() { void TabbedSelector::showStarted() {
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
currentTab()->widget()->refreshRecent(); currentTab()->widget()->refreshRecent();
currentTab()->widget()->preloadImages(); currentTab()->widget()->preloadImages();
_a_slide.finish(); _a_slide.finish();
@ -665,8 +665,8 @@ void TabbedSelector::switchTab() {
_a_slide.start([this] { update(); }, 0., 1., st::emojiPanSlideDuration, anim::linear); _a_slide.start([this] { update(); }, 0., 1., st::emojiPanSlideDuration, anim::linear);
update(); update();
AuthSession::Current().data().setSelectorTab(_currentTabType); Auth().data().setSelectorTab(_currentTabType);
AuthSession::Current().saveDataDelayed(kSaveChosenTabTimeout); Auth().saveDataDelayed(kSaveChosenTabTimeout);
} }
gsl::not_null<EmojiListWidget*> TabbedSelector::emoji() const { gsl::not_null<EmojiListWidget*> TabbedSelector::emoji() const {

View file

@ -94,7 +94,7 @@ DialogsInner::DialogsInner(QWidget *parent, gsl::not_null<Window::Controller*> c
_cancelSearchFromUser->setClickedCallback([this] { searchFromUserChanged.notify(nullptr); }); _cancelSearchFromUser->setClickedCallback([this] { searchFromUserChanged.notify(nullptr); });
_cancelSearchFromUser->hide(); _cancelSearchFromUser->hide();
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) { subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) {
itemRemoved(item); itemRemoved(item);
}); });
@ -219,7 +219,7 @@ void DialogsInner::paintRegion(Painter &p, const QRegion &region, bool paintingO
if (!paintingOther) { if (!paintingOther) {
p.setFont(st::noContactsFont); p.setFont(st::noContactsFont);
p.setPen(st::noContactsColor); p.setPen(st::noContactsColor);
p.drawText(QRect(0, 0, fullWidth, st::noContactsHeight - (AuthSession::Current().data().contactsLoaded().value() ? st::noContactsFont->height : 0)), lang(AuthSession::Current().data().contactsLoaded().value() ? lng_no_chats : lng_contacts_loading), style::al_center); p.drawText(QRect(0, 0, fullWidth, st::noContactsHeight - (Auth().data().contactsLoaded().value() ? st::noContactsFont->height : 0)), lang(Auth().data().contactsLoaded().value() ? lng_no_chats : lng_contacts_loading), style::al_center);
} }
} }
} else if (_state == FilteredState || _state == SearchedState) { } else if (_state == FilteredState || _state == SearchedState) {
@ -1036,7 +1036,7 @@ void DialogsInner::removeDialog(History *history) {
if (_dialogsImportant) { if (_dialogsImportant) {
history->removeFromChatList(Dialogs::Mode::Important, _dialogsImportant.get()); history->removeFromChatList(Dialogs::Mode::Important, _dialogsImportant.get());
} }
AuthSession::Current().notifications().clearFromHistory(history); Auth().notifications().clearFromHistory(history);
if (_contacts->contains(history->peer->id)) { if (_contacts->contains(history->peer->id)) {
if (!_contactsNoDialogs->contains(history->peer->id)) { if (!_contactsNoDialogs->contains(history->peer->id)) {
_contactsNoDialogs->addByName(history); _contactsNoDialogs->addByName(history);
@ -1465,8 +1465,8 @@ void DialogsInner::dialogsReceived(const QVector<MTPDialog> &added) {
} }
if (!channel->amCreator()) { if (!channel->amCreator()) {
if (auto topMsg = App::histItemById(channel, d.vtop_message.v)) { if (auto topMsg = App::histItemById(channel, d.vtop_message.v)) {
if (topMsg->date <= date(channel->date) && App::api()) { if (topMsg->date <= date(channel->date)) {
App::api()->requestSelfParticipant(channel); Auth().api().requestSelfParticipant(channel);
} }
} }
} }
@ -1576,7 +1576,7 @@ void DialogsInner::contactsReceived(const QVector<MTPContact> &result) {
if (contact.type() != mtpc_contact) continue; if (contact.type() != mtpc_contact) continue;
auto userId = contact.c_contact().vuser_id.v; auto userId = contact.c_contact().vuser_id.v;
if (userId == AuthSession::CurrentUserId() && App::self()) { if (userId == Auth().userId() && App::self()) {
if (App::self()->contact < 1) { if (App::self()->contact < 1) {
App::self()->contact = 1; App::self()->contact = 1;
Notify::userIsContactChanged(App::self()); Notify::userIsContactChanged(App::self());
@ -1664,7 +1664,7 @@ void DialogsInner::refresh(bool toTop) {
if (_state == DefaultState) { if (_state == DefaultState) {
if (shownDialogs()->isEmpty()) { if (shownDialogs()->isEmpty()) {
h = st::noContactsHeight; h = st::noContactsHeight;
if (AuthSession::Current().data().contactsLoaded().value()) { if (Auth().data().contactsLoaded().value()) {
if (_addContactLnk->isHidden()) _addContactLnk->show(); if (_addContactLnk->isHidden()) _addContactLnk->show();
} else { } else {
if (!_addContactLnk->isHidden()) _addContactLnk->hide(); if (!_addContactLnk->isHidden()) _addContactLnk->hide();
@ -1912,7 +1912,7 @@ void DialogsInner::loadPeerPhotos() {
auto yFrom = _visibleTop; auto yFrom = _visibleTop;
auto yTo = _visibleTop + (_visibleBottom - _visibleTop) * (PreloadHeightsCount + 1); auto yTo = _visibleTop + (_visibleBottom - _visibleTop) * (PreloadHeightsCount + 1);
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
if (_state == DefaultState) { if (_state == DefaultState) {
auto otherStart = shownDialogs()->size() * st::dialogsRowHeight; auto otherStart = shownDialogs()->size() * st::dialogsRowHeight;
if (yFrom < otherStart) { if (yFrom < otherStart) {

View file

@ -77,7 +77,7 @@ void ChatSearchFromController::rebuildRows() {
auto now = unixtime(); auto now = unixtime();
QMultiMap<int32, UserData*> ordered; QMultiMap<int32, UserData*> ordered;
if (_chat->noParticipantInfo()) { if (_chat->noParticipantInfo()) {
AuthSession::Current().api().requestFullPeer(_chat); Auth().api().requestFullPeer(_chat);
} else if (!_chat->participants.isEmpty()) { } else if (!_chat->participants.isEmpty()) {
for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) { for (auto i = _chat->participants.cbegin(), e = _chat->participants.cend(); i != e; ++i) {
auto user = i.key(); auto user = i.key();

View file

@ -338,7 +338,7 @@ void DialogsWidget::dialogsReceived(const MTPmessages_Dialogs &dialogs, mtpReque
} break; } break;
} }
if (!AuthSession::Current().data().contactsLoaded().value() && !_contactsRequestId) { if (!Auth().data().contactsLoaded().value() && !_contactsRequestId) {
_contactsRequestId = MTP::send(MTPcontacts_GetContacts(MTP_int(0)), rpcDone(&DialogsWidget::contactsReceived), rpcFail(&DialogsWidget::contactsFailed)); _contactsRequestId = MTP::send(MTPcontacts_GetContacts(MTP_int(0)), rpcDone(&DialogsWidget::contactsReceived), rpcFail(&DialogsWidget::contactsFailed));
} }
@ -395,9 +395,9 @@ void DialogsWidget::dialogsReceived(const MTPmessages_Dialogs &dialogs, mtpReque
_dialogsRequestId = 0; _dialogsRequestId = 0;
loadDialogs(); loadDialogs();
AuthSession::Current().data().moreChatsLoaded().notify(); Auth().data().moreChatsLoaded().notify();
if (_dialogsFull) { if (_dialogsFull) {
AuthSession::Current().data().allChatsLoaded().set(true); Auth().data().allChatsLoaded().set(true);
} }
} }
@ -432,7 +432,7 @@ void DialogsWidget::pinnedDialogsReceived(const MTPmessages_PeerDialogs &dialogs
_pinnedDialogsRequestId = 0; _pinnedDialogsRequestId = 0;
_pinnedDialogsReceived = true; _pinnedDialogsReceived = true;
AuthSession::Current().data().moreChatsLoaded().notify(); Auth().data().moreChatsLoaded().notify();
} }
bool DialogsWidget::dialogsFailed(const RPCError &error, mtpRequestId requestId) { bool DialogsWidget::dialogsFailed(const RPCError &error, mtpRequestId requestId) {
@ -598,7 +598,7 @@ void DialogsWidget::contactsReceived(const MTPcontacts_Contacts &result) {
App::feedUsers(d.vusers); App::feedUsers(d.vusers);
_inner->contactsReceived(d.vcontacts.v); _inner->contactsReceived(d.vcontacts.v);
} }
AuthSession::Current().data().contactsLoaded().set(true); Auth().data().contactsLoaded().set(true);
} }
bool DialogsWidget::contactsFailed(const RPCError &error) { bool DialogsWidget::contactsFailed(const RPCError &error) {

View file

@ -188,7 +188,7 @@ void activateClickHandler(ClickHandlerPtr handler, Qt::MouseButton button) {
} }
void logOutDelayed() { void logOutDelayed() {
App::CallDelayed(1, App::app(), [] { InvokeQueued(QCoreApplication::instance(), [] {
App::logOut(); App::logOut();
}); });
} }
@ -364,7 +364,7 @@ void handlePendingHistoryUpdate() {
if (!AuthSession::Exists()) { if (!AuthSession::Exists()) {
return; return;
} }
AuthSession::Current().data().pendingHistoryResize().notify(true); Auth().data().pendingHistoryResize().notify(true);
for (auto item : base::take(Global::RefPendingRepaintItems())) { for (auto item : base::take(Global::RefPendingRepaintItems())) {
Ui::repaintHistoryItem(item); Ui::repaintHistoryItem(item);
@ -539,10 +539,10 @@ namespace Global {
namespace internal { namespace internal {
struct Data { struct Data {
SingleQueuedInvokation HandleHistoryUpdate = { [] { App::app()->call_handleHistoryUpdate(); } }; SingleQueuedInvokation HandleHistoryUpdate = { [] { Messenger::Instance().call_handleHistoryUpdate(); } };
SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { App::app()->call_handleUnreadCounterUpdate(); } }; SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { Messenger::Instance().call_handleUnreadCounterUpdate(); } };
SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { App::app()->call_handleDelayedPeerUpdates(); } }; SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { Messenger::Instance().call_handleDelayedPeerUpdates(); } };
SingleQueuedInvokation HandleObservables = { [] { App::app()->call_handleObservables(); } }; SingleQueuedInvokation HandleObservables = { [] { Messenger::Instance().call_handleObservables(); } };
Adaptive::WindowLayout AdaptiveWindowLayout = Adaptive::WindowLayout::Normal; Adaptive::WindowLayout AdaptiveWindowLayout = Adaptive::WindowLayout::Normal;
Adaptive::ChatLayout AdaptiveChatLayout = Adaptive::ChatLayout::Normal; Adaptive::ChatLayout AdaptiveChatLayout = Adaptive::ChatLayout::Normal;

View file

@ -127,7 +127,7 @@ void History::takeLocalDraft(History *from) {
_localDraft->msgId = 0; _localDraft->msgId = 0;
} }
from->clearLocalDraft(); from->clearLocalDraft();
App::api()->saveDraftToCloudDelayed(from); Auth().api().saveDraftToCloudDelayed(from);
} }
} }
@ -440,7 +440,7 @@ HistoryJoined *ChannelHistory::insertJoinedMessage(bool unread) {
if (!inviter) return nullptr; if (!inviter) return nullptr;
MTPDmessage::Flags flags = 0; MTPDmessage::Flags flags = 0;
if (inviter->id == AuthSession::CurrentUserPeerId()) { if (inviter->id == Auth().userPeerId()) {
unread = false; unread = false;
//} else if (unread) { //} else if (unread) {
// flags |= MTPDmessage::Flag::f_unread; // flags |= MTPDmessage::Flag::f_unread;
@ -1600,7 +1600,7 @@ MsgId History::inboxRead(MsgId upTo) {
} }
showFrom = nullptr; showFrom = nullptr;
AuthSession::Current().notifications().clearFromHistory(this); Auth().notifications().clearFromHistory(this);
return upTo; return upTo;
} }
@ -2116,7 +2116,7 @@ void History::clear(bool leaveItems) {
} }
} }
if (leaveItems) { if (leaveItems) {
AuthSession::Current().data().historyCleared().notify(this, true); Auth().data().historyCleared().notify(this, true);
} }
} }

View file

@ -212,13 +212,13 @@ InnerWidget::InnerWidget(QWidget *parent, gsl::not_null<Window::Controller*> con
, _emptyText(st::historyAdminLogEmptyWidth - st::historyAdminLogEmptyPadding.left() - st::historyAdminLogEmptyPadding.left()) { , _emptyText(st::historyAdminLogEmptyWidth - st::historyAdminLogEmptyPadding.left() - st::historyAdminLogEmptyPadding.left()) {
setMouseTracking(true); setMouseTracking(true);
_scrollDateHideTimer.setCallback([this] { scrollDateHideByTimer(); }); _scrollDateHideTimer.setCallback([this] { scrollDateHideByTimer(); });
subscribe(AuthSession::Current().data().repaintLogEntry(), [this](gsl::not_null<const HistoryItem*> historyItem) { subscribe(Auth().data().repaintLogEntry(), [this](gsl::not_null<const HistoryItem*> historyItem) {
if (_history == historyItem->history()) { if (_history == historyItem->history()) {
repaintItem(historyItem); repaintItem(historyItem);
} }
}); });
subscribe(AuthSession::Current().data().pendingHistoryResize(), [this] { handlePendingHistoryResize(); }); subscribe(Auth().data().pendingHistoryResize(), [this] { handlePendingHistoryResize(); });
subscribe(AuthSession::Current().data().queryItemVisibility(), [this](const AuthSessionData::ItemVisibilityQuery &query) { subscribe(Auth().data().queryItemVisibility(), [this](const AuthSessionData::ItemVisibilityQuery &query) {
if (_history != query.item->history() || !query.item->isLogEntry() || !isVisible()) { if (_history != query.item->history() || !query.item->isLogEntry() || !isVisible()) {
return; return;
} }
@ -1056,7 +1056,7 @@ void InnerWidget::suggestRestrictUser(gsl::not_null<UserData*> user) {
void InnerWidget::restrictUser(gsl::not_null<UserData*> user, const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) { void InnerWidget::restrictUser(gsl::not_null<UserData*> user, const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) {
auto weak = QPointer<InnerWidget>(this); auto weak = QPointer<InnerWidget>(this);
MTP::send(MTPchannels_EditBanned(_channel->inputChannel, user->inputUser, newRights), rpcDone([megagroup = _channel.get(), user, weak, oldRights, newRights](const MTPUpdates &result) { MTP::send(MTPchannels_EditBanned(_channel->inputChannel, user->inputUser, newRights), rpcDone([megagroup = _channel.get(), user, weak, oldRights, newRights](const MTPUpdates &result) {
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
megagroup->applyEditBanned(user, oldRights, newRights); megagroup->applyEditBanned(user, oldRights, newRights);
if (weak) { if (weak) {
weak->restrictUserDone(user, newRights); weak->restrictUserDone(user, newRights);

View file

@ -115,7 +115,7 @@ HistoryInner::HistoryInner(HistoryWidget *historyWidget, gsl::not_null<Window::C
subscribe(_controller->window()->dragFinished(), [this] { subscribe(_controller->window()->dragFinished(), [this] {
mouseActionUpdate(QCursor::pos()); mouseActionUpdate(QCursor::pos());
}); });
subscribe(AuthSession::Current().data().historyCleared(), [this](gsl::not_null<History*> history) { subscribe(Auth().data().historyCleared(), [this](gsl::not_null<History*> history) {
if (_history == history) { if (_history == history) {
mouseActionCancel(); mouseActionCancel();
} }
@ -2310,7 +2310,7 @@ void HistoryInner::notifyIsBotChanged() {
if (newinfo) { if (newinfo) {
_botAbout.reset(new BotAbout(this, newinfo)); _botAbout.reset(new BotAbout(this, newinfo));
if (newinfo && !newinfo->inited) { if (newinfo && !newinfo->inited) {
AuthSession::Current().api().requestFullPeer(_peer); Auth().api().requestFullPeer(_peer);
} }
} else { } else {
_botAbout = nullptr; _botAbout = nullptr;

View file

@ -1057,7 +1057,7 @@ void HistoryItem::clipCallback(Media::Clip::Notification notification) {
auto stopped = false; auto stopped = false;
if (reader->autoPausedGif()) { if (reader->autoPausedGif()) {
auto amVisible = false; auto amVisible = false;
AuthSession::Current().data().queryItemVisibility().notify({ this, &amVisible }, true); Auth().data().queryItemVisibility().notify({ this, &amVisible }, true);
if (!amVisible) { // stop animation if it is not visible if (!amVisible) { // stop animation if it is not visible
media->stopInline(); media->stopInline();
if (auto document = media->getDocument()) { // forget data from memory if (auto document = media->getDocument()) { // forget data from memory
@ -1182,8 +1182,8 @@ void HistoryItem::drawInDialog(Painter &p, const QRect &r, bool active, bool sel
HistoryItem::~HistoryItem() { HistoryItem::~HistoryItem() {
App::historyUnregItem(this); App::historyUnregItem(this);
if (id < 0 && App::uploader()) { if (id < 0 && !App::quitting()) {
App::uploader()->cancel(fullId()); Auth().uploader().cancel(fullId());
} }
} }

View file

@ -862,8 +862,8 @@ void HistoryMessage::createComponents(const CreateConfig &config) {
if (auto reply = Get<HistoryMessageReply>()) { if (auto reply = Get<HistoryMessageReply>()) {
reply->replyToMsgId = config.replyTo; reply->replyToMsgId = config.replyTo;
if (!reply->updateData(this) && App::api()) { if (!reply->updateData(this)) {
App::api()->requestMessageData(history()->peer->asChannel(), reply->replyToMsgId, HistoryDependentItemCallback(fullId())); Auth().api().requestMessageData(history()->peer->asChannel(), reply->replyToMsgId, HistoryDependentItemCallback(fullId()));
} }
} }
if (auto via = Get<HistoryMessageVia>()) { if (auto via = Get<HistoryMessageVia>()) {

View file

@ -192,7 +192,7 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
if (auto channel = history()->peer->asMegagroup()) { if (auto channel = history()->peer->asMegagroup()) {
auto &users = action.c_messageActionChatAddUser().vusers; auto &users = action.c_messageActionChatAddUser().vusers;
for_const (auto &item, users.v) { for_const (auto &item, users.v) {
if (item.v == AuthSession::CurrentUserId()) { if (item.v == Auth().userId()) {
channel->mgInfo->joinedMessageFound = true; channel->mgInfo->joinedMessageFound = true;
break; break;
} }
@ -258,7 +258,7 @@ bool HistoryService::updateDependent(bool force) {
updateDependentText(); updateDependentText();
} }
if (force && gotDependencyItem) { if (force && gotDependencyItem) {
AuthSession::Current().notifications().checkDelayed(); Auth().notifications().checkDelayed();
} }
return (dependent->msg || !dependent->msgId); return (dependent->msg || !dependent->msgId);
} }
@ -678,8 +678,8 @@ void HistoryService::createFromMtp(const MTPDmessageService &message) {
} }
if (auto dependent = GetDependentData()) { if (auto dependent = GetDependentData()) {
dependent->msgId = message.vreply_to_msg_id.v; dependent->msgId = message.vreply_to_msg_id.v;
if (!updateDependent() && App::api()) { if (!updateDependent()) {
App::api()->requestMessageData(history()->peer->asChannel(), dependent->msgId, HistoryDependentItemCallback(fullId())); Auth().api().requestMessageData(history()->peer->asChannel(), dependent->msgId, HistoryDependentItemCallback(fullId()));
} }
} }
} }
@ -777,7 +777,7 @@ HistoryJoined::HistoryJoined(gsl::not_null<History*> history, const QDateTime &i
} }
HistoryJoined::PreparedText HistoryJoined::GenerateText(gsl::not_null<History*> history, gsl::not_null<UserData*> inviter) { HistoryJoined::PreparedText HistoryJoined::GenerateText(gsl::not_null<History*> history, gsl::not_null<UserData*> inviter) {
if (inviter->id == AuthSession::CurrentUserPeerId()) { if (inviter->id == Auth().userPeerId()) {
return { lang(history->isMegagroup() ? lng_action_you_joined_group : lng_action_you_joined) }; return { lang(history->isMegagroup() ? lng_action_you_joined_group : lng_action_you_joined) };
} }
auto result = PreparedText {}; auto result = PreparedText {};

View file

@ -636,7 +636,7 @@ HistoryWidget::HistoryWidget(QWidget *parent, gsl::not_null<Window::Controller*>
, _topShadow(this, st::shadowFg) { , _topShadow(this, st::shadowFg) {
setAcceptDrops(true); setAcceptDrops(true);
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
connect(_topBar, &Window::TopBarWidget::clicked, this, [this] { topBarClick(); }); connect(_topBar, &Window::TopBarWidget::clicked, this, [this] { topBarClick(); });
connect(_scroll, SIGNAL(scrolled()), this, SLOT(onScroll())); connect(_scroll, SIGNAL(scrolled()), this, SLOT(onScroll()));
connect(_historyDown, SIGNAL(clicked()), this, SLOT(onHistoryToEnd())); connect(_historyDown, SIGNAL(clicked()), this, SLOT(onHistoryToEnd()));
@ -758,7 +758,7 @@ HistoryWidget::HistoryWidget(QWidget *parent, gsl::not_null<Window::Controller*>
subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) { subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) {
itemRemoved(item); itemRemoved(item);
}); });
subscribe(AuthSession::Current().data().contactsLoaded(), [this](bool) { subscribe(Auth().data().contactsLoaded(), [this](bool) {
if (_peer) { if (_peer) {
updateReportSpamStatus(); updateReportSpamStatus();
updateControlsVisibility(); updateControlsVisibility();
@ -790,8 +790,8 @@ HistoryWidget::HistoryWidget(QWidget *parent, gsl::not_null<Window::Controller*>
// So we force HistoryWidget::resizeEvent() here, without WA_UpdatesDisabled. // So we force HistoryWidget::resizeEvent() here, without WA_UpdatesDisabled.
myEnsureResized(this); myEnsureResized(this);
}); });
subscribe(AuthSession::Current().data().pendingHistoryResize(), [this] { handlePendingHistoryUpdate(); }); subscribe(Auth().data().pendingHistoryResize(), [this] { handlePendingHistoryUpdate(); });
subscribe(AuthSession::Current().data().queryItemVisibility(), [this](const AuthSessionData::ItemVisibilityQuery &query) { subscribe(Auth().data().queryItemVisibility(), [this](const AuthSessionData::ItemVisibilityQuery &query) {
if (_a_show.animating() || _history != query.item->history() || query.item->detached() || !isVisible()) { if (_a_show.animating() || _history != query.item->history() || query.item->detached() || !isVisible()) {
return; return;
} }
@ -923,8 +923,8 @@ int HistoryWidget::itemTopForHighlight(gsl::not_null<HistoryItem*> item) const {
void HistoryWidget::start() { void HistoryWidget::start() {
connect(App::main(), SIGNAL(stickersUpdated()), this, SLOT(onStickersUpdated())); connect(App::main(), SIGNAL(stickersUpdated()), this, SLOT(onStickersUpdated()));
updateRecentStickers(); updateRecentStickers();
AuthSession::Current().data().savedGifsUpdated().notify(); Auth().data().savedGifsUpdated().notify();
subscribe(App::api()->fullPeerUpdated(), [this](PeerData *peer) { subscribe(Auth().api().fullPeerUpdated(), [this](PeerData *peer) {
fullPeerUpdated(peer); fullPeerUpdated(peer);
}); });
} }
@ -1565,8 +1565,8 @@ void HistoryWidget::applyDraft(bool parseLinks, Ui::FlatTextarea::UndoHistoryAct
} }
if (_editMsgId || _replyToId) { if (_editMsgId || _replyToId) {
updateReplyEditTexts(); updateReplyEditTexts();
if (!_replyEditMsg && App::api()) { if (!_replyEditMsg) {
App::api()->requestMessageData(_peer->asChannel(), _editMsgId ? _editMsgId : _replyToId, replyEditMessageDataCallback()); Auth().api().requestMessageData(_peer->asChannel(), _editMsgId ? _editMsgId : _replyToId, replyEditMessageDataCallback());
} }
} }
} }
@ -1724,7 +1724,7 @@ void HistoryWidget::showHistory(const PeerId &peerId, MsgId showAtMsgId, bool re
if (_peer) { if (_peer) {
App::forgetMedia(); App::forgetMedia();
_serviceImageCacheSize = imageCacheSize(); _serviceImageCacheSize = imageCacheSize();
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
_history = App::history(_peer->id); _history = App::history(_peer->id);
_migrated = _peer->migrateFrom() ? App::history(_peer->migrateFrom()->id) : 0; _migrated = _peer->migrateFrom() ? App::history(_peer->migrateFrom()->id) : 0;
@ -1732,7 +1732,7 @@ void HistoryWidget::showHistory(const PeerId &peerId, MsgId showAtMsgId, bool re
if (_channel) { if (_channel) {
updateNotifySettings(); updateNotifySettings();
if (_peer->notify == UnknownNotifySettings) { if (_peer->notify == UnknownNotifySettings) {
App::api()->requestNotifySetting(_peer); Auth().api().requestNotifySetting(_peer);
} }
} }
@ -1850,7 +1850,7 @@ bool HistoryWidget::contentOverlapped(const QRect &globalRect) {
} }
void HistoryWidget::updateReportSpamStatus() { void HistoryWidget::updateReportSpamStatus() {
if (!_peer || (_peer->isUser() && (_peer->id == AuthSession::CurrentUserPeerId() || isNotificationsUser(_peer->id) || isServiceUser(_peer->id) || _peer->asUser()->botInfo))) { if (!_peer || (_peer->isUser() && (_peer->id == Auth().userPeerId() || isNotificationsUser(_peer->id) || isServiceUser(_peer->id) || _peer->asUser()->botInfo))) {
setReportSpamStatus(dbiprsHidden); setReportSpamStatus(dbiprsHidden);
return; return;
} else if (!_firstLoadRequest && _history->isEmpty()) { } else if (!_firstLoadRequest && _history->isEmpty()) {
@ -1899,7 +1899,7 @@ void HistoryWidget::updateReportSpamStatus() {
} }
} }
auto status = dbiprsRequesting; auto status = dbiprsRequesting;
if (!AuthSession::Current().data().contactsLoaded().value() || _firstLoadRequest) { if (!Auth().data().contactsLoaded().value() || _firstLoadRequest) {
status = dbiprsUnknown; status = dbiprsUnknown;
} else if (_peer->isUser() && _peer->asUser()->contact > 0) { } else if (_peer->isUser() && _peer->asUser()->contact > 0) {
status = dbiprsHidden; status = dbiprsHidden;
@ -2172,7 +2172,7 @@ void HistoryWidget::newUnreadMsg(History *history, HistoryItem *item) {
return; return;
} }
} }
AuthSession::Current().notifications().schedule(history, item); Auth().notifications().schedule(history, item);
history->setUnreadCount(history->unreadCount() + 1); history->setUnreadCount(history->unreadCount() + 1);
} }
@ -2882,8 +2882,8 @@ void HistoryWidget::shareContact(const PeerId &peer, const QString &phone, const
if (silentPost) { if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent; sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(peer), MTPnullFwdHeader, MTPint(), MTP_int(replyToId()), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaContact(MTP_string(phone), MTP_string(fname), MTP_string(lname), MTP_int(userId)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint(), MTP_string(messagePostAuthor)), NewMessageUnread); history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(peer), MTPnullFwdHeader, MTPint(), MTP_int(replyToId()), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaContact(MTP_string(phone), MTP_string(fname), MTP_string(lname), MTP_int(userId)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint(), MTP_string(messagePostAuthor)), NewMessageUnread);
history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), p->input, MTP_int(replyTo), MTP_inputMediaContact(MTP_string(phone), MTP_string(fname), MTP_string(lname)), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, history->sendRequestId); history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), p->input, MTP_int(replyTo), MTP_inputMediaContact(MTP_string(phone), MTP_string(fname), MTP_string(lname)), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, history->sendRequestId);
@ -3736,7 +3736,7 @@ void HistoryWidget::topBarClick() {
} }
void HistoryWidget::updateTabbedSelectorSectionShown() { void HistoryWidget::updateTabbedSelectorSectionShown() {
auto tabbedSelectorSectionEnabled = AuthSession::Current().data().tabbedSelectorSectionEnabled(); auto tabbedSelectorSectionEnabled = Auth().data().tabbedSelectorSectionEnabled();
auto useTabbedSection = tabbedSelectorSectionEnabled && (width() >= minimalWidthForTabbedSelectorSection()); auto useTabbedSection = tabbedSelectorSectionEnabled && (width() >= minimalWidthForTabbedSelectorSection());
if (_tabbedSectionUsed == useTabbedSection) { if (_tabbedSectionUsed == useTabbedSection) {
return; return;
@ -3770,7 +3770,7 @@ void HistoryWidget::updateTabbedSelectorSectionShown() {
void HistoryWidget::checkTabbedSelectorToggleTooltip() { void HistoryWidget::checkTabbedSelectorToggleTooltip() {
if (_tabbedSection && !_tabbedSection->isHidden() && !_tabbedSelectorToggle->isHidden()) { if (_tabbedSection && !_tabbedSection->isHidden() && !_tabbedSelectorToggle->isHidden()) {
if (!_tabbedSelectorToggleTooltipShown) { if (!_tabbedSelectorToggleTooltipShown) {
auto shownCount = AuthSession::Current().data().tabbedSelectorSectionTooltipShown(); auto shownCount = Auth().data().tabbedSelectorSectionTooltipShown();
if (shownCount < kTabbedSelectorToggleTooltipCount) { if (shownCount < kTabbedSelectorToggleTooltipCount) {
_tabbedSelectorToggleTooltipShown = true; _tabbedSelectorToggleTooltipShown = true;
_tabbedSelectorToggleTooltip.create(this, object_ptr<Ui::FlatLabel>(this, lang(lng_emoji_hide_panel), Ui::FlatLabel::InitType::Simple, st::defaultImportantTooltipLabel), st::defaultImportantTooltip); _tabbedSelectorToggleTooltip.create(this, object_ptr<Ui::FlatLabel>(this, lang(lng_emoji_hide_panel), Ui::FlatLabel::InitType::Simple, st::defaultImportantTooltipLabel), st::defaultImportantTooltip);
@ -3778,8 +3778,8 @@ void HistoryWidget::checkTabbedSelectorToggleTooltip() {
_tabbedSelectorToggleTooltip.destroy(); _tabbedSelectorToggleTooltip.destroy();
}); });
InvokeQueued(_tabbedSelectorToggleTooltip, [this, shownCount] { InvokeQueued(_tabbedSelectorToggleTooltip, [this, shownCount] {
AuthSession::Current().data().setTabbedSelectorSectionTooltipShown(shownCount + 1); Auth().data().setTabbedSelectorSectionTooltipShown(shownCount + 1);
AuthSession::Current().saveDataDelayed(kTabbedSelectorToggleTooltipTimeoutMs); Auth().saveDataDelayed(kTabbedSelectorToggleTooltipTimeoutMs);
updateTabbedSelectorToggleTooltipGeometry(); updateTabbedSelectorToggleTooltipGeometry();
_tabbedSelectorToggleTooltip->hideAfter(kTabbedSelectorToggleTooltipTimeoutMs); _tabbedSelectorToggleTooltip->hideAfter(kTabbedSelectorToggleTooltipTimeoutMs);
@ -3801,7 +3801,7 @@ int HistoryWidget::minimalWidthForTabbedSelectorSection() const {
} }
bool HistoryWidget::willSwitchToTabbedSelectorWithWidth(int newWidth) const { bool HistoryWidget::willSwitchToTabbedSelectorWithWidth(int newWidth) const {
if (!AuthSession::Current().data().tabbedSelectorSectionEnabled()) { if (!Auth().data().tabbedSelectorSectionEnabled()) {
return false; return false;
} else if (_tabbedSectionUsed) { } else if (_tabbedSectionUsed) {
return false; return false;
@ -3811,15 +3811,15 @@ bool HistoryWidget::willSwitchToTabbedSelectorWithWidth(int newWidth) const {
void HistoryWidget::toggleTabbedSelectorMode() { void HistoryWidget::toggleTabbedSelectorMode() {
if (_tabbedSection) { if (_tabbedSection) {
AuthSession::Current().data().setTabbedSelectorSectionEnabled(false); Auth().data().setTabbedSelectorSectionEnabled(false);
AuthSession::Current().saveDataDelayed(kSaveTabbedSelectorSectionTimeoutMs); Auth().saveDataDelayed(kSaveTabbedSelectorSectionTimeoutMs);
updateTabbedSelectorSectionShown(); updateTabbedSelectorSectionShown();
recountChatWidth(); recountChatWidth();
updateControlsGeometry(); updateControlsGeometry();
} else if (controller()->canProvideChatWidth(minimalWidthForTabbedSelectorSection())) { } else if (controller()->canProvideChatWidth(minimalWidthForTabbedSelectorSection())) {
if (!AuthSession::Current().data().tabbedSelectorSectionEnabled()) { if (!Auth().data().tabbedSelectorSectionEnabled()) {
AuthSession::Current().data().setTabbedSelectorSectionEnabled(true); Auth().data().setTabbedSelectorSectionEnabled(true);
AuthSession::Current().saveDataDelayed(kSaveTabbedSelectorSectionTimeoutMs); Auth().saveDataDelayed(kSaveTabbedSelectorSectionTimeoutMs);
} }
controller()->provideChatWidth(minimalWidthForTabbedSelectorSection()); controller()->provideChatWidth(minimalWidthForTabbedSelectorSection());
updateTabbedSelectorSectionShown(); updateTabbedSelectorSectionShown();
@ -3886,7 +3886,7 @@ void HistoryWidget::updateOnlineDisplay() {
} else if (_peer->isChannel()) { } else if (_peer->isChannel()) {
if (_peer->isMegagroup() && _peer->asChannel()->membersCount() > 0 && _peer->asChannel()->membersCount() <= Global::ChatSizeMax()) { if (_peer->isMegagroup() && _peer->asChannel()->membersCount() > 0 && _peer->asChannel()->membersCount() <= Global::ChatSizeMax()) {
if (_peer->asChannel()->mgInfo->lastParticipants.size() < _peer->asChannel()->membersCount() || _peer->asChannel()->lastParticipantsCountOutdated()) { if (_peer->asChannel()->mgInfo->lastParticipants.size() < _peer->asChannel()->membersCount() || _peer->asChannel()->lastParticipantsCountOutdated()) {
if (App::api()) App::api()->requestLastParticipants(_peer->asChannel()); Auth().api().requestLastParticipants(_peer->asChannel());
} }
auto online = 0; auto online = 0;
bool onlyMe = true; bool onlyMe = true;
@ -4297,15 +4297,15 @@ void HistoryWidget::sendFileConfirmed(const FileLoadResultPtr &file) {
FullMsgId newId(peerToChannel(file->to.peer), clientMsgId()); FullMsgId newId(peerToChannel(file->to.peer), clientMsgId());
connect(App::uploader(), SIGNAL(photoReady(const FullMsgId&,bool,const MTPInputFile&)), this, SLOT(onPhotoUploaded(const FullMsgId&,bool,const MTPInputFile&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(photoReady(const FullMsgId&,bool,const MTPInputFile&)), this, SLOT(onPhotoUploaded(const FullMsgId&,bool,const MTPInputFile&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(documentReady(const FullMsgId&,bool,const MTPInputFile&)), this, SLOT(onDocumentUploaded(const FullMsgId&,bool,const MTPInputFile&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(documentReady(const FullMsgId&,bool,const MTPInputFile&)), this, SLOT(onDocumentUploaded(const FullMsgId&,bool,const MTPInputFile&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(thumbDocumentReady(const FullMsgId&,bool,const MTPInputFile&,const MTPInputFile&)), this, SLOT(onThumbDocumentUploaded(const FullMsgId&,bool,const MTPInputFile&, const MTPInputFile&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(thumbDocumentReady(const FullMsgId&,bool,const MTPInputFile&,const MTPInputFile&)), this, SLOT(onThumbDocumentUploaded(const FullMsgId&,bool,const MTPInputFile&, const MTPInputFile&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(photoProgress(const FullMsgId&)), this, SLOT(onPhotoProgress(const FullMsgId&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(photoProgress(const FullMsgId&)), this, SLOT(onPhotoProgress(const FullMsgId&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(documentProgress(const FullMsgId&)), this, SLOT(onDocumentProgress(const FullMsgId&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(documentProgress(const FullMsgId&)), this, SLOT(onDocumentProgress(const FullMsgId&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(photoFailed(const FullMsgId&)), this, SLOT(onPhotoFailed(const FullMsgId&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(photoFailed(const FullMsgId&)), this, SLOT(onPhotoFailed(const FullMsgId&)), Qt::UniqueConnection);
connect(App::uploader(), SIGNAL(documentFailed(const FullMsgId&)), this, SLOT(onDocumentFailed(const FullMsgId&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(documentFailed(const FullMsgId&)), this, SLOT(onDocumentFailed(const FullMsgId&)), Qt::UniqueConnection);
App::uploader()->upload(newId, file); Auth().uploader().upload(newId, file);
History *h = App::history(file->to.peer); History *h = App::history(file->to.peer);
@ -4327,8 +4327,8 @@ void HistoryWidget::sendFileConfirmed(const FileLoadResultPtr &file) {
if (silentPost) { if (silentPost) {
flags |= MTPDmessage::Flag::f_silent; flags |= MTPDmessage::Flag::f_silent;
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
if (file->type == SendMediaType::Photo) { if (file->type == SendMediaType::Photo) {
auto photoFlags = qFlags(MTPDmessageMediaPhoto::Flag::f_photo); auto photoFlags = qFlags(MTPDmessageMediaPhoto::Flag::f_photo);
if (!file->caption.isEmpty()) { if (!file->caption.isEmpty()) {
@ -5169,8 +5169,8 @@ void HistoryWidget::onInlineResultSend(InlineBots::Result *result, UserData *bot
flags |= MTPDmessage::Flag::f_via_bot_id; flags |= MTPDmessage::Flag::f_via_bot_id;
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
MTPint messageDate = MTP_int(unixtime()); MTPint messageDate = MTP_int(unixtime());
UserId messageViaBotId = bot ? peerToUser(bot->id) : 0; UserId messageViaBotId = bot ? peerToUser(bot->id) : 0;
MsgId messageId = newId.msg; MsgId messageId = newId.msg;
@ -5282,8 +5282,8 @@ bool HistoryWidget::pinnedMsgVisibilityUpdated() {
_pinnedBar->text.clear(); _pinnedBar->text.clear();
updatePinnedBar(); updatePinnedBar();
} }
if (!_pinnedBar->msg && App::api()) { if (!_pinnedBar->msg) {
App::api()->requestMessageData(_peer->asChannel(), _pinnedBar->msgId, replyEditMessageDataCallback()); Auth().api().requestMessageData(_peer->asChannel(), _pinnedBar->msgId, replyEditMessageDataCallback());
} }
} else if (_pinnedBar) { } else if (_pinnedBar) {
destroyPinnedBar(); destroyPinnedBar();
@ -5340,8 +5340,8 @@ bool HistoryWidget::sendExistingDocument(DocumentData *doc, const QString &capti
if (silentPost) { if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent; sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
_history->addNewDocument(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, messagePostAuthor, doc, caption, MTPnullMarkup); _history->addNewDocument(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, messagePostAuthor, doc, caption, MTPnullMarkup);
_history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaDocument(MTP_flags(0), mtpInput, MTP_string(caption), MTPint()), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId); _history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaDocument(MTP_flags(0), mtpInput, MTP_string(caption), MTPint()), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId);
@ -5398,8 +5398,8 @@ void HistoryWidget::sendExistingPhoto(PhotoData *photo, const QString &caption)
if (silentPost) { if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent; sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
_history->addNewPhoto(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, messagePostAuthor, photo, caption, MTPnullMarkup); _history->addNewPhoto(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, messagePostAuthor, photo, caption, MTPnullMarkup);
_history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaPhoto(MTP_flags(0), MTP_inputPhoto(MTP_long(photo->id), MTP_long(photo->access)), MTP_string(caption), MTPint()), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId); _history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaPhoto(MTP_flags(0), MTP_inputPhoto(MTP_long(photo->id), MTP_long(photo->access)), MTP_string(caption), MTPint()), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId);
@ -5903,7 +5903,7 @@ void HistoryWidget::peerUpdated(PeerData *data) {
if (data && data == _peer) { if (data && data == _peer) {
if (auto channel = data->migrateTo()) { if (auto channel = data->migrateTo()) {
Ui::showPeerHistory(channel, ShowAtUnreadMsgId); Ui::showPeerHistory(channel, ShowAtUnreadMsgId);
App::api()->requestParticipantsCountDelayed(channel); Auth().api().requestParticipantsCountDelayed(channel);
return; return;
} }
QString restriction = _peer->restrictionReason(); QString restriction = _peer->restrictionReason();
@ -5918,14 +5918,12 @@ void HistoryWidget::peerUpdated(PeerData *data) {
} }
updateHistoryGeometry(); updateHistoryGeometry();
if (_peer->isChannel()) updateReportSpamStatus(); if (_peer->isChannel()) updateReportSpamStatus();
if (App::api()) { if (data->isChat() && data->asChat()->noParticipantInfo()) {
if (data->isChat() && data->asChat()->noParticipantInfo()) { Auth().api().requestFullPeer(data);
App::api()->requestFullPeer(data); } else if (data->isUser() && (data->asUser()->blockStatus() == UserData::BlockStatus::Unknown || data->asUser()->callsStatus() == UserData::CallsStatus::Unknown)) {
} else if (data->isUser() && (data->asUser()->blockStatus() == UserData::BlockStatus::Unknown || data->asUser()->callsStatus() == UserData::CallsStatus::Unknown)) { Auth().api().requestFullPeer(data);
App::api()->requestFullPeer(data); } else if (data->isMegagroup() && !data->asChannel()->mgInfo->botStatus) {
} else if (data->isMegagroup() && !data->asChannel()->mgInfo->botStatus) { Auth().api().requestBots(data->asChannel());
App::api()->requestBots(data->asChannel());
}
} }
if (!_a_show.animating()) { if (!_a_show.animating()) {
if (_unblock->isHidden() == isBlocked() || (!isBlocked() && _joinChannel->isHidden() == isJoinChannel())) { if (_unblock->isHidden() == isBlocked() || (!isBlocked() && _joinChannel->isHidden() == isJoinChannel())) {

View file

@ -129,7 +129,7 @@ void DeleteSavedGifClickHandler::onClickImpl() const {
MTP::send(MTPmessages_SaveGif(_data->mtpInput(), MTP_bool(true))); MTP::send(MTPmessages_SaveGif(_data->mtpInput(), MTP_bool(true)));
} }
AuthSession::Current().data().savedGifsUpdated().notify(); Auth().data().savedGifsUpdated().notify();
} }
void Gif::paint(Painter &p, const QRect &clip, const PaintContext *context) const { void Gif::paint(Painter &p, const QRect &clip, const PaintContext *context) const {

View file

@ -61,7 +61,7 @@ Inner::Inner(QWidget *parent, gsl::not_null<Window::Controller*> controller) : T
_updateInlineItems.setSingleShot(true); _updateInlineItems.setSingleShot(true);
connect(&_updateInlineItems, SIGNAL(timeout()), this, SLOT(onUpdateInlineItems())); connect(&_updateInlineItems, SIGNAL(timeout()), this, SLOT(onUpdateInlineItems()));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
update(); update();
}); });
subscribe(controller->gifPauseLevelChanged(), [this] { subscribe(controller->gifPauseLevelChanged(), [this] {

View file

@ -457,10 +457,10 @@ void Widget::Step::finish(const MTPUser &user, QImage photo) {
// "this" is already deleted here by creating the main widget. // "this" is already deleted here by creating the main widget.
if (auto user = App::self()) { if (auto user = App::self()) {
App::api()->requestFullPeer(user); Auth().api().requestFullPeer(user);
} }
if (!photo.isNull()) { if (!photo.isNull()) {
App::app()->uploadProfilePhoto(photo, AuthSession::CurrentUserId()); Messenger::Instance().uploadProfilePhoto(photo, Auth().userId());
} }
} }

View file

@ -734,7 +734,7 @@ MediaPreviewWidget::MediaPreviewWidget(QWidget *parent, gsl::not_null<Window::Co
, _controller(controller) , _controller(controller)
, _emojiSize(Ui::Emoji::Size(Ui::Emoji::Index() + 1) / cIntRetinaFactor()) { , _emojiSize(Ui::Emoji::Size(Ui::Emoji::Index() + 1) / cIntRetinaFactor()) {
setAttribute(Qt::WA_TransparentForMouseEvents); setAttribute(Qt::WA_TransparentForMouseEvents);
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
} }
void MediaPreviewWidget::paintEvent(QPaintEvent *e) { void MediaPreviewWidget::paintEvent(QPaintEvent *e) {

View file

@ -148,8 +148,8 @@ MainWidget::MainWidget(QWidget *parent, gsl::not_null<Window::Controller*> contr
handleAudioUpdate(audioId); handleAudioUpdate(audioId);
} }
}); });
subscribe(AuthSession::Current().calls().currentCallChanged(), [this](Calls::Call *call) { setCurrentCall(call); }); subscribe(Auth().calls().currentCallChanged(), [this](Calls::Call *call) { setCurrentCall(call); });
subscribe(AuthSession::Current().api().fullPeerUpdated(), [this](PeerData *peer) { subscribe(Auth().api().fullPeerUpdated(), [this](PeerData *peer) {
emit peerUpdated(peer); emit peerUpdated(peer);
}); });
subscribe(_controller->dialogsListFocused(), [this](bool) { subscribe(_controller->dialogsListFocused(), [this](bool) {
@ -260,8 +260,8 @@ void MainWidget::checkCurrentFloatPlayer() {
}, [this](gsl::not_null<Float*> instance, bool closed) { }, [this](gsl::not_null<Float*> instance, bool closed) {
finishFloatPlayerDrag(instance, closed); finishFloatPlayerDrag(instance, closed);
})); }));
currentFloatPlayer()->column = AuthSession::Current().data().floatPlayerColumn(); currentFloatPlayer()->column = Auth().data().floatPlayerColumn();
currentFloatPlayer()->corner = AuthSession::Current().data().floatPlayerCorner(); currentFloatPlayer()->corner = Auth().data().floatPlayerCorner();
checkFloatPlayerVisibility(); checkFloatPlayerVisibility();
} }
} }
@ -294,7 +294,7 @@ void MainWidget::checkFloatPlayerVisibility() {
auto amVisible = false; auto amVisible = false;
if (auto item = instance->widget->item()) { if (auto item = instance->widget->item()) {
AuthSession::Current().data().queryItemVisibility().notify({ item, &amVisible }, true); Auth().data().queryItemVisibility().notify({ item, &amVisible }, true);
} }
instance->hiddenByHistory = amVisible; instance->hiddenByHistory = amVisible;
toggleFloatPlayer(instance); toggleFloatPlayer(instance);
@ -424,8 +424,8 @@ void MainWidget::updateFloatPlayerColumnCorner(QPoint center) {
Expects(!_playerFloats.empty()); Expects(!_playerFloats.empty());
auto size = _playerFloats.back()->widget->size(); auto size = _playerFloats.back()->widget->size();
auto min = INT_MAX; auto min = INT_MAX;
auto column = AuthSession::Current().data().floatPlayerColumn(); auto column = Auth().data().floatPlayerColumn();
auto corner = AuthSession::Current().data().floatPlayerCorner(); auto corner = Auth().data().floatPlayerCorner();
auto checkSection = [this, center, size, &min, &column, &corner](Window::AbstractSectionWidget *widget, Window::Column myColumn, Window::Column playerColumn) { auto checkSection = [this, center, size, &min, &column, &corner](Window::AbstractSectionWidget *widget, Window::Column myColumn, Window::Column playerColumn) {
auto rect = mapFromGlobal(widget->rectForFloatPlayer(myColumn, playerColumn)); auto rect = mapFromGlobal(widget->rectForFloatPlayer(myColumn, playerColumn));
auto left = rect.x() + (size.width() / 2); auto left = rect.x() + (size.width() / 2);
@ -469,13 +469,13 @@ void MainWidget::updateFloatPlayerColumnCorner(QPoint center) {
checkSection(_history, Window::Column::Second, Window::Column::Third); checkSection(_history, Window::Column::Second, Window::Column::Third);
} }
} }
if (AuthSession::Current().data().floatPlayerColumn() != column) { if (Auth().data().floatPlayerColumn() != column) {
AuthSession::Current().data().setFloatPlayerColumn(column); Auth().data().setFloatPlayerColumn(column);
AuthSession::Current().saveDataDelayed(kSaveFloatPlayerPositionTimeoutMs); Auth().saveDataDelayed(kSaveFloatPlayerPositionTimeoutMs);
} }
if (AuthSession::Current().data().floatPlayerCorner() != corner) { if (Auth().data().floatPlayerCorner() != corner) {
AuthSession::Current().data().setFloatPlayerCorner(corner); Auth().data().setFloatPlayerCorner(corner);
AuthSession::Current().saveDataDelayed(kSaveFloatPlayerPositionTimeoutMs); Auth().saveDataDelayed(kSaveFloatPlayerPositionTimeoutMs);
} }
} }
@ -487,8 +487,8 @@ void MainWidget::finishFloatPlayerDrag(gsl::not_null<Float*> instance, bool clos
instance->animationSide = getFloatPlayerSide(center); instance->animationSide = getFloatPlayerSide(center);
} }
updateFloatPlayerColumnCorner(center); updateFloatPlayerColumnCorner(center);
instance->column = AuthSession::Current().data().floatPlayerColumn(); instance->column = Auth().data().floatPlayerColumn();
instance->corner = AuthSession::Current().data().floatPlayerCorner(); instance->corner = Auth().data().floatPlayerCorner();
instance->draggedAnimation.finish(); instance->draggedAnimation.finish();
instance->draggedAnimation.start([this, instance] { updateFloatPlayerPosition(instance); }, 0., 1., st::slideDuration, anim::sineInOut); instance->draggedAnimation.start([this, instance] { updateFloatPlayerPosition(instance); }, 0., 1., st::slideDuration, anim::sineInOut);
@ -633,8 +633,8 @@ void MainWidget::finishForwarding(History *history, bool silent) {
if (genClientSideMessage) { if (genClientSideMessage) {
if (auto message = i.value()->toHistoryMessage()) { if (auto message = i.value()->toHistoryMessage()) {
auto newId = FullMsgId(peerToChannel(history->peer->id), clientMsgId()); auto newId = FullMsgId(peerToChannel(history->peer->id), clientMsgId());
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
history->addNewForwarded(newId.msg, flags, date(MTP_int(unixtime())), messageFromId, messagePostAuthor, message); history->addNewForwarded(newId.msg, flags, date(MTP_int(unixtime())), messageFromId, messagePostAuthor, message);
App::historyRegRandom(randomId, newId); App::historyRegRandom(randomId, newId);
} }
@ -800,7 +800,7 @@ void MainWidget::notify_migrateUpdated(PeerData *peer) {
void MainWidget::ui_repaintHistoryItem(gsl::not_null<const HistoryItem*> item) { void MainWidget::ui_repaintHistoryItem(gsl::not_null<const HistoryItem*> item) {
if (item->isLogEntry()) { if (item->isLogEntry()) {
AuthSession::Current().data().repaintLogEntry().notify(item, true); Auth().data().repaintLogEntry().notify(item, true);
} else { } else {
_history->ui_repaintHistoryItem(item); _history->ui_repaintHistoryItem(item);
if (item->history()->lastMsg == item) { if (item->history()->lastMsg == item) {
@ -943,16 +943,16 @@ void MainWidget::cancelUploadLayer() {
return; return;
} }
App::uploader()->pause(item->fullId()); Auth().uploader().pause(item->fullId());
Ui::show(Box<ConfirmBox>(lang(lng_selected_cancel_sure_this), lang(lng_selected_upload_stop), lang(lng_continue), base::lambda_guarded(this, [this] { Ui::show(Box<ConfirmBox>(lang(lng_selected_cancel_sure_this), lang(lng_selected_upload_stop), lang(lng_continue), base::lambda_guarded(this, [this] {
if (_overview) { if (_overview) {
_overview->deleteContextItem(false); _overview->deleteContextItem(false);
} else { } else {
_history->deleteContextItem(false); _history->deleteContextItem(false);
} }
App::uploader()->unpause(); Auth().uploader().unpause();
}), base::lambda_guarded(this, [] { }), base::lambda_guarded(this, [] {
App::uploader()->unpause(); Auth().uploader().unpause();
}))); })));
} }
@ -965,9 +965,9 @@ void MainWidget::deletePhotoLayer(PhotoData *photo) {
if (!me) return; if (!me) return;
if (me->photoId == photo->id) { if (me->photoId == photo->id) {
App::app()->peerClearPhoto(me->id); Messenger::Instance().peerClearPhoto(me->id);
} else if (photo->peer && !photo->peer->isUser() && photo->peer->photoId == photo->id) { } else if (photo->peer && !photo->peer->isUser() && photo->peer->photoId == photo->id) {
App::app()->peerClearPhoto(photo->peer->id); Messenger::Instance().peerClearPhoto(photo->peer->id);
} else { } else {
for (int i = 0, l = me->photos.size(); i != l; ++i) { for (int i = 0, l = me->photos.size(); i != l; ++i) {
if (me->photos.at(i) == photo) { if (me->photos.at(i) == photo) {
@ -1465,8 +1465,8 @@ void MainWidget::sendMessage(const MessageToSend &message) {
sendFlags |= MTPmessages_SendMessage::Flag::f_clear_draft; sendFlags |= MTPmessages_SendMessage::Flag::f_clear_draft;
history->clearCloudDraft(); history->clearCloudDraft();
} }
auto messageFromId = channelPost ? 0 : AuthSession::CurrentUserId(); auto messageFromId = channelPost ? 0 : Auth().userId();
auto messagePostAuthor = channelPost ? (AuthSession::CurrentUser()->firstName + ' ' + AuthSession::CurrentUser()->lastName) : QString(); auto messagePostAuthor = channelPost ? (Auth().user()->firstName + ' ' + Auth().user()->lastName) : QString();
lastMessage = history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(history->peer->id), MTPnullFwdHeader, MTPint(), MTP_int(replyTo), MTP_int(unixtime()), msgText, media, MTPnullMarkup, localEntities, MTP_int(1), MTPint(), MTP_string(messagePostAuthor)), NewMessageUnread); lastMessage = history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(history->peer->id), MTPnullFwdHeader, MTPint(), MTP_int(replyTo), MTP_int(unixtime()), msgText, media, MTPnullMarkup, localEntities, MTP_int(1), MTPint(), MTP_string(messagePostAuthor)), NewMessageUnread);
history->sendRequestId = MTP::send(MTPmessages_SendMessage(MTP_flags(sendFlags), history->peer->input, MTP_int(replyTo), msgText, MTP_long(randomId), MTPnullMarkup, sentEntities), rpcDone(&MainWidget::sentUpdatesReceived, randomId), rpcFail(&MainWidget::sendMessageFail), 0, 0, history->sendRequestId); history->sendRequestId = MTP::send(MTPmessages_SendMessage(MTP_flags(sendFlags), history->peer->input, MTP_int(replyTo), msgText, MTP_long(randomId), MTPnullMarkup, sentEntities), rpcDone(&MainWidget::sentUpdatesReceived, randomId), rpcFail(&MainWidget::sendMessageFail), 0, 0, history->sendRequestId);
} }
@ -2028,7 +2028,7 @@ void MainWidget::insertCheckedServiceNotification(const TextWithEntities &messag
HistoryItem *item = nullptr; HistoryItem *item = nullptr;
while (TextUtilities::CutPart(sending, left, MaxMessageSize)) { while (TextUtilities::CutPart(sending, left, MaxMessageSize)) {
auto localEntities = TextUtilities::EntitiesToMTP(sending.entities); auto localEntities = TextUtilities::EntitiesToMTP(sending.entities);
item = App::histories().addNewMessage(MTP_message(MTP_flags(flags), MTP_int(clientMsgId()), MTP_int(ServiceUserId), MTP_peerUser(MTP_int(AuthSession::CurrentUserId())), MTPnullFwdHeader, MTPint(), MTPint(), MTP_int(date), MTP_string(sending.text), media, MTPnullMarkup, localEntities, MTPint(), MTPint(), MTPstring()), NewMessageUnread); item = App::histories().addNewMessage(MTP_message(MTP_flags(flags), MTP_int(clientMsgId()), MTP_int(ServiceUserId), MTP_peerUser(MTP_int(Auth().userId())), MTPnullFwdHeader, MTPint(), MTPint(), MTP_int(date), MTP_string(sending.text), media, MTPnullMarkup, localEntities, MTPint(), MTPint(), MTPstring()), NewMessageUnread);
} }
if (item) { if (item) {
_history->peerMessagesUpdated(item->history()->peer->id); _history->peerMessagesUpdated(item->history()->peer->id);
@ -2321,7 +2321,7 @@ void MainWidget::fillPeerMenu(PeerData *peer, base::lambda<QAction*(const QStrin
*blockSubscription = Notify::PeerUpdated().add_subscription(std::move(blockChangedHandler)); *blockSubscription = Notify::PeerUpdated().add_subscription(std::move(blockChangedHandler));
if (user->blockStatus() == UserData::BlockStatus::Unknown) { if (user->blockStatus() == UserData::BlockStatus::Unknown) {
App::api()->requestFullPeer(user); Auth().api().requestFullPeer(user);
} }
} }
} else if (peer->isChat()) { } else if (peer->isChat()) {
@ -3015,7 +3015,7 @@ bool MainWidget::deleteChannelFailed(const RPCError &error) {
void MainWidget::inviteToChannelDone(ChannelData *channel, const MTPUpdates &updates) { void MainWidget::inviteToChannelDone(ChannelData *channel, const MTPUpdates &updates) {
sentUpdatesReceived(updates); sentUpdatesReceived(updates);
AuthSession::Current().api().requestParticipantsCountDelayed(channel); Auth().api().requestParticipantsCountDelayed(channel);
} }
void MainWidget::historyToDown(History *history) { void MainWidget::historyToDown(History *history) {
@ -3357,7 +3357,7 @@ void MainWidget::updateWindowAdaptiveLayout() {
// for the normal layout. If so, switch to the normal layout. // for the normal layout. If so, switch to the normal layout.
if (layout.windowLayout == Adaptive::WindowLayout::OneColumn) { if (layout.windowLayout == Adaptive::WindowLayout::OneColumn) {
auto chatWidth = layout.chatWidth; auto chatWidth = layout.chatWidth;
if (AuthSession::Current().data().tabbedSelectorSectionEnabled() if (Auth().data().tabbedSelectorSectionEnabled()
&& chatWidth >= _history->minimalWidthForTabbedSelectorSection()) { && chatWidth >= _history->minimalWidthForTabbedSelectorSection()) {
chatWidth -= _history->tabbedSelectorSectionWidth(); chatWidth -= _history->tabbedSelectorSectionWidth();
} }
@ -3790,7 +3790,7 @@ bool MainWidget::ptsUpdateAndApply(int32 pts, int32 ptsCount) {
} }
void MainWidget::feedDifference(const MTPVector<MTPUser> &users, const MTPVector<MTPChat> &chats, const MTPVector<MTPMessage> &msgs, const MTPVector<MTPUpdate> &other) { void MainWidget::feedDifference(const MTPVector<MTPUser> &users, const MTPVector<MTPChat> &chats, const MTPVector<MTPMessage> &msgs, const MTPVector<MTPUpdate> &other) {
AuthSession::Current().checkAutoLock(); Auth().checkAutoLock();
App::feedUsers(users); App::feedUsers(users);
App::feedChats(chats); App::feedChats(chats);
feedMessageIds(other); feedMessageIds(other);
@ -3911,7 +3911,7 @@ void MainWidget::start(const MTPUser *self) {
MTP::send(MTPusers_GetFullUser(MTP_inputUserSelf()), rpcDone(&MainWidget::startWithSelf)); MTP::send(MTPusers_GetFullUser(MTP_inputUserSelf()), rpcDone(&MainWidget::startWithSelf));
return; return;
} }
if (!AuthSession::Current().validateSelf(*self)) { if (!Auth().validateSelf(*self)) {
return; return;
} }
@ -4146,7 +4146,7 @@ void MainWidget::startWithSelf(const MTPUserFull &result) {
auto &d = result.c_userFull(); auto &d = result.c_userFull();
start(&d.vuser); start(&d.vuser);
if (auto user = App::self()) { if (auto user = App::self()) {
App::api()->processFullPeer(user, result); Auth().api().processFullPeer(user, result);
} }
} }
@ -4204,7 +4204,7 @@ void MainWidget::applyNotifySetting(const MTPNotifyPeer &peer, const MTPPeerNoti
if (!h) h = App::history(updatePeer->id); if (!h) h = App::history(updatePeer->id);
int32 changeIn = 0; int32 changeIn = 0;
if (isNotifyMuted(setTo, &changeIn)) { if (isNotifyMuted(setTo, &changeIn)) {
AuthSession::Current().notifications().clearFromHistory(h); Auth().notifications().clearFromHistory(h);
h->setMute(true); h->setMute(true);
App::regMuted(updatePeer, changeIn); App::regMuted(updatePeer, changeIn);
} else { } else {
@ -4389,7 +4389,7 @@ MainWidget::~MainWidget() {
void MainWidget::updateOnline(bool gotOtherOffline) { void MainWidget::updateOnline(bool gotOtherOffline) {
if (this != App::main()) return; if (this != App::main()) return;
AuthSession::Current().checkAutoLock(); Auth().checkAutoLock();
bool isOnline = App::wnd()->isActive(); bool isOnline = App::wnd()->isActive();
int updateIn = Global::OnlineUpdatePeriod(); int updateIn = Global::OnlineUpdatePeriod();
@ -4443,7 +4443,7 @@ void MainWidget::saveDraftToCloud() {
auto localDraft = history->localDraft(); auto localDraft = history->localDraft();
auto cloudDraft = history->cloudDraft(); auto cloudDraft = history->cloudDraft();
if (!Data::draftsAreEqual(localDraft, cloudDraft)) { if (!Data::draftsAreEqual(localDraft, cloudDraft)) {
App::api()->saveDraftToCloudDelayed(history); Auth().api().saveDraftToCloudDelayed(history);
} }
} }
} }
@ -4484,7 +4484,7 @@ void MainWidget::checkIdleFinish() {
void MainWidget::updateReceived(const mtpPrime *from, const mtpPrime *end) { void MainWidget::updateReceived(const mtpPrime *from, const mtpPrime *end) {
if (end <= from) return; if (end <= from) return;
AuthSession::Current().checkAutoLock(); Auth().checkAutoLock();
if (mtpTypeId(*from) == mtpc_new_session_created) { if (mtpTypeId(*from) == mtpc_new_session_created) {
try { try {
@ -4683,7 +4683,9 @@ void MainWidget::feedUpdates(const MTPUpdates &updates, uint64 randomId) {
|| (d.has_entities() && !mentionUsersLoaded(d.ventities)) || (d.has_entities() && !mentionUsersLoaded(d.ventities))
|| (d.has_fwd_from() && !fwdInfoDataLoaded(d.vfwd_from))) { || (d.has_fwd_from() && !fwdInfoDataLoaded(d.vfwd_from))) {
MTP_LOG(0, ("getDifference { good - getting user for updateShortChatMessage }%1").arg(cTestMode() ? " TESTMODE" : "")); MTP_LOG(0, ("getDifference { good - getting user for updateShortChatMessage }%1").arg(cTestMode() ? " TESTMODE" : ""));
if (noFrom && App::api()) App::api()->requestFullPeer(App::chatLoaded(d.vchat_id.v)); if (noFrom) {
Auth().api().requestFullPeer(App::chatLoaded(d.vchat_id.v));
}
return getDifference(); return getDifference();
} }
if (ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, updates)) { if (ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, updates)) {
@ -4707,7 +4709,7 @@ void MainWidget::feedUpdates(const MTPUpdates &updates, uint64 randomId) {
if (peerId) { if (peerId) {
if (auto item = App::histItemById(peerToChannel(peerId), d.vid.v)) { if (auto item = App::histItemById(peerToChannel(peerId), d.vid.v)) {
if (d.has_entities() && !mentionUsersLoaded(d.ventities)) { if (d.has_entities() && !mentionUsersLoaded(d.ventities)) {
AuthSession::Current().api().requestMessageData(item->history()->peer->asChannel(), item->id, ApiWrap::RequestMessageDataCallback()); Auth().api().requestMessageData(item->history()->peer->asChannel(), item->id, ApiWrap::RequestMessageDataCallback());
} }
auto entities = d.has_entities() ? TextUtilities::EntitiesFromMTP(d.ventities.v) : EntitiesInText(); auto entities = d.has_entities() ? TextUtilities::EntitiesFromMTP(d.ventities.v) : EntitiesInText();
item->setText({ text, entities }); item->setText({ text, entities });
@ -4838,7 +4840,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
} else if (auto channel = App::channelLoaded(d.vchat_id.v)) { } else if (auto channel = App::channelLoaded(d.vchat_id.v)) {
history = App::historyLoaded(channel->id); history = App::historyLoaded(channel->id);
} }
auto user = (d.vuser_id.v == AuthSession::CurrentUserId()) ? nullptr : App::userLoaded(d.vuser_id.v); auto user = (d.vuser_id.v == Auth().userId()) ? nullptr : App::userLoaded(d.vuser_id.v);
if (history && user) { if (history && user) {
auto when = requestingDifference() ? 0 : unixtime(); auto when = requestingDifference() ? 0 : unixtime();
App::histories().regSendAction(history, user, d.vaction, when); App::histories().regSendAction(history, user, d.vaction, when);
@ -4883,7 +4885,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
App::markPeerUpdated(user); App::markPeerUpdated(user);
Notify::peerUpdatedDelayed(user, Notify::PeerUpdate::Flag::UserOnlineChanged); Notify::peerUpdatedDelayed(user, Notify::PeerUpdate::Flag::UserOnlineChanged);
} }
if (d.vuser_id.v == AuthSession::CurrentUserId()) { if (d.vuser_id.v == Auth().userId()) {
if (d.vstatus.type() == mtpc_userStatusOffline || d.vstatus.type() == mtpc_userStatusEmpty) { if (d.vstatus.type() == mtpc_userStatusOffline || d.vstatus.type() == mtpc_userStatusEmpty) {
updateOnline(true); updateOnline(true);
if (d.vstatus.type() == mtpc_userStatusOffline) { if (d.vstatus.type() == mtpc_userStatusOffline) {
@ -5011,7 +5013,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
case mtpc_updatePrivacy: { case mtpc_updatePrivacy: {
auto &d = update.c_updatePrivacy(); auto &d = update.c_updatePrivacy();
App::api()->handlePrivacyChange(d.vkey.type(), d.vrules); Auth().api().handlePrivacyChange(d.vkey.type(), d.vrules);
} break; } break;
case mtpc_updatePinnedDialogs: { case mtpc_updatePinnedDialogs: {
@ -5063,7 +5065,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
deleteConversation(channel, false); deleteConversation(channel, false);
} else if (!channel->amCreator() && App::history(channel->id)) { // create history } else if (!channel->amCreator() && App::history(channel->id)) { // create history
_updatedChannels.insert(channel, true); _updatedChannels.insert(channel, true);
if (App::api()) App::api()->requestSelfParticipant(channel); Auth().api().requestSelfParticipant(channel);
} }
} }
} break; } break;
@ -5077,9 +5079,9 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
// Request last active supergroup participants if the 'from' user was not loaded yet. // Request last active supergroup participants if the 'from' user was not loaded yet.
// This will optimize similar getDifference() calls for almost all next messages. // This will optimize similar getDifference() calls for almost all next messages.
if (isDataLoaded == DataIsLoadedResult::FromNotLoaded && channel && channel->isMegagroup() && App::api()) { if (isDataLoaded == DataIsLoadedResult::FromNotLoaded && channel && channel->isMegagroup()) {
if (channel->mgInfo->lastParticipants.size() < Global::ChatSizeMax() && (channel->mgInfo->lastParticipants.isEmpty() || channel->mgInfo->lastParticipants.size() < channel->membersCount())) { if (channel->mgInfo->lastParticipants.size() < Global::ChatSizeMax() && (channel->mgInfo->lastParticipants.isEmpty() || channel->mgInfo->lastParticipants.size() < channel->membersCount())) {
App::api()->requestLastParticipants(channel); Auth().api().requestLastParticipants(channel);
} }
} }
@ -5097,7 +5099,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
_history->peerMessagesUpdated(); _history->peerMessagesUpdated();
} }
} else { } else {
App::api()->applyUpdateNoPtsCheck(update); Auth().api().applyUpdateNoPtsCheck(update);
// We could've added an item. // We could've added an item.
// Better would be for history to be subscribed to new messages. // Better would be for history to be subscribed to new messages.
@ -5116,7 +5118,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
channel->ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, update); channel->ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, update);
} }
} else { } else {
App::api()->applyUpdateNoPtsCheck(update); Auth().api().applyUpdateNoPtsCheck(update);
} }
} break; } break;
@ -5131,9 +5133,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
if (auto channel = App::channelLoaded(d.vchannel_id.v)) { if (auto channel = App::channelLoaded(d.vchannel_id.v)) {
if (channel->isMegagroup()) { if (channel->isMegagroup()) {
channel->mgInfo->pinnedMsgId = d.vid.v; channel->mgInfo->pinnedMsgId = d.vid.v;
if (App::api()) { Auth().api().fullPeerUpdated().notify(channel);
App::api()->fullPeerUpdated().notify(channel);
}
} }
} }
} break; } break;
@ -5169,7 +5169,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
channel->ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, update); channel->ptsUpdateAndApply(d.vpts.v, d.vpts_count.v, update);
} }
} else { } else {
App::api()->applyUpdateNoPtsCheck(update); Auth().api().applyUpdateNoPtsCheck(update);
} }
} break; } break;
@ -5190,7 +5190,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
// Better would be for history to be subscribed to removed messages. // Better would be for history to be subscribed to removed messages.
_history->peerMessagesUpdated(); _history->peerMessagesUpdated();
App::api()->applyUpdateNoPtsCheck(update); Auth().api().applyUpdateNoPtsCheck(update);
} }
} break; } break;
@ -5305,7 +5305,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
} }
if (result.size() != Global::StickerSetsOrder().size() || result.size() != order.size()) { if (result.size() != Global::StickerSetsOrder().size() || result.size() != order.size()) {
Global::SetLastStickersUpdate(0); Global::SetLastStickersUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} else { } else {
Global::SetStickerSetsOrder(result); Global::SetStickerSetsOrder(result);
Local::writeInstalledStickers(); Local::writeInstalledStickers();
@ -5316,17 +5316,17 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
case mtpc_updateStickerSets: { case mtpc_updateStickerSets: {
Global::SetLastStickersUpdate(0); Global::SetLastStickersUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} break; } break;
case mtpc_updateRecentStickers: { case mtpc_updateRecentStickers: {
Global::SetLastRecentStickersUpdate(0); Global::SetLastRecentStickersUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} break; } break;
case mtpc_updateFavedStickers: { case mtpc_updateFavedStickers: {
Global::SetLastFavedStickersUpdate(0); Global::SetLastFavedStickersUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} break; } break;
case mtpc_updateReadFeaturedStickers: { case mtpc_updateReadFeaturedStickers: {
@ -5334,13 +5334,13 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
// Here we don't know what featured sticker sets were read, so we // Here we don't know what featured sticker sets were read, so we
// request all of them once again. // request all of them once again.
Global::SetLastFeaturedStickersUpdate(0); Global::SetLastFeaturedStickersUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} break; } break;
////// Cloud saved GIFs ////// Cloud saved GIFs
case mtpc_updateSavedGifs: { case mtpc_updateSavedGifs: {
cSetLastSavedGifsUpdate(0); cSetLastSavedGifsUpdate(0);
AuthSession::Current().api().updateStickers(); Auth().api().updateStickers();
} break; } break;
////// Cloud drafts ////// Cloud drafts

View file

@ -802,9 +802,9 @@ void MainWindow::toggleDisplayNotifyFromTray() {
} }
} }
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(Window::Notifications::ChangeType::DesktopEnabled); Auth().notifications().settingsChanged().notify(Window::Notifications::ChangeType::DesktopEnabled);
if (soundNotifyChanged) { if (soundNotifyChanged) {
AuthSession::Current().notifications().settingsChanged().notify(Window::Notifications::ChangeType::SoundEnabled); Auth().notifications().settingsChanged().notify(Window::Notifications::ChangeType::SoundEnabled);
} }
} }

View file

@ -69,7 +69,7 @@ Instance::Instance()
// While we have one Media::Player::Instance for all authsessions we have to do this. // While we have one Media::Player::Instance for all authsessions we have to do this.
auto handleAuthSessionChange = [this] { auto handleAuthSessionChange = [this] {
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
subscribe(AuthSession::Current().calls().currentCallChanged(), [this](Calls::Call *call) { subscribe(Auth().calls().currentCallChanged(), [this](Calls::Call *call) {
if (call) { if (call) {
pause(AudioMsgId::Type::Voice); pause(AudioMsgId::Type::Voice);
pause(AudioMsgId::Type::Song); pause(AudioMsgId::Type::Song);

View file

@ -96,12 +96,12 @@ MediaView::MediaView(QWidget*) : TWidget(nullptr)
// While we have one mediaview for all authsessions we have to do this. // While we have one mediaview for all authsessions we have to do this.
auto handleAuthSessionChange = [this] { auto handleAuthSessionChange = [this] {
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
if (!isHidden()) { if (!isHidden()) {
updateControls(); updateControls();
} }
}); });
subscribe(AuthSession::Current().calls().currentCallChanged(), [this](Calls::Call *call) { subscribe(Auth().calls().currentCallChanged(), [this](Calls::Call *call) {
if (call && _clipController && !_videoPaused) { if (call && _clipController && !_videoPaused) {
onVideoPauseResume(); onVideoPauseResume();
} }
@ -1195,7 +1195,7 @@ void MediaView::displayPhoto(PhotoData *photo, HistoryItem *item) {
} }
_zoomToScreen = 0; _zoomToScreen = 0;
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
_full = -1; _full = -1;
_current = QPixmap(); _current = QPixmap();
_down = OverNone; _down = OverNone;
@ -1628,7 +1628,7 @@ void MediaView::onVideoPlayProgress(const AudioMsgId &audioId) {
if (state.length) { if (state.length) {
updateVideoPlaybackState(state); updateVideoPlaybackState(state);
} }
AuthSession::Current().data().setLastTimeVideoPlayedAt(getms(true)); Auth().data().setLastTimeVideoPlayedAt(getms(true));
} }
} }

View file

@ -211,7 +211,7 @@ QByteArray Messenger::serializeMtpAuthorization() const {
QDataStream stream(&result, QIODevice::WriteOnly); QDataStream stream(&result, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_5_1); stream.setVersion(QDataStream::Qt_5_1);
auto currentUserId = AuthSession::Exists() ? AuthSession::CurrentUserId() : 0; auto currentUserId = _authSession ? _authSession->userId() : 0;
stream << qint32(currentUserId) << qint32(mainDcId); stream << qint32(currentUserId) << qint32(mainDcId);
writeKeys(stream, keys); writeKeys(stream, keys);
writeKeys(stream, keysToDestroy); writeKeys(stream, keysToDestroy);
@ -243,8 +243,8 @@ void Messenger::setAuthSessionFromStorage(std::unique_ptr<Local::StoredAuthSessi
AuthSessionData *Messenger::getAuthSessionData() { AuthSessionData *Messenger::getAuthSessionData() {
if (_private->authSessionUserId) { if (_private->authSessionUserId) {
return _private->storedAuthSession ? &_private->storedAuthSession->data : nullptr; return _private->storedAuthSession ? &_private->storedAuthSession->data : nullptr;
} else if (AuthSession::Exists()) { } else if (_authSession) {
return &AuthSession::Current().data(); return &_authSession->data();
} }
return nullptr; return nullptr;
} }
@ -459,7 +459,7 @@ bool Messenger::peerPhotoFail(PeerId peer, const RPCError &error) {
void Messenger::peerClearPhoto(PeerId id) { void Messenger::peerClearPhoto(PeerId id) {
if (!AuthSession::Exists()) return; if (!AuthSession::Exists()) return;
if (id == AuthSession::CurrentUserPeerId()) { if (id == Auth().userPeerId()) {
MTP::send(MTPphotos_UpdateProfilePhoto(MTP_inputPhotoEmpty()), rpcDone(&Messenger::selfPhotoCleared), rpcFail(&Messenger::peerPhotoFail, id)); MTP::send(MTPphotos_UpdateProfilePhoto(MTP_inputPhotoEmpty()), rpcDone(&Messenger::selfPhotoCleared), rpcFail(&Messenger::peerPhotoFail, id));
} else if (peerIsChat(id)) { } else if (peerIsChat(id)) {
MTP::send(MTPmessages_EditChatPhoto(peerToBareMTPInt(id), MTP_inputChatPhotoEmpty()), rpcDone(&Messenger::chatPhotoCleared, id), rpcFail(&Messenger::peerPhotoFail, id)); MTP::send(MTPmessages_EditChatPhoto(peerToBareMTPInt(id), MTP_inputChatPhotoEmpty()), rpcDone(&Messenger::chatPhotoCleared, id), rpcFail(&Messenger::peerPhotoFail, id));
@ -554,7 +554,7 @@ void Messenger::photoUpdated(const FullMsgId &msgId, bool silent, const MTPInput
auto i = photoUpdates.find(msgId); auto i = photoUpdates.find(msgId);
if (i != photoUpdates.end()) { if (i != photoUpdates.end()) {
auto id = i.value(); auto id = i.value();
if (id == AuthSession::CurrentUserPeerId()) { if (id == Auth().userPeerId()) {
MTP::send(MTPphotos_UploadProfilePhoto(file), rpcDone(&Messenger::selfPhotoDone), rpcFail(&Messenger::peerPhotoFail, id)); MTP::send(MTPphotos_UploadProfilePhoto(file), rpcDone(&Messenger::selfPhotoDone), rpcFail(&Messenger::peerPhotoFail, id));
} else if (peerIsChat(id)) { } else if (peerIsChat(id)) {
auto history = App::history(id); auto history = App::history(id);
@ -748,11 +748,6 @@ bool Messenger::openLocalUrl(const QString &url) {
return false; return false;
} }
FileUploader *Messenger::uploader() {
if (!_uploader && !App::quitting()) _uploader = new FileUploader();
return _uploader;
}
void Messenger::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) { void Messenger::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) {
PreparedPhotoThumbs photoThumbs; PreparedPhotoThumbs photoThumbs;
QVector<MTPPhotoSize> photoSizes; QVector<MTPPhotoSize> photoSizes;
@ -783,11 +778,11 @@ void Messenger::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) {
SendMediaReady ready(SendMediaType::Photo, file, filename, filesize, data, id, id, qsl("jpg"), peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg, 0); SendMediaReady ready(SendMediaType::Photo, file, filename, filesize, data, id, id, qsl("jpg"), peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg, 0);
connect(App::uploader(), SIGNAL(photoReady(const FullMsgId&, bool, const MTPInputFile&)), App::app(), SLOT(photoUpdated(const FullMsgId&, bool, const MTPInputFile&)), Qt::UniqueConnection); connect(&Auth().uploader(), SIGNAL(photoReady(const FullMsgId&, bool, const MTPInputFile&)), this, SLOT(photoUpdated(const FullMsgId&, bool, const MTPInputFile&)), Qt::UniqueConnection);
FullMsgId newId(peerToChannel(peerId), clientMsgId()); FullMsgId newId(peerToChannel(peerId), clientMsgId());
App::app()->regPhotoUpdate(peerId, newId); regPhotoUpdate(peerId, newId);
App::uploader()->uploadMedia(newId, ready); Auth().uploader().uploadMedia(newId, ready);
} }
void Messenger::setupPasscode() { void Messenger::setupPasscode() {
@ -825,8 +820,6 @@ Messenger::~Messenger() {
App::deinitMedia(); App::deinitMedia();
deinitLocationManager(); deinitLocationManager();
delete base::take(_uploader);
Window::Theme::Unload(); Window::Theme::Unload();
Media::Player::finish(); Media::Player::finish();
@ -855,10 +848,10 @@ QPoint Messenger::getPointForCallPanelCenter() const {
void Messenger::QuitAttempt() { void Messenger::QuitAttempt() {
auto prevents = false; auto prevents = false;
if (!Sandbox::isSavingSession() && AuthSession::Exists()) { if (!Sandbox::isSavingSession() && AuthSession::Exists()) {
if (AuthSession::Current().api().isQuitPrevent()) { if (Auth().api().isQuitPrevent()) {
prevents = true; prevents = true;
} }
if (AuthSession::Current().calls().isQuitPrevent()) { if (Auth().calls().isQuitPrevent()) {
prevents = true; prevents = true;
} }
} }

View file

@ -136,7 +136,6 @@ public:
void checkStartUrl(); void checkStartUrl();
bool openLocalUrl(const QString &url); bool openLocalUrl(const QString &url);
FileUploader *uploader();
void uploadProfilePhoto(const QImage &tosend, const PeerId &peerId); void uploadProfilePhoto(const QImage &tosend, const PeerId &peerId);
void regPhotoUpdate(const PeerId &peer, const FullMsgId &msgId); void regPhotoUpdate(const PeerId &peer, const FullMsgId &msgId);
bool isPhotoUpdating(const PeerId &peer); bool isPhotoUpdating(const PeerId &peer);
@ -209,8 +208,6 @@ private:
const std::unique_ptr<Private> _private; const std::unique_ptr<Private> _private;
std::unique_ptr<MainWindow> _window; std::unique_ptr<MainWindow> _window;
FileUploader *_uploader = nullptr;
std::unique_ptr<Lang::Instance> _langpack; std::unique_ptr<Lang::Instance> _langpack;
std::unique_ptr<Lang::CloudManager> _langCloudManager; std::unique_ptr<Lang::CloudManager> _langCloudManager;
std::unique_ptr<Lang::Translator> _translator; std::unique_ptr<Lang::Translator> _translator;

View file

@ -63,7 +63,7 @@ OverviewInner::OverviewInner(OverviewWidget *overview, Ui::ScrollArea *scroll, P
, _cancelSearch(this, st::dialogsCancelSearch) , _cancelSearch(this, st::dialogsCancelSearch)
, _itemsToBeLoaded(LinksOverviewPerPage * 2) , _itemsToBeLoaded(LinksOverviewPerPage * 2)
, _width(st::windowMinWidth) { , _width(st::windowMinWidth) {
subscribe(AuthSession::Current().downloader().taskFinished(), [this] { update(); }); subscribe(Auth().downloader().taskFinished(), [this] { update(); });
subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) { subscribe(Global::RefItemRemoved(), [this](HistoryItem *item) {
itemRemoved(item); itemRemoved(item);
}); });
@ -1946,7 +1946,7 @@ void OverviewWidget::clear() {
} }
void OverviewWidget::onScroll() { void OverviewWidget::onScroll() {
AuthSession::Current().downloader().clearPriorities(); Auth().downloader().clearPriorities();
int32 preloadThreshold = _scroll->height() * 5; int32 preloadThreshold = _scroll->height() * 5;
bool needToPreload = false; bool needToPreload = false;
do { do {

View file

@ -75,7 +75,7 @@ bool EventFilter::mainWindowEvent(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPa
case WM_TIMECHANGE: { case WM_TIMECHANGE: {
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
AuthSession::Current().checkAutoLockIn(100); Auth().checkAutoLockIn(100);
} }
} return false; } return false;

View file

@ -101,7 +101,7 @@ void ActionsWidget::validateBlockStatus() const {
return false; return false;
}; };
if (needFullPeer()) { if (needFullPeer()) {
if (App::api()) App::api()->requestFullPeer(peer()); Auth().api().requestFullPeer(peer());
} }
} }
@ -171,7 +171,7 @@ void ActionsWidget::refreshVisibility() {
QString ActionsWidget::getBlockButtonText() const { QString ActionsWidget::getBlockButtonText() const {
auto user = peer()->asUser(); auto user = peer()->asUser();
if (!user || (user->id == AuthSession::CurrentUserPeerId())) return QString(); if (!user || (user->id == Auth().userPeerId())) return QString();
if (user->blockStatus() == UserData::BlockStatus::Unknown) return QString(); if (user->blockStatus() == UserData::BlockStatus::Unknown) return QString();
if (user->isBlocked()) { if (user->isBlocked()) {
@ -323,9 +323,9 @@ void ActionsWidget::onDeleteConversation() {
void ActionsWidget::onBlockUser() { void ActionsWidget::onBlockUser() {
if (auto user = peer()->asUser()) { if (auto user = peer()->asUser()) {
if (user->isBlocked()) { if (user->isBlocked()) {
App::api()->unblockUser(user); Auth().api().unblockUser(user);
} else { } else {
App::api()->blockUser(user); Auth().api().blockUser(user);
} }
} }
} }
@ -363,7 +363,7 @@ void ActionsWidget::onLeaveChannel() {
auto text = lang(channel->isMegagroup() ? lng_sure_leave_group : lng_sure_leave_channel); auto text = lang(channel->isMegagroup() ? lng_sure_leave_group : lng_sure_leave_channel);
Ui::show(Box<ConfirmBox>(text, lang(lng_box_leave), base::lambda_guarded(this, [this] { Ui::show(Box<ConfirmBox>(text, lang(lng_box_leave), base::lambda_guarded(this, [this] {
App::api()->leaveChannel(peer()->asChannel()); Auth().api().leaveChannel(peer()->asChannel());
}))); })));
} }

View file

@ -122,7 +122,7 @@ void GroupMembersWidget::removePeer(PeerData *selectedPeer) {
if (auto chat = peer->asChat()) { if (auto chat = peer->asChat()) {
if (App::main()) App::main()->kickParticipant(chat, user); if (App::main()) App::main()->kickParticipant(chat, user);
} else if (auto channel = peer->asChannel()) { } else if (auto channel = peer->asChannel()) {
if (App::api()) App::api()->kickParticipant(channel, user, currentRestrictedRights); Auth().api().kickParticipant(channel, user, currentRestrictedRights);
} }
})); }));
} }
@ -174,7 +174,7 @@ void GroupMembersWidget::preloadMore() {
if (auto megagroup = peer()->asMegagroup()) { if (auto megagroup = peer()->asMegagroup()) {
auto &megagroupInfo = megagroup->mgInfo; auto &megagroupInfo = megagroup->mgInfo;
if (!megagroupInfo->lastParticipants.isEmpty() && megagroupInfo->lastParticipants.size() < megagroup->membersCount()) { if (!megagroupInfo->lastParticipants.isEmpty() && megagroupInfo->lastParticipants.size() < megagroup->membersCount()) {
App::api()->requestLastParticipants(megagroup, false); Auth().api().requestLastParticipants(megagroup, false);
} }
} }
} }
@ -290,14 +290,14 @@ void GroupMembersWidget::refreshMembers() {
if (auto chat = peer()->asChat()) { if (auto chat = peer()->asChat()) {
checkSelfAdmin(chat); checkSelfAdmin(chat);
if (chat->noParticipantInfo()) { if (chat->noParticipantInfo()) {
App::api()->requestFullPeer(chat); Auth().api().requestFullPeer(chat);
} }
fillChatMembers(chat); fillChatMembers(chat);
refreshLimitReached(); refreshLimitReached();
} else if (auto megagroup = peer()->asMegagroup()) { } else if (auto megagroup = peer()->asMegagroup()) {
auto &megagroupInfo = megagroup->mgInfo; auto &megagroupInfo = megagroup->mgInfo;
if (megagroupInfo->lastParticipants.isEmpty() || megagroup->lastParticipantsCountOutdated()) { if (megagroupInfo->lastParticipants.isEmpty() || megagroup->lastParticipantsCountOutdated()) {
App::api()->requestLastParticipants(megagroup); Auth().api().requestLastParticipants(megagroup);
} }
fillMegagroupMembers(megagroup); fillMegagroupMembers(megagroup);
} }
@ -407,7 +407,7 @@ void GroupMembersWidget::setItemFlags(Item *item, ChatData *chat) {
auto isAdmin = chat->admins.contains(user); auto isAdmin = chat->admins.contains(user);
auto adminState = isCreator ? AdminState::Creator : isAdmin ? AdminState::Admin : AdminState::None; auto adminState = isCreator ? AdminState::Creator : isAdmin ? AdminState::Admin : AdminState::None;
item->adminState = adminState; item->adminState = adminState;
if (item->peer->id == AuthSession::CurrentUserPeerId()) { if (item->peer->id == Auth().userPeerId()) {
item->hasRemoveLink = false; item->hasRemoveLink = false;
} else if (chat->amCreator() || (chat->amAdmin() && (adminState == AdminState::None))) { } else if (chat->amCreator() || (chat->amAdmin() && (adminState == AdminState::None))) {
item->hasRemoveLink = true; item->hasRemoveLink = true;

View file

@ -39,7 +39,7 @@ PeerListWidget::PeerListWidget(QWidget *parent, PeerData *peer, const QString &t
, _removeText(removeText) , _removeText(removeText)
, _removeWidth(st::normalFont->width(_removeText)) { , _removeWidth(st::normalFont->width(_removeText)) {
setMouseTracking(true); setMouseTracking(true);
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
} }
int PeerListWidget::resizeGetHeight(int newWidth) { int PeerListWidget::resizeGetHeight(int newWidth) {

View file

@ -115,7 +115,7 @@ void SettingsWidget::refreshButtons() {
void SettingsWidget::refreshEnableNotifications() { void SettingsWidget::refreshEnableNotifications() {
if (peer()->notify == UnknownNotifySettings) { if (peer()->notify == UnknownNotifySettings) {
App::api()->requestNotifySetting(peer()); Auth().api().requestNotifySetting(peer());
} else { } else {
auto &notifySettings = peer()->notify; auto &notifySettings = peer()->notify;
bool enabled = (notifySettings == EmptyNotifySettings || notifySettings->mute < unixtime()); bool enabled = (notifySettings == EmptyNotifySettings || notifySettings->mute < unixtime());
@ -250,7 +250,7 @@ void SettingsWidget::onInviteLink() {
auto text = lang(link.isEmpty() ? lng_group_invite_about : lng_group_invite_about_new); auto text = lang(link.isEmpty() ? lng_group_invite_about : lng_group_invite_about_new);
Ui::show(Box<ConfirmBox>(text, base::lambda_guarded(this, [this] { Ui::show(Box<ConfirmBox>(text, base::lambda_guarded(this, [this] {
Ui::hideLayer(); Ui::hideLayer();
App::api()->exportInviteLink(peer()); Auth().api().exportInviteLink(peer());
}))); })));
} }

View file

@ -342,7 +342,7 @@ void ParticipantsBoxController::showAdmin(gsl::not_null<UserData*> user) {
if (canSave) { if (canSave) {
box->setSaveCallback([channel = _channel.get(), user, weak](const MTPChannelAdminRights &oldRights, const MTPChannelAdminRights &newRights) { box->setSaveCallback([channel = _channel.get(), user, weak](const MTPChannelAdminRights &oldRights, const MTPChannelAdminRights &newRights) {
MTP::send(MTPchannels_EditAdmin(channel->inputChannel, user->inputUser, newRights), rpcDone([channel, user, weak, oldRights, newRights](const MTPUpdates &result) { MTP::send(MTPchannels_EditAdmin(channel->inputChannel, user->inputUser, newRights), rpcDone([channel, user, weak, oldRights, newRights](const MTPUpdates &result) {
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
channel->applyEditAdmin(user, oldRights, newRights); channel->applyEditAdmin(user, oldRights, newRights);
if (weak) { if (weak) {
weak->editAdminDone(user, newRights); weak->editAdminDone(user, newRights);
@ -396,7 +396,7 @@ void ParticipantsBoxController::showRestricted(gsl::not_null<UserData*> user) {
if (_channel->canBanMembers()) { if (_channel->canBanMembers()) {
box->setSaveCallback([megagroup = _channel.get(), user, weak](const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) { box->setSaveCallback([megagroup = _channel.get(), user, weak](const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) {
MTP::send(MTPchannels_EditBanned(megagroup->inputChannel, user->inputUser, newRights), rpcDone([megagroup, user, weak, oldRights, newRights](const MTPUpdates &result) { MTP::send(MTPchannels_EditBanned(megagroup->inputChannel, user->inputUser, newRights), rpcDone([megagroup, user, weak, oldRights, newRights](const MTPUpdates &result) {
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
megagroup->applyEditBanned(user, oldRights, newRights); megagroup->applyEditBanned(user, oldRights, newRights);
if (weak) { if (weak) {
weak->editRestrictedDone(user, newRights); weak->editRestrictedDone(user, newRights);
@ -470,14 +470,14 @@ void ParticipantsBoxController::kickMemberSure(gsl::not_null<UserData*> user) {
delegate()->peerListRemoveRow(row); delegate()->peerListRemoveRow(row);
delegate()->peerListRefreshRows(); delegate()->peerListRefreshRows();
} }
AuthSession::Current().api().kickParticipant(_channel, user, currentRights); Auth().api().kickParticipant(_channel, user, currentRights);
} }
void ParticipantsBoxController::removeKicked(gsl::not_null<PeerListRow*> row, gsl::not_null<UserData*> user) { void ParticipantsBoxController::removeKicked(gsl::not_null<PeerListRow*> row, gsl::not_null<UserData*> user) {
delegate()->peerListRemoveRow(row); delegate()->peerListRemoveRow(row);
delegate()->peerListRefreshRows(); delegate()->peerListRefreshRows();
AuthSession::Current().api().unblockParticipant(_channel, user); Auth().api().unblockParticipant(_channel, user);
} }
bool ParticipantsBoxController::appendRow(gsl::not_null<UserData*> user) { bool ParticipantsBoxController::appendRow(gsl::not_null<UserData*> user) {
@ -869,7 +869,7 @@ void AddParticipantBoxController::showAdmin(gsl::not_null<UserData*> user, bool
if (!canNotEdit) { if (!canNotEdit) {
box->setSaveCallback([channel = _channel.get(), user, weak](const MTPChannelAdminRights &oldRights, const MTPChannelAdminRights &newRights) { box->setSaveCallback([channel = _channel.get(), user, weak](const MTPChannelAdminRights &oldRights, const MTPChannelAdminRights &newRights) {
MTP::send(MTPchannels_EditAdmin(channel->inputChannel, user->inputUser, newRights), rpcDone([channel, user, weak, oldRights, newRights](const MTPUpdates &result) { MTP::send(MTPchannels_EditAdmin(channel->inputChannel, user->inputUser, newRights), rpcDone([channel, user, weak, oldRights, newRights](const MTPUpdates &result) {
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
channel->applyEditAdmin(user, oldRights, newRights); channel->applyEditAdmin(user, oldRights, newRights);
if (weak) { if (weak) {
weak->editAdminDone(user, newRights); weak->editAdminDone(user, newRights);
@ -965,7 +965,7 @@ void AddParticipantBoxController::showRestricted(gsl::not_null<UserData*> user,
void AddParticipantBoxController::restrictUserSure(gsl::not_null<UserData*> user, const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) { void AddParticipantBoxController::restrictUserSure(gsl::not_null<UserData*> user, const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) {
auto weak = base::weak_unique_ptr<AddParticipantBoxController>(this); auto weak = base::weak_unique_ptr<AddParticipantBoxController>(this);
MTP::send(MTPchannels_EditBanned(_channel->inputChannel, user->inputUser, newRights), rpcDone([megagroup = _channel.get(), user, weak, oldRights, newRights](const MTPUpdates &result) { MTP::send(MTPchannels_EditBanned(_channel->inputChannel, user->inputUser, newRights), rpcDone([megagroup = _channel.get(), user, weak, oldRights, newRights](const MTPUpdates &result) {
AuthSession::Current().api().applyUpdates(result); Auth().api().applyUpdates(result);
megagroup->applyEditBanned(user, oldRights, newRights); megagroup->applyEditBanned(user, oldRights, newRights);
if (weak) { if (weak) {
weak->editRestrictedDone(user, newRights); weak->editRestrictedDone(user, newRights);

View file

@ -33,6 +33,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "boxes/photo_crop_box.h" #include "boxes/photo_crop_box.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "messenger.h"
@ -77,8 +78,8 @@ CoverWidget::CoverWidget(QWidget *parent, PeerData *peer) : TWidget(parent)
notifyPeerUpdated(update); notifyPeerUpdated(update);
})); }));
connect(App::app(), SIGNAL(peerPhotoDone(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId))); connect(&Messenger::Instance(), SIGNAL(peerPhotoDone(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId)));
connect(App::app(), SIGNAL(peerPhotoFail(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId))); connect(&Messenger::Instance(), SIGNAL(peerPhotoFail(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId)));
connect(_userpicButton, SIGNAL(clicked()), this, SLOT(onPhotoShow())); connect(_userpicButton, SIGNAL(clicked()), this, SLOT(onPhotoShow()));
validatePhoto(); validatePhoto();
@ -97,7 +98,7 @@ PhotoData *CoverWidget::validatePhoto() const {
auto photo = (_peer->photoId && _peer->photoId != UnknownPeerPhotoId) ? App::photo(_peer->photoId) : nullptr; auto photo = (_peer->photoId && _peer->photoId != UnknownPeerPhotoId) ? App::photo(_peer->photoId) : nullptr;
_userpicButton->setPointerCursor(photo != nullptr && photo->date != 0); _userpicButton->setPointerCursor(photo != nullptr && photo->date != 0);
if ((_peer->photoId == UnknownPeerPhotoId) || (_peer->photoId && (!photo || !photo->date))) { if ((_peer->photoId == UnknownPeerPhotoId) || (_peer->photoId && (!photo || !photo->date))) {
App::api()->requestFullPeer(_peer); Auth().api().requestFullPeer(_peer);
return nullptr; return nullptr;
} }
return photo; return photo;
@ -557,7 +558,7 @@ void CoverWidget::onAddBotToGroup() {
void CoverWidget::onJoin() { void CoverWidget::onJoin() {
if (!_peerChannel) return; if (!_peerChannel) return;
App::api()->joinChannel(_peerChannel); Auth().api().joinChannel(_peerChannel);
} }
void CoverWidget::onViewChannel() { void CoverWidget::onViewChannel() {

View file

@ -41,7 +41,7 @@ UserpicButton::UserpicButton(QWidget *parent, PeerData *peer, int size) : Abstra
subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(observeEvents, [this](const Notify::PeerUpdate &update) { subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(observeEvents, [this](const Notify::PeerUpdate &update) {
notifyPeerUpdated(update); notifyPeerUpdated(update);
})); }));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { subscribe(Auth().downloaderTaskFinished(), [this] {
if (_waiting && _peer->userpicLoaded()) { if (_waiting && _peer->userpicLoaded()) {
_waiting = false; _waiting = false;
startNewPhotoShowing(); startNewPhotoShowing();

View file

@ -27,6 +27,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "messenger.h" #include "messenger.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h"
#include "profile/profile_userpic_button.h" #include "profile/profile_userpic_button.h"
#include "profile/profile_cover_drop_area.h" #include "profile/profile_cover_drop_area.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
@ -62,8 +63,8 @@ CoverWidget::CoverWidget(QWidget *parent, UserData *self) : BlockWidget(parent,
notifyPeerUpdated(update); notifyPeerUpdated(update);
})); }));
connect(App::app(), SIGNAL(peerPhotoDone(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId))); connect(&Messenger::Instance(), SIGNAL(peerPhotoDone(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId)));
connect(App::app(), SIGNAL(peerPhotoFail(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId))); connect(&Messenger::Instance(), SIGNAL(peerPhotoFail(PeerId)), this, SLOT(onPhotoUploadStatusChanged(PeerId)));
connect(_userpicButton, SIGNAL(clicked()), this, SLOT(onPhotoShow())); connect(_userpicButton, SIGNAL(clicked()), this, SLOT(onPhotoShow()));
validatePhoto(); validatePhoto();
@ -78,7 +79,7 @@ PhotoData *CoverWidget::validatePhoto() const {
auto photo = (_self->photoId && _self->photoId != UnknownPeerPhotoId) ? App::photo(_self->photoId) : nullptr; auto photo = (_self->photoId && _self->photoId != UnknownPeerPhotoId) ? App::photo(_self->photoId) : nullptr;
_userpicButton->setPointerCursor(photo != nullptr && photo->date != 0); _userpicButton->setPointerCursor(photo != nullptr && photo->date != 0);
if ((_self->photoId == UnknownPeerPhotoId) || (_self->photoId && (!photo || !photo->date))) { if ((_self->photoId == UnknownPeerPhotoId) || (_self->photoId && (!photo || !photo->date))) {
App::api()->requestFullPeer(_self); Auth().api().requestFullPeer(_self);
return nullptr; return nullptr;
} }
return photo; return photo;

View file

@ -42,7 +42,7 @@ using ChangeType = Window::Notifications::ChangeType;
NotificationsWidget::NotificationsWidget(QWidget *parent, UserData *self) : BlockWidget(parent, self, lang(lng_settings_section_notify)) { NotificationsWidget::NotificationsWidget(QWidget *parent, UserData *self) : BlockWidget(parent, self, lang(lng_settings_section_notify)) {
createControls(); createControls();
subscribe(AuthSession::Current().notifications().settingsChanged(), [this](ChangeType type) { subscribe(Auth().notifications().settingsChanged(), [this](ChangeType type) {
if (type == ChangeType::DesktopEnabled) { if (type == ChangeType::DesktopEnabled) {
desktopEnabledUpdated(); desktopEnabledUpdated();
} else if (type == ChangeType::ViewParams) { } else if (type == ChangeType::ViewParams) {
@ -101,7 +101,7 @@ void NotificationsWidget::onDesktopNotifications() {
} }
Global::SetDesktopNotify(_desktopNotifications->checked()); Global::SetDesktopNotify(_desktopNotifications->checked());
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::DesktopEnabled); Auth().notifications().settingsChanged().notify(ChangeType::DesktopEnabled);
} }
void NotificationsWidget::desktopEnabledUpdated() { void NotificationsWidget::desktopEnabledUpdated() {
@ -124,7 +124,7 @@ void NotificationsWidget::onShowSenderName() {
} }
Global::SetNotifyView(viewParam); Global::SetNotifyView(viewParam);
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::ViewParams); Auth().notifications().settingsChanged().notify(ChangeType::ViewParams);
} }
void NotificationsWidget::onShowMessagePreview() { void NotificationsWidget::onShowMessagePreview() {
@ -142,7 +142,7 @@ void NotificationsWidget::onShowMessagePreview() {
Global::SetNotifyView(viewParam); Global::SetNotifyView(viewParam);
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::ViewParams); Auth().notifications().settingsChanged().notify(ChangeType::ViewParams);
} }
void NotificationsWidget::viewParamUpdated() { void NotificationsWidget::viewParamUpdated() {
@ -157,7 +157,7 @@ void NotificationsWidget::onNativeNotifications() {
Global::SetNativeNotifications(_nativeNotifications->checked()); Global::SetNativeNotifications(_nativeNotifications->checked());
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().createManager(); Auth().notifications().createManager();
_advanced->toggleAnimated(!Global::NativeNotifications()); _advanced->toggleAnimated(!Global::NativeNotifications());
} }
@ -173,13 +173,13 @@ void NotificationsWidget::onPlaySound() {
Global::SetSoundNotify(_playSound->checked()); Global::SetSoundNotify(_playSound->checked());
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::SoundEnabled); Auth().notifications().settingsChanged().notify(ChangeType::SoundEnabled);
} }
void NotificationsWidget::onIncludeMuted() { void NotificationsWidget::onIncludeMuted() {
Global::SetIncludeMuted(_includeMuted->checked()); Global::SetIncludeMuted(_includeMuted->checked());
Local::writeUserSettings(); Local::writeUserSettings();
AuthSession::Current().notifications().settingsChanged().notify(ChangeType::IncludeMuted); Auth().notifications().settingsChanged().notify(ChangeType::IncludeMuted);
} }
} // namespace Settings } // namespace Settings

View file

@ -146,7 +146,7 @@ void BlockedBoxController::rowActionClicked(gsl::not_null<PeerListRow*> row) {
auto user = row->peer()->asUser(); auto user = row->peer()->asUser();
Expects(user != nullptr); Expects(user != nullptr);
App::api()->unblockUser(user); Auth().api().unblockUser(user);
} }
void BlockedBoxController::receivedUsers(const QVector<MTPContactBlocked> &result) { void BlockedBoxController::receivedUsers(const QVector<MTPContactBlocked> &result) {
@ -185,7 +185,7 @@ void BlockedBoxController::BlockNewUser() {
auto controller = std::make_unique<BlockUserBoxController>(); auto controller = std::make_unique<BlockUserBoxController>();
auto initBox = [controller = controller.get()](PeerListBox *box) { auto initBox = [controller = controller.get()](PeerListBox *box) {
controller->setBlockUserCallback([box](gsl::not_null<UserData*> user) { controller->setBlockUserCallback([box](gsl::not_null<UserData*> user) {
App::api()->blockUser(user); Auth().api().blockUser(user);
box->closeBox(); box->closeBox();
}); });
box->addButton(langFactory(lng_cancel), [box] { box->closeBox(); }); box->addButton(langFactory(lng_cancel), [box] { box->closeBox(); });
@ -261,14 +261,14 @@ QString LastSeenPrivacyController::exceptionsDescription() {
} }
void LastSeenPrivacyController::confirmSave(bool someAreDisallowed, base::lambda_once<void()> saveCallback) { void LastSeenPrivacyController::confirmSave(bool someAreDisallowed, base::lambda_once<void()> saveCallback) {
if (someAreDisallowed && !AuthSession::Current().data().lastSeenWarningSeen()) { if (someAreDisallowed && !Auth().data().lastSeenWarningSeen()) {
auto weakBox = std::make_shared<QPointer<ConfirmBox>>(); auto weakBox = std::make_shared<QPointer<ConfirmBox>>();
auto callback = [weakBox, saveCallback = std::move(saveCallback)]() mutable { auto callback = [weakBox, saveCallback = std::move(saveCallback)]() mutable {
if (auto box = *weakBox) { if (auto box = *weakBox) {
box->closeBox(); box->closeBox();
} }
saveCallback(); saveCallback();
AuthSession::Current().data().setLastSeenWarningSeen(true); Auth().data().setLastSeenWarningSeen(true);
Local::writeUserSettings(); Local::writeUserSettings();
}; };
auto box = Box<ConfirmBox>(lang(lng_edit_privacy_lastseen_warning), lang(lng_continue), lang(lng_cancel), std::move(callback)); auto box = Box<ConfirmBox>(lang(lng_edit_privacy_lastseen_warning), lang(lng_continue), lang(lng_cancel), std::move(callback));

View file

@ -52,13 +52,13 @@ void fillCodes() {
Codes.insert(qsl("debugmode"), [] { Codes.insert(qsl("debugmode"), [] {
QString text = cDebug() ? qsl("Do you want to disable DEBUG logs?") : qsl("Do you want to enable DEBUG logs?\n\nAll network events will be logged."); QString text = cDebug() ? qsl("Do you want to disable DEBUG logs?") : qsl("Do you want to enable DEBUG logs?\n\nAll network events will be logged.");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
App::app()->onSwitchDebugMode(); Messenger::Instance().onSwitchDebugMode();
})); }));
}); });
Codes.insert(qsl("testmode"), [] { Codes.insert(qsl("testmode"), [] {
auto text = cTestMode() ? qsl("Do you want to disable TEST mode?") : qsl("Do you want to enable TEST mode?\n\nYou will be switched to test cloud."); auto text = cTestMode() ? qsl("Do you want to disable TEST mode?") : qsl("Do you want to enable TEST mode?\n\nYou will be switched to test cloud.");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
App::app()->onSwitchTestMode(); Messenger::Instance().onSwitchTestMode();
})); }));
}); });
Codes.insert(qsl("loadlang"), [] { Codes.insert(qsl("loadlang"), [] {
@ -79,7 +79,7 @@ void fillCodes() {
Codes.insert(qsl("workmode"), [] { Codes.insert(qsl("workmode"), [] {
auto text = Global::DialogsModeEnabled() ? qsl("Disable work mode?") : qsl("Enable work mode?"); auto text = Global::DialogsModeEnabled() ? qsl("Disable work mode?") : qsl("Enable work mode?");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
App::app()->onSwitchWorkMode(); Messenger::Instance().onSwitchWorkMode();
})); }));
}); });
Codes.insert(qsl("moderate"), [] { Codes.insert(qsl("moderate"), [] {
@ -145,7 +145,7 @@ void fillCodes() {
if (track->failed()) { if (track->failed()) {
Ui::show(Box<InformBox>("Could not audio :( Errors in 'log.txt'.")); Ui::show(Box<InformBox>("Could not audio :( Errors in 'log.txt'."));
} else { } else {
AuthSession::Current().data().setSoundOverride(key, result.paths.front()); Auth().data().setSoundOverride(key, result.paths.front());
Local::writeUserSettings(); Local::writeUserSettings();
} }
} }
@ -154,7 +154,7 @@ void fillCodes() {
} }
Codes.insert(qsl("sounds_reset"), [] { Codes.insert(qsl("sounds_reset"), [] {
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
AuthSession::Current().data().clearSoundOverrides(); Auth().data().clearSoundOverrides();
Local::writeUserSettings(); Local::writeUserSettings();
Ui::show(Box<InformBox>("All sound overrides were reset.")); Ui::show(Box<InformBox>("All sound overrides were reset."));
} }

View file

@ -114,7 +114,7 @@ WebLoadMainManager *_webLoadMainManager = nullptr;
} // namespace } // namespace
FileLoader::FileLoader(const QString &toFile, int32 size, LocationType locationType, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading) FileLoader::FileLoader(const QString &toFile, int32 size, LocationType locationType, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading)
: _downloader(&AuthSession::Current().downloader()) : _downloader(&Auth().downloader())
, _autoLoading(autoLoading) , _autoLoading(autoLoading)
, _file(toFile) , _file(toFile)
, _fname(toFile) , _fname(toFile)

View file

@ -20,21 +20,21 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/ */
#include "storage/file_upload.h" #include "storage/file_upload.h"
namespace Storage {
namespace { namespace {
constexpr auto kMaxUploadFileParallelSize = MTP::kUploadSessionsCount * 512 * 1024; // max 512kb uploaded at the same time in each session constexpr auto kMaxUploadFileParallelSize = MTP::kUploadSessionsCount * 512 * 1024; // max 512kb uploaded at the same time in each session
} // namespace } // namespace
FileUploader::FileUploader() : sentSize(0) { Uploader::Uploader() {
memset(sentSizes, 0, sizeof(sentSizes));
nextTimer.setSingleShot(true); nextTimer.setSingleShot(true);
connect(&nextTimer, SIGNAL(timeout()), this, SLOT(sendNext())); connect(&nextTimer, SIGNAL(timeout()), this, SLOT(sendNext()));
killSessionsTimer.setSingleShot(true); killSessionsTimer.setSingleShot(true);
connect(&killSessionsTimer, SIGNAL(timeout()), this, SLOT(killSessions())); connect(&killSessionsTimer, SIGNAL(timeout()), this, SLOT(killSessions()));
} }
void FileUploader::uploadMedia(const FullMsgId &msgId, const SendMediaReady &media) { void Uploader::uploadMedia(const FullMsgId &msgId, const SendMediaReady &media) {
if (media.type == SendMediaType::Photo) { if (media.type == SendMediaType::Photo) {
App::feedPhoto(media.photo, media.photoThumbs); App::feedPhoto(media.photo, media.photoThumbs);
} else if (media.type == SendMediaType::File || media.type == SendMediaType::Audio) { } else if (media.type == SendMediaType::File || media.type == SendMediaType::Audio) {
@ -56,7 +56,7 @@ void FileUploader::uploadMedia(const FullMsgId &msgId, const SendMediaReady &med
sendNext(); sendNext();
} }
void FileUploader::upload(const FullMsgId &msgId, const FileLoadResultPtr &file) { void Uploader::upload(const FullMsgId &msgId, const FileLoadResultPtr &file) {
if (file->type == SendMediaType::Photo) { if (file->type == SendMediaType::Photo) {
auto photo = App::feedPhoto(file->photo, file->photoThumbs); auto photo = App::feedPhoto(file->photo, file->photoThumbs);
photo->uploadingData = std::make_unique<PhotoData::UploadingData>(file->partssize); photo->uploadingData = std::make_unique<PhotoData::UploadingData>(file->partssize);
@ -74,7 +74,7 @@ void FileUploader::upload(const FullMsgId &msgId, const FileLoadResultPtr &file)
sendNext(); sendNext();
} }
void FileUploader::currentFailed() { void Uploader::currentFailed() {
Queue::iterator j = queue.find(uploading); Queue::iterator j = queue.find(uploading);
if (j != queue.end()) { if (j != queue.end()) {
if (j->type() == SendMediaType::Photo) { if (j->type() == SendMediaType::Photo) {
@ -101,13 +101,13 @@ void FileUploader::currentFailed() {
sendNext(); sendNext();
} }
void FileUploader::killSessions() { void Uploader::killSessions() {
for (int i = 0; i < MTP::kUploadSessionsCount; ++i) { for (int i = 0; i < MTP::kUploadSessionsCount; ++i) {
MTP::stopSession(MTP::uploadDcId(i)); MTP::stopSession(MTP::uploadDcId(i));
} }
} }
void FileUploader::sendNext() { void Uploader::sendNext() {
if (sentSize >= kMaxUploadFileParallelSize || _paused.msg) return; if (sentSize >= kMaxUploadFileParallelSize || _paused.msg) return;
bool killing = killSessionsTimer.isActive(); bool killing = killSessionsTimer.isActive();
@ -194,9 +194,9 @@ void FileUploader::sendNext() {
} }
mtpRequestId requestId; mtpRequestId requestId;
if (i->docSize > UseBigFilesFrom) { if (i->docSize > UseBigFilesFrom) {
requestId = MTP::send(MTPupload_SaveBigFilePart(MTP_long(i->id()), MTP_int(i->docSentParts), MTP_int(i->docPartsCount), MTP_bytes(toSend)), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::uploadDcId(todc)); requestId = MTP::send(MTPupload_SaveBigFilePart(MTP_long(i->id()), MTP_int(i->docSentParts), MTP_int(i->docPartsCount), MTP_bytes(toSend)), rpcDone(&Uploader::partLoaded), rpcFail(&Uploader::partFailed), MTP::uploadDcId(todc));
} else { } else {
requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(i->id()), MTP_int(i->docSentParts), MTP_bytes(toSend)), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::uploadDcId(todc)); requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(i->id()), MTP_int(i->docSentParts), MTP_bytes(toSend)), rpcDone(&Uploader::partLoaded), rpcFail(&Uploader::partFailed), MTP::uploadDcId(todc));
} }
docRequestsSent.insert(requestId, i->docSentParts); docRequestsSent.insert(requestId, i->docSentParts);
dcMap.insert(requestId, todc); dcMap.insert(requestId, todc);
@ -207,7 +207,7 @@ void FileUploader::sendNext() {
} else { } else {
UploadFileParts::iterator part = parts.begin(); UploadFileParts::iterator part = parts.begin();
mtpRequestId requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(partsOfId), MTP_int(part.key()), MTP_bytes(part.value())), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::uploadDcId(todc)); mtpRequestId requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(partsOfId), MTP_int(part.key()), MTP_bytes(part.value())), rpcDone(&Uploader::partLoaded), rpcFail(&Uploader::partFailed), MTP::uploadDcId(todc));
requestsSent.insert(requestId, part.value()); requestsSent.insert(requestId, part.value());
dcMap.insert(requestId, todc); dcMap.insert(requestId, todc);
sentSize += part.value().size(); sentSize += part.value().size();
@ -218,7 +218,7 @@ void FileUploader::sendNext() {
nextTimer.start(UploadRequestInterval); nextTimer.start(UploadRequestInterval);
} }
void FileUploader::cancel(const FullMsgId &msgId) { void Uploader::cancel(const FullMsgId &msgId) {
uploaded.remove(msgId); uploaded.remove(msgId);
if (uploading == msgId) { if (uploading == msgId) {
currentFailed(); currentFailed();
@ -227,19 +227,19 @@ void FileUploader::cancel(const FullMsgId &msgId) {
} }
} }
void FileUploader::pause(const FullMsgId &msgId) { void Uploader::pause(const FullMsgId &msgId) {
_paused = msgId; _paused = msgId;
} }
void FileUploader::unpause() { void Uploader::unpause() {
_paused = FullMsgId(); _paused = FullMsgId();
sendNext(); sendNext();
} }
void FileUploader::confirm(const FullMsgId &msgId) { void Uploader::confirm(const FullMsgId &msgId) {
} }
void FileUploader::clear() { void Uploader::clear() {
uploaded.clear(); uploaded.clear();
queue.clear(); queue.clear();
for (QMap<mtpRequestId, QByteArray>::const_iterator i = requestsSent.cbegin(), e = requestsSent.cend(); i != e; ++i) { for (QMap<mtpRequestId, QByteArray>::const_iterator i = requestsSent.cbegin(), e = requestsSent.cend(); i != e; ++i) {
@ -259,7 +259,7 @@ void FileUploader::clear() {
killSessionsTimer.stop(); killSessionsTimer.stop();
} }
void FileUploader::partLoaded(const MTPBool &result, mtpRequestId requestId) { void Uploader::partLoaded(const MTPBool &result, mtpRequestId requestId) {
QMap<mtpRequestId, int32>::iterator j = docRequestsSent.end(); QMap<mtpRequestId, int32>::iterator j = docRequestsSent.end();
QMap<mtpRequestId, QByteArray>::iterator i = requestsSent.find(requestId); QMap<mtpRequestId, QByteArray>::iterator i = requestsSent.find(requestId);
if (i == requestsSent.cend()) { if (i == requestsSent.cend()) {
@ -313,7 +313,7 @@ void FileUploader::partLoaded(const MTPBool &result, mtpRequestId requestId) {
sendNext(); sendNext();
} }
bool FileUploader::partFailed(const RPCError &error, mtpRequestId requestId) { bool Uploader::partFailed(const RPCError &error, mtpRequestId requestId) {
if (MTP::isDefaultHandledError(error)) return false; if (MTP::isDefaultHandledError(error)) return false;
if (requestsSent.constFind(requestId) != requestsSent.cend() || docRequestsSent.constFind(requestId) != docRequestsSent.cend()) { // failed to upload current file if (requestsSent.constFind(requestId) != requestsSent.cend() || docRequestsSent.constFind(requestId) != docRequestsSent.cend()) { // failed to upload current file
@ -322,3 +322,9 @@ bool FileUploader::partFailed(const RPCError &error, mtpRequestId requestId) {
sendNext(); sendNext();
return true; return true;
} }
Uploader::~Uploader() {
clear();
}
} // namespace Storage

View file

@ -22,11 +22,13 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "storage/localimageloader.h" #include "storage/localimageloader.h"
class FileUploader : public QObject, public RPCSender { namespace Storage {
class Uploader : public QObject, public RPCSender {
Q_OBJECT Q_OBJECT
public: public:
FileUploader(); Uploader();
void uploadMedia(const FullMsgId &msgId, const SendMediaReady &image); void uploadMedia(const FullMsgId &msgId, const SendMediaReady &image);
void upload(const FullMsgId &msgId, const FileLoadResultPtr &file); void upload(const FullMsgId &msgId, const FileLoadResultPtr &file);
@ -39,6 +41,8 @@ public:
void clear(); void clear();
~Uploader();
public slots: public slots:
void unpause(); void unpause();
void sendNext(); void sendNext();
@ -129,8 +133,8 @@ private:
QMap<mtpRequestId, QByteArray> requestsSent; QMap<mtpRequestId, QByteArray> requestsSent;
QMap<mtpRequestId, int32> docRequestsSent; QMap<mtpRequestId, int32> docRequestsSent;
QMap<mtpRequestId, int32> dcMap; QMap<mtpRequestId, int32> dcMap;
uint32 sentSize; uint32 sentSize = 0;
uint32 sentSizes[MTP::kUploadSessionsCount]; uint32 sentSizes[MTP::kUploadSessionsCount] = { 0 };
FullMsgId uploading, _paused; FullMsgId uploading, _paused;
Queue queue; Queue queue;
@ -138,3 +142,5 @@ private:
QTimer nextTimer, killSessionsTimer; QTimer nextTimer, killSessionsTimer;
}; };
} // namespace Storage

View file

@ -4075,7 +4075,7 @@ PeerData *_readPeer(FileReadDescriptor &from, int32 fileVersion = 0) {
} }
from.stream >> onlineTill >> contact >> botInfoVersion; from.stream >> onlineTill >> contact >> botInfoVersion;
bool showPhone = !isServiceUser(user->id) && (user->id != AuthSession::CurrentUserPeerId()) && (contact <= 0); bool showPhone = !isServiceUser(user->id) && (user->id != Auth().userPeerId()) && (contact <= 0);
QString pname = (showPhone && !phone.isEmpty()) ? App::formatPhone(phone) : QString(); QString pname = (showPhone && !phone.isEmpty()) ? App::formatPhone(phone) : QString();
if (!wasLoaded) { if (!wasLoaded) {
@ -4091,7 +4091,7 @@ PeerData *_readPeer(FileReadDescriptor &from, int32 fileVersion = 0) {
user->botInfo->inlinePlaceholder = inlinePlaceholder; user->botInfo->inlinePlaceholder = inlinePlaceholder;
} }
if (user->id == AuthSession::CurrentUserPeerId()) { if (user->id == Auth().userPeerId()) {
user->input = MTP_inputPeerSelf(); user->input = MTP_inputPeerSelf();
user->inputUser = MTP_inputUserSelf(); user->inputUser = MTP_inputUserSelf();
} else { } else {
@ -4335,7 +4335,7 @@ void readSavedPeers() {
peers.push_back(peer); peers.push_back(peer);
} }
if (App::api()) App::api()->requestPeers(peers); Auth().api().requestPeers(peers);
} }
void addSavedPeer(PeerData *peer, const QDateTime &position) { void addSavedPeer(PeerData *peer, const QDateTime &position) {

View file

@ -44,7 +44,7 @@ namespace {
constexpr auto kUpdateFullPeerTimeout = TimeMs(5000); // Not more than once in 5 seconds. constexpr auto kUpdateFullPeerTimeout = TimeMs(5000); // Not more than once in 5 seconds.
int peerColorIndex(const PeerId &peer) { int peerColorIndex(const PeerId &peer) {
auto myId = AuthSession::CurrentUserId(); auto myId = Auth().userId();
auto peerId = peerToBareInt(peer); auto peerId = peerToBareInt(peer);
auto both = (QByteArray::number(peerId) + QByteArray::number(myId)).mid(0, 15); auto both = (QByteArray::number(peerId) + QByteArray::number(myId)).mid(0, 15);
uchar md5[16]; uchar md5[16];
@ -731,12 +731,10 @@ void PeerData::updateFull() {
} }
void PeerData::updateFullForced() { void PeerData::updateFullForced() {
if (App::api()) { Auth().api().requestFullPeer(this);
App::api()->requestFullPeer(this); if (auto channel = asChannel()) {
if (auto channel = asChannel()) { if (!channel->amCreator() && !channel->inviter) {
if (!channel->amCreator() && !channel->inviter) { Auth().api().requestSelfParticipant(channel);
App::api()->requestSelfParticipant(channel);
}
} }
} }
} }
@ -1032,13 +1030,13 @@ void PtsWaiter::applySkippedUpdates(ChannelData *channel) {
setWaitingForSkipped(channel, -1); setWaitingForSkipped(channel, -1);
if (!App::api() || _queue.isEmpty()) return; if (_queue.isEmpty()) return;
++_applySkippedLevel; ++_applySkippedLevel;
for (QMap<uint64, PtsSkippedQueue>::const_iterator i = _queue.cbegin(), e = _queue.cend(); i != e; ++i) { for (auto i = _queue.cbegin(), e = _queue.cend(); i != e; ++i) {
switch (i.value()) { switch (i.value()) {
case SkippedUpdate: App::api()->applyUpdateNoPtsCheck(_updateQueue.value(i.key())); break; case SkippedUpdate: Auth().api().applyUpdateNoPtsCheck(_updateQueue.value(i.key())); break;
case SkippedUpdates: App::api()->applyUpdatesNoPtsCheck(_updatesQueue.value(i.key())); break; case SkippedUpdates: Auth().api().applyUpdatesNoPtsCheck(_updatesQueue.value(i.key())); break;
} }
} }
--_applySkippedLevel; --_applySkippedLevel;
@ -1091,7 +1089,7 @@ bool PtsWaiter::updateAndApply(ChannelData *channel, int32 pts, int32 count, con
} }
if (!_waitingForSkipped || _queue.isEmpty()) { if (!_waitingForSkipped || _queue.isEmpty()) {
// Optimization - no need to put in queue and back. // Optimization - no need to put in queue and back.
App::api()->applyUpdatesNoPtsCheck(updates); Auth().api().applyUpdatesNoPtsCheck(updates);
} else { } else {
_updatesQueue.insert(ptsKey(SkippedUpdates, pts), updates); _updatesQueue.insert(ptsKey(SkippedUpdates, pts), updates);
applySkippedUpdates(channel); applySkippedUpdates(channel);
@ -1105,7 +1103,7 @@ bool PtsWaiter::updateAndApply(ChannelData *channel, int32 pts, int32 count, con
} }
if (!_waitingForSkipped || _queue.isEmpty()) { if (!_waitingForSkipped || _queue.isEmpty()) {
// Optimization - no need to put in queue and back. // Optimization - no need to put in queue and back.
App::api()->applyUpdateNoPtsCheck(update); Auth().api().applyUpdateNoPtsCheck(update);
} else { } else {
_updateQueue.insert(ptsKey(SkippedUpdate, pts), update); _updateQueue.insert(ptsKey(SkippedUpdate, pts), update);
applySkippedUpdates(channel); applySkippedUpdates(channel);
@ -1844,7 +1842,7 @@ bool DocumentData::loaded(FilePathResolveType type) const {
void DocumentData::destroyLoaderDelayed(mtpFileLoader *newValue) const { void DocumentData::destroyLoaderDelayed(mtpFileLoader *newValue) const {
_loader->stop(); _loader->stop();
auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, newValue)); auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, newValue));
AuthSession::Current().downloader().delayedDestroyLoader(std::move(loader)); Auth().downloader().delayedDestroyLoader(std::move(loader));
} }
bool DocumentData::loading() const { bool DocumentData::loading() const {
@ -1933,7 +1931,7 @@ void DocumentData::cancel() {
auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, CancelledMtpFileLoader)); auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, CancelledMtpFileLoader));
loader->cancel(); loader->cancel();
loader->stop(); loader->stop();
AuthSession::Current().downloader().delayedDestroyLoader(std::move(loader)); Auth().downloader().delayedDestroyLoader(std::move(loader));
notifyLayoutChanged(); notifyLayoutChanged();
if (auto main = App::main()) { if (auto main = App::main()) {

View file

@ -886,7 +886,7 @@ void RemoteImage::doCheckload() const {
void RemoteImage::destroyLoaderDelayed(FileLoader *newValue) const { void RemoteImage::destroyLoaderDelayed(FileLoader *newValue) const {
_loader->stop(); _loader->stop();
auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, newValue)); auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, newValue));
AuthSession::Current().downloader().delayedDestroyLoader(std::move(loader)); Auth().downloader().delayedDestroyLoader(std::move(loader));
} }
void RemoteImage::loadLocal() { void RemoteImage::loadLocal() {
@ -987,7 +987,7 @@ void RemoteImage::cancel() {
auto loader = std::exchange(_loader, CancelledFileLoader); auto loader = std::exchange(_loader, CancelledFileLoader);
loader->cancel(); loader->cancel();
loader->stop(); loader->stop();
AuthSession::Current().downloader().delayedDestroyLoader(std::unique_ptr<FileLoader>(loader)); Auth().downloader().delayedDestroyLoader(std::unique_ptr<FileLoader>(loader));
} }
float64 RemoteImage::progress() const { float64 RemoteImage::progress() const {

View file

@ -1475,7 +1475,7 @@ EntitiesInText EntitiesFromMTP(const QVector<MTPMessageEntity> &entities) {
auto &d = entity.c_inputMessageEntityMentionName(); auto &d = entity.c_inputMessageEntityMentionName();
auto data = ([&d]() -> QString { auto data = ([&d]() -> QString {
if (d.vuser_id.type() == mtpc_inputUserSelf) { if (d.vuser_id.type() == mtpc_inputUserSelf) {
return MentionNameDataFromFields(AuthSession::CurrentUserId()); return MentionNameDataFromFields(Auth().userId());
} else if (d.vuser_id.type() == mtpc_inputUser) { } else if (d.vuser_id.type() == mtpc_inputUser) {
auto &user = d.vuser_id.c_inputUser(); auto &user = d.vuser_id.c_inputUser();
return MentionNameDataFromFields({ user.vuser_id.v, user.vaccess_hash.v }); return MentionNameDataFromFields({ user.vuser_id.v, user.vaccess_hash.v });
@ -1522,7 +1522,7 @@ MTPVector<MTPMessageEntity> EntitiesToMTP(const EntitiesInText &entities, Conver
case EntityInTextMentionName: { case EntityInTextMentionName: {
auto inputUser = ([](const QString &data) -> MTPInputUser { auto inputUser = ([](const QString &data) -> MTPInputUser {
auto fields = MentionNameDataToFields(data); auto fields = MentionNameDataToFields(data);
if (fields.userId == AuthSession::CurrentUserId()) { if (fields.userId == Auth().userId()) {
return MTP_inputUserSelf(); return MTP_inputUserSelf();
} else if (fields.userId) { } else if (fields.userId) {
return MTP_inputUser(MTP_int(fields.userId), MTP_long(fields.accessHash)); return MTP_inputUser(MTP_int(fields.userId), MTP_long(fields.accessHash));

View file

@ -60,7 +60,7 @@ void System::createManager() {
} }
void System::schedule(History *history, HistoryItem *item) { void System::schedule(History *history, HistoryItem *item) {
if (App::quitting() || !history->currentNotification() || !App::api()) return; if (App::quitting() || !history->currentNotification() || !AuthSession::Exists()) return;
auto notifyByFrom = (!history->peer->isUser() && item->mentionsMe()) ? item->from() : nullptr; auto notifyByFrom = (!history->peer->isUser() && item->mentionsMe()) ? item->from() : nullptr;
@ -80,7 +80,7 @@ void System::schedule(History *history, HistoryItem *item) {
return; return;
} }
} else { } else {
App::api()->requestNotifySetting(notifyByFrom); Auth().api().requestNotifySetting(notifyByFrom);
} }
} else { } else {
history->popNotification(item); history->popNotification(item);
@ -89,9 +89,9 @@ void System::schedule(History *history, HistoryItem *item) {
} }
} else { } else {
if (notifyByFrom && notifyByFrom->notify == UnknownNotifySettings) { if (notifyByFrom && notifyByFrom->notify == UnknownNotifySettings) {
App::api()->requestNotifySetting(notifyByFrom); Auth().api().requestNotifySetting(notifyByFrom);
} }
App::api()->requestNotifySetting(history->peer); Auth().api().requestNotifySetting(history->peer);
} }
if (!item->notificationReady()) { if (!item->notificationReady()) {
haveSetting = false; haveSetting = false;
@ -362,7 +362,7 @@ void System::ensureSoundCreated() {
} }
_soundTrack = Media::Audio::Current().createTrack(); _soundTrack = Media::Audio::Current().createTrack();
_soundTrack->fillFromFile(AuthSession::Current().data().getSoundPath(qsl("msg_incoming"))); _soundTrack->fillFromFile(Auth().data().getSoundPath(qsl("msg_incoming")));
} }
void System::updateAll() { void System::updateAll() {

View file

@ -177,7 +177,7 @@ void Controller::showJumpToDate(gsl::not_null<PeerData*> peer, QDate requestedDa
}; };
auto highlighted = requestedDate.isNull() ? currentPeerDate() : requestedDate; auto highlighted = requestedDate.isNull() ? currentPeerDate() : requestedDate;
auto month = highlighted; auto month = highlighted;
auto box = Box<CalendarBox>(month, highlighted, [this, peer](const QDate &date) { AuthSession::Current().api().jumpToDate(peer, date); }); auto box = Box<CalendarBox>(month, highlighted, [this, peer](const QDate &date) { Auth().api().jumpToDate(peer, date); });
box->setMinDate(minPeerDate()); box->setMinDate(minPeerDate());
box->setMaxDate(maxPeerDate()); box->setMaxDate(maxPeerDate());
Ui::show(std::move(box)); Ui::show(std::move(box));

View file

@ -72,8 +72,8 @@ MainMenu::MainMenu(QWidget *parent) : TWidget(parent)
_version->setLink(1, MakeShared<UrlClickHandler>(qsl("https://desktop.telegram.org/changelog"))); _version->setLink(1, MakeShared<UrlClickHandler>(qsl("https://desktop.telegram.org/changelog")));
_version->setLink(2, MakeShared<LambdaClickHandler>([] { Ui::show(Box<AboutBox>()); })); _version->setLink(2, MakeShared<LambdaClickHandler>([] { Ui::show(Box<AboutBox>()); }));
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
subscribe(AuthSession::CurrentDownloaderTaskFinished(), [this] { update(); }); subscribe(Auth().downloaderTaskFinished(), [this] { update(); });
subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(Notify::PeerUpdate::Flag::UserPhoneChanged, [this](const Notify::PeerUpdate &update) { subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(Notify::PeerUpdate::Flag::UserPhoneChanged, [this](const Notify::PeerUpdate &update) {
if (update.peer->isSelf()) { if (update.peer->isSelf()) {
updatePhone(); updatePhone();