1
0
mirror of https://github.com/telegramdesktop/tdesktop synced 2025-03-23 11:47:57 +00:00

Moved MTP::authedId() to AuthSession::Current().

This commit is contained in:
John Preston 2017-02-23 12:32:28 +03:00
parent a35947141c
commit 63c61637f8
29 changed files with 276 additions and 154 deletions

View File

@ -29,6 +29,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "mainwidget.h"
#include "historywidget.h"
#include "localstorage.h"
#include "auth_session.h"
#include "boxes/confirmbox.h"
#include "window/themes/window_theme.h"
@ -591,27 +592,27 @@ void ApiWrap::gotSelfParticipant(ChannelData *channel, const MTPchannels_Channel
return;
}
const auto &p(result.c_channels_channelParticipant());
auto &p = result.c_channels_channelParticipant();
App::feedUsers(p.vusers);
switch (p.vparticipant.type()) {
case mtpc_channelParticipantSelf: {
const auto &d(p.vparticipant.c_channelParticipantSelf());
auto &d = p.vparticipant.c_channelParticipantSelf();
channel->inviter = d.vinviter_id.v;
channel->inviteDate = date(d.vdate);
} break;
case mtpc_channelParticipantCreator: {
const auto &d(p.vparticipant.c_channelParticipantCreator());
channel->inviter = MTP::authedId();
auto &d = p.vparticipant.c_channelParticipantCreator();
channel->inviter = AuthSession::CurrentUserId();
channel->inviteDate = date(MTP_int(channel->date));
} break;
case mtpc_channelParticipantModerator: {
const auto &d(p.vparticipant.c_channelParticipantModerator());
auto &d = p.vparticipant.c_channelParticipantModerator();
channel->inviter = d.vinviter_id.v;
channel->inviteDate = date(d.vdate);
} break;
case mtpc_channelParticipantEditor: {
const auto &d(p.vparticipant.c_channelParticipantEditor());
auto &d = p.vparticipant.c_channelParticipantEditor();
channel->inviter = d.vinviter_id.v;
channel->inviteDate = date(d.vdate);
} break;
@ -1097,7 +1098,7 @@ void ApiWrap::gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result)
if (auto emoji = Ui::Emoji::Find(qs(pack.vemoticon))) {
emoji = emoji->original();
auto &stickers = pack.vdocuments.c_vector().v;
StickerPack p;
p.reserve(stickers.size());
for (auto j = 0, c = stickers.size(); j != c; ++j) {

View File

@ -44,6 +44,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "apiwrap.h"
#include "numbers.h"
#include "observer_peer.h"
#include "auth_session.h"
#include "window/themes/window_theme.h"
#include "window/notifications_manager.h"
#include "platform/platform_notifications_manager.h"
@ -201,7 +202,7 @@ namespace {
w->notifyClearFast();
w->setupIntro();
}
MTP::setAuthedId(0);
AppClass::Instance().authSessionDestroy();
Local::reset();
Window::Theme::Background()->reset();
@ -470,7 +471,7 @@ namespace {
bool showPhoneChanged = !isServiceUser(data->id) && !d.is_self() && ((showPhone && data->contact) || (!showPhone && !data->contact));
if (minimal) {
showPhoneChanged = false;
showPhone = !isServiceUser(data->id) && (data->id != peerFromUser(MTP::authedId())) && !data->contact;
showPhone = !isServiceUser(data->id) && (data->id != AuthSession::CurrentUserPeerId()) && !data->contact;
}
// see also Local::readPeer
@ -546,7 +547,7 @@ namespace {
update.flags |= UpdateFlag::UserOnlineChanged;
}
if (data->contact < 0 && !data->phone().isEmpty() && peerToUser(data->id) != MTP::authedId()) {
if (data->contact < 0 && !data->phone().isEmpty() && data->id != AuthSession::CurrentUserPeerId()) {
data->contact = 0;
}
if (App::main()) {
@ -841,7 +842,7 @@ namespace {
UserData *user = App::userLoaded(uid);
if (user) {
chat->participants[user] = pversion;
if (inviter == MTP::authedId()) {
if (inviter == AuthSession::CurrentUserId()) {
chat->invitedByMe.insert(user);
}
if (i->type() == mtpc_chatParticipantAdmin) {
@ -916,7 +917,7 @@ namespace {
chat->botStatus = 0;
} else if (chat->participants.find(user) == chat->participants.end()) {
chat->participants[user] = (chat->participants.isEmpty() ? 1 : chat->participants.begin().value());
if (d.vinviter_id.v == MTP::authedId()) {
if (d.vinviter_id.v == AuthSession::CurrentUserId()) {
chat->invitedByMe.insert(user);
} else {
chat->invitedByMe.remove(user);
@ -1090,7 +1091,7 @@ namespace {
bool checkEntitiesAndViewsUpdate(const MTPDmessage &m) {
auto peerId = peerFromMTP(m.vto_id);
if (m.has_from_id() && peerToUser(peerId) == MTP::authedId()) {
if (m.has_from_id() && peerId == AuthSession::CurrentUserPeerId()) {
peerId = peerFromUser(m.vfrom_id);
}
if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) {
@ -1115,7 +1116,7 @@ namespace {
template <typename TMTPDclass>
void updateEditedMessage(const TMTPDclass &m) {
auto peerId = peerFromMTP(m.vto_id);
if (m.has_from_id() && peerToUser(peerId) == MTP::authedId()) {
if (m.has_from_id() && peerId == AuthSession::CurrentUserPeerId()) {
peerId = peerFromUser(m.vfrom_id);
}
if (auto existing = App::histItemById(peerToChannel(peerId), m.vid.v)) {
@ -1318,7 +1319,7 @@ namespace {
break;
}
if (user->contact < 1) {
if (user->contact < 0 && !user->phone().isEmpty() && peerToUser(user->id) != MTP::authedId()) {
if (user->contact < 0 && !user->phone().isEmpty() && user->id != AuthSession::CurrentUserPeerId()) {
user->contact = 0;
}
}
@ -1521,10 +1522,6 @@ namespace {
return App::gameSet(game.vid.v, convert, game.vaccess_hash.v, qs(game.vshort_name), qs(game.vtitle), qs(game.vdescription), App::feedPhoto(game.vphoto), game.has_document() ? App::feedDocument(game.vdocument) : nullptr);
}
UserData *curUser() {
return user(MTP::authedId());
}
PeerData *peer(const PeerId &id, PeerData::LoadedStatus restriction) {
if (!id) return nullptr;

View File

@ -40,6 +40,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "history/history_location_manager.h"
#include "core/task_queue.h"
#include "mtproto/dc_options.h"
#include "auth_session.h"
namespace {
@ -764,7 +765,7 @@ AppClass::AppClass() : QObject() {
if (state == Local::ReadMapPassNeeded) {
_window->setupPasscode();
} else {
if (MTP::authedId()) {
if (AuthSession::Current()) {
_window->setupMain();
} else {
_window->setupIntro();
@ -897,12 +898,14 @@ bool AppClass::peerPhotoFail(PeerId peer, const RPCError &error) {
}
void AppClass::peerClearPhoto(PeerId id) {
if (MTP::authedId() && peerToUser(id) == MTP::authedId()) {
if (!AuthSession::Current()) return;
if (id == AuthSession::CurrentUserPeerId()) {
MTP::send(MTPphotos_UpdateProfilePhoto(MTP_inputPhotoEmpty()), rpcDone(&AppClass::selfPhotoCleared), rpcFail(&AppClass::peerPhotoFail, id));
} else if (peerIsChat(id)) {
MTP::send(MTPmessages_EditChatPhoto(peerToBareMTPInt(id), MTP_inputChatPhotoEmpty()), rpcDone(&AppClass::chatPhotoCleared, id), rpcFail(&AppClass::peerPhotoFail, id));
} else if (peerIsChannel(id)) {
if (ChannelData *channel = App::channelLoaded(id)) {
if (auto channel = App::channelLoaded(id)) {
MTP::send(MTPchannels_EditPhoto(channel->inputChannel, MTP_inputChatPhotoEmpty()), rpcDone(&AppClass::chatPhotoCleared, id), rpcFail(&AppClass::peerPhotoFail, id));
}
}
@ -995,12 +998,12 @@ void AppClass::killDownloadSessions() {
}
void AppClass::photoUpdated(const FullMsgId &msgId, bool silent, const MTPInputFile &file) {
if (!App::self()) return;
if (!AuthSession::Current()) return;
auto i = photoUpdates.find(msgId);
if (i != photoUpdates.end()) {
auto id = i.value();
if (MTP::authedId() && peerToUser(id) == MTP::authedId()) {
if (id == AuthSession::CurrentUserPeerId()) {
MTP::send(MTPphotos_UploadProfilePhoto(file), rpcDone(&AppClass::selfPhotoDone), rpcFail(&AppClass::peerPhotoFail, id));
} else if (peerIsChat(id)) {
auto history = App::history(id);
@ -1051,6 +1054,14 @@ void AppClass::onSwitchTestMode() {
App::restart();
}
void AppClass::authSessionCreate(UserId userId) {
_authSession = std::make_unique<AuthSession>(userId);
}
void AppClass::authSessionDestroy() {
_authSession.reset();
}
FileUploader *AppClass::uploader() {
if (!_uploader && !App::quitting()) _uploader = new FileUploader();
return _uploader;

View File

@ -29,6 +29,8 @@ namespace MTP {
class DcOptions;
} // namespace MTP
class AuthSession;
class UpdateChecker;
class Application : public QApplication {
Q_OBJECT
@ -153,6 +155,8 @@ class AppClass : public QObject, public RPCSender, private base::Subscriber {
public:
AppClass();
AppClass(const AppClass &other) = delete;
AppClass &operator=(const AppClass &other) = delete;
void joinThreads();
~AppClass();
@ -166,9 +170,15 @@ public:
t_assert(result != nullptr);
return *result;
}
MTP::DcOptions *dcOptions() {
return _dcOptions.get();
}
AuthSession *authSession() {
return _authSession.get();
}
void authSessionCreate(UserId userId);
void authSessionDestroy();
FileUploader *uploader();
void uploadProfilePhoto(const QImage &tosend, const PeerId &peerId);
@ -232,5 +242,6 @@ private:
Translator *_translator = nullptr;
std::unique_ptr<MTP::DcOptions> _dcOptions;
std::unique_ptr<AuthSession> _authSession;
};

View File

@ -0,0 +1,39 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "stdafx.h"
#include "auth_session.h"
#include "application.h"
AuthSession::AuthSession(UserId userId) : _userId(userId) {
t_assert(_userId != 0);
}
AuthSession *AuthSession::Current() {
return AppClass::Instance().authSession();
}
UserData *AuthSession::CurrentUser() {
if (auto userId = CurrentUserId()) {
return App::user(userId);
}
return nullptr;
}

View File

@ -0,0 +1,48 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
class AuthSession {
public:
AuthSession(UserId userId);
AuthSession(const AuthSession &other) = delete;
AuthSession &operator=(const AuthSession &other) = delete;
static AuthSession *Current();
static UserId CurrentUserId() {
auto current = Current();
return current ? current->userId() : 0;
}
static PeerId CurrentUserPeerId() {
auto userId = CurrentUserId();
return userId ? peerFromUser(userId) : 0;
}
static UserData *CurrentUser();
UserId userId() const {
return _userId;
}
private:
UserId _userId = 0;
};

View File

@ -43,6 +43,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "window/themes/window_theme.h"
#include "observer_peer.h"
#include "apiwrap.h"
#include "auth_session.h"
QString PeerFloodErrorText(PeerFloodType type) {
auto link = textcmdLink(CreateInternalLinkHttps(qsl("spambot")), lang(lng_cant_more_info));
@ -891,9 +892,9 @@ ContactsBox::Inner::ContactData *ContactsBox::Inner::contactData(Dialogs::Row *r
data->disabledChecked = _chat->participants.contains(peer->asUser());
}
} else if (_creating == CreatingGroupGroup) {
data->disabledChecked = (peerToUser(peer->id) == MTP::authedId());
data->disabledChecked = (peer->id == AuthSession::CurrentUserPeerId());
} else if (_channel) {
data->disabledChecked = (peerToUser(peer->id) == MTP::authedId()) || _already.contains(peer->asUser());
data->disabledChecked = (peer->id == AuthSession::CurrentUserPeerId()) || _already.contains(peer->asUser());
}
}
if (usingMultiSelect() && _checkedContacts.contains(peer)) {

View File

@ -39,6 +39,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "ui/widgets/scroll_area.h"
#include "window/themes/window_theme.h"
#include "boxes/contactsbox.h"
#include "auth_session.h"
ShareBox::ShareBox(QWidget*, CopyCallback &&copyCallback, SubmitCallback &&submitCallback, FilterCallback &&filterCallback)
: _copyCallback(std::move(copyCallback))
@ -814,7 +815,7 @@ QString appendShareGameScoreUrl(const QString &url, const FullMsgId &fullId) {
auto channel = fullId.channel ? App::channelLoaded(fullId.channel) : static_cast<ChannelData*>(nullptr);
auto channelAccessHash = channel ? channel->access : 0ULL;
auto channelAccessHashInts = reinterpret_cast<int32*>(&channelAccessHash);
shareHashDataInts[0] = MTP::authedId();
shareHashDataInts[0] = AuthSession::CurrentUserId();
shareHashDataInts[1] = fullId.channel;
shareHashDataInts[2] = fullId.msg;
shareHashDataInts[3] = channelAccessHashInts[0];
@ -953,7 +954,7 @@ void shareGameScoreByHash(const QString &hash) {
}
auto hashDataInts = reinterpret_cast<int32*>(hashData.data());
if (hashDataInts[0] != MTP::authedId()) {
if (hashDataInts[0] != AuthSession::CurrentUserId()) {
Ui::show(Box<InformBox>(lang(lng_share_wrong_user)));
return;
}

View File

@ -45,6 +45,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "window/themes/window_theme.h"
#include "autoupdater.h"
#include "observer_peer.h"
#include "auth_session.h"
namespace {
@ -1563,7 +1564,7 @@ void DialogsInner::contactsReceived(const QVector<MTPContact> &result) {
if (contact.type() != mtpc_contact) continue;
auto userId = contact.c_contact().vuser_id.v;
if (userId == MTP::authedId() && App::self()) {
if (userId == AuthSession::CurrentUserId() && App::self()) {
if (App::self()->contact < 1) {
App::self()->contact = 1;
Notify::userIsContactChanged(App::self());

View File

@ -32,6 +32,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "localstorage.h"
#include "window/top_bar_widget.h"
#include "observer_peer.h"
#include "auth_session.h"
namespace {
@ -406,7 +407,7 @@ HistoryJoined *ChannelHistory::insertJoinedMessage(bool unread) {
if (!inviter) return nullptr;
MTPDmessage::Flags flags = 0;
if (peerToUser(inviter->id) == MTP::authedId()) {
if (inviter->id == AuthSession::CurrentUserPeerId()) {
unread = false;
//} else if (unread) {
// flags |= MTPDmessage::Flag::f_unread;

View File

@ -29,6 +29,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "styles/style_history.h"
#include "ui/effects/ripple_animation.h"
#include "fileuploader.h"
#include "auth_session.h"
namespace {
@ -743,7 +744,7 @@ void HistoryItem::setId(MsgId newId) {
}
bool HistoryItem::canEdit(const QDateTime &cur) const {
auto messageToMyself = (peerToUser(_history->peer->id) == MTP::authedId());
auto messageToMyself = (_history->peer->id == AuthSession::CurrentUserPeerId());
auto messageTooOld = messageToMyself ? false : (date.secsTo(cur) >= Global::EditTimeLimit());
if (id < 0 || messageTooOld) return false;
@ -772,7 +773,7 @@ bool HistoryItem::canEdit(const QDateTime &cur) const {
}
bool HistoryItem::canDeleteForEveryone(const QDateTime &cur) const {
auto messageToMyself = (peerToUser(_history->peer->id) == MTP::authedId());
auto messageToMyself = (_history->peer->id == AuthSession::CurrentUserPeerId());
auto messageTooOld = messageToMyself ? false : (date.secsTo(cur) >= Global::EditTimeLimit());
if (id < 0 || messageToMyself || messageTooOld) return false;
if (history()->peer->isChannel()) return false;

View File

@ -28,6 +28,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "history/history_location_manager.h"
#include "history/history_service_layout.h"
#include "history/history_media_types.h"
#include "auth_session.h"
#include "styles/style_dialogs.h"
#include "styles/style_widgets.h"
#include "styles/style_history.h"
@ -1852,7 +1853,7 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto &v = d.vusers.c_vector().v;
bool foundSelf = false;
for (int i = 0, l = v.size(); i < l; ++i) {
if (v.at(i).v == MTP::authedId()) {
if (v.at(i).v == AuthSession::CurrentUserId()) {
foundSelf = true;
break;
}
@ -2445,7 +2446,7 @@ HistoryJoined::HistoryJoined(History *history, const QDateTime &inviteDate, User
: HistoryService(history, clientMsgId(), inviteDate, QString(), flags) {
Links links;
auto text = ([history, inviter, &links]() {
if (peerToUser(inviter->id) == MTP::authedId()) {
if (inviter->id == AuthSession::CurrentUserPeerId()) {
return lang(history->isMegagroup() ? lng_action_you_joined_group : lng_action_you_joined);
}
links.push_back(peerOpenClickHandler(inviter));

View File

@ -61,12 +61,13 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "core/qthelp_regex.h"
#include "ui/widgets/popup_menu.h"
#include "platform/platform_file_dialog.h"
#include "auth_session.h"
namespace {
QString mimeTagFromTag(const QString &tagId) {
if (tagId.startsWith(qstr("mention://"))) {
return tagId + ':' + QString::number(MTP::authedId());
return tagId + ':' + QString::number(AuthSession::CurrentUserId());
}
return tagId;
}
@ -98,7 +99,7 @@ public:
QString tagFromMimeTag(const QString &mimeTag) override {
if (mimeTag.startsWith(qstr("mention://"))) {
auto match = QRegularExpression(":(\\d+)$").match(mimeTag);
if (!match.hasMatch() || match.capturedRef(1).toInt() != MTP::authedId()) {
if (!match.hasMatch() || match.capturedRef(1).toInt() != AuthSession::CurrentUserId()) {
return QString();
}
return mimeTag.mid(0, mimeTag.size() - match.capturedLength());
@ -4475,7 +4476,7 @@ bool HistoryWidget::contentOverlapped(const QRect &globalRect) {
}
void HistoryWidget::updateReportSpamStatus() {
if (!_peer || (_peer->isUser() && (peerToUser(_peer->id) == MTP::authedId() || isNotificationsUser(_peer->id) || isServiceUser(_peer->id) || _peer->asUser()->botInfo))) {
if (!_peer || (_peer->isUser() && (_peer->id == AuthSession::CurrentUserPeerId() || isNotificationsUser(_peer->id) || isServiceUser(_peer->id) || _peer->asUser()->botInfo))) {
_reportSpamStatus = dbiprsHidden;
return;
} else if (!_firstLoadRequest && _history->isEmpty()) {
@ -5461,7 +5462,8 @@ void HistoryWidget::shareContact(const PeerId &peer, const QString &phone, const
if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
}
history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(showFromName ? MTP::authedId() : 0), 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()), NewMessageUnread);
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
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()), 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);
App::historyRegRandom(randomId, newId);
@ -6791,15 +6793,16 @@ void HistoryWidget::sendFileConfirmed(const FileLoadResultPtr &file) {
if (silentPost) {
flags |= MTPDmessage::Flag::f_silent;
}
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
if (file->type == SendMediaType::Photo) {
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(showFromName ? MTP::authedId() : 0), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaPhoto(file->photo, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaPhoto(file->photo, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
} else if (file->type == SendMediaType::File) {
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(showFromName ? MTP::authedId() : 0), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaDocument(file->document, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaDocument(file->document, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
} else if (file->type == SendMediaType::Audio) {
if (!h->peer->isChannel()) {
flags |= MTPDmessage::Flag::f_media_unread;
}
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(showFromName ? MTP::authedId() : 0), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaDocument(file->document, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
h->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(messageFromId), peerToMTP(file->to.peer), MTPnullFwdHeader, MTPint(), MTP_int(file->to.replyTo), MTP_int(unixtime()), MTP_string(""), MTP_messageMediaDocument(file->document, MTP_string(file->caption)), MTPnullMarkup, MTPnullEntities, MTP_int(1), MTPint()), NewMessageUnread);
}
if (_peer && file->to.peer == _peer->id) {
@ -6812,9 +6815,9 @@ void HistoryWidget::sendFileConfirmed(const FileLoadResultPtr &file) {
}
void HistoryWidget::onPhotoUploaded(const FullMsgId &newId, bool silent, const MTPInputFile &file) {
if (!MTP::authedId()) return;
HistoryItem *item = App::histItemById(newId);
if (item) {
if (!AuthSession::Current()) return;
if (auto item = App::histItemById(newId)) {
uint64 randomId = rand_value<uint64>();
App::historyRegRandom(randomId, newId);
History *hist = item->history();
@ -6862,11 +6865,11 @@ namespace {
}
void HistoryWidget::onDocumentUploaded(const FullMsgId &newId, bool silent, const MTPInputFile &file) {
if (!MTP::authedId()) return;
HistoryMessage *item = dynamic_cast<HistoryMessage*>(App::histItemById(newId));
if (item) {
DocumentData *document = item->getMedia() ? item->getMedia()->getDocument() : 0;
if (document) {
if (!AuthSession::Current()) return;
if (auto item = dynamic_cast<HistoryMessage*>(App::histItemById(newId))) {
auto media = item->getMedia();
if (auto document = media ? media->getDocument() : nullptr) {
uint64 randomId = rand_value<uint64>();
App::historyRegRandom(randomId, newId);
History *hist = item->history();
@ -6890,11 +6893,11 @@ void HistoryWidget::onDocumentUploaded(const FullMsgId &newId, bool silent, cons
}
void HistoryWidget::onThumbDocumentUploaded(const FullMsgId &newId, bool silent, const MTPInputFile &file, const MTPInputFile &thumb) {
if (!MTP::authedId()) return;
HistoryMessage *item = dynamic_cast<HistoryMessage*>(App::histItemById(newId));
if (item) {
DocumentData *document = item->getMedia() ? item->getMedia()->getDocument() : 0;
if (document) {
if (!AuthSession::Current()) return;
if (auto item = dynamic_cast<HistoryMessage*>(App::histItemById(newId))) {
auto media = item->getMedia();
if (auto document = media ? media->getDocument() : nullptr) {
uint64 randomId = rand_value<uint64>();
App::historyRegRandom(randomId, newId);
History *hist = item->history();
@ -6909,7 +6912,7 @@ void HistoryWidget::onThumbDocumentUploaded(const FullMsgId &newId, bool silent,
if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
}
auto caption = item->getMedia() ? item->getMedia()->getCaption() : TextWithEntities();
auto caption = media ? media->getCaption() : TextWithEntities();
MTPDinputMediaUploadedThumbDocument::Flags mediaFlags = 0;
auto media = MTP_inputMediaUploadedThumbDocument(MTP_flags(mediaFlags), file, thumb, MTP_string(document->mime), _composeDocumentAttributes(document), MTP_string(caption.text), MTPVector<MTPInputDocument>());
hist->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), item->history()->peer->input, MTP_int(replyTo), media, MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, hist->sendRequestId);
@ -6918,9 +6921,10 @@ void HistoryWidget::onThumbDocumentUploaded(const FullMsgId &newId, bool silent,
}
void HistoryWidget::onPhotoProgress(const FullMsgId &newId) {
if (!MTP::authedId()) return;
if (HistoryItem *item = App::histItemById(newId)) {
PhotoData *photo = (item->getMedia() && item->getMedia()->type() == MediaTypePhoto) ? static_cast<HistoryPhoto*>(item->getMedia())->photo() : 0;
if (!AuthSession::Current()) return;
if (auto item = App::histItemById(newId)) {
auto photo = (item->getMedia() && item->getMedia()->type() == MediaTypePhoto) ? static_cast<HistoryPhoto*>(item->getMedia())->photo() : nullptr;
if (!item->isPost()) {
updateSendAction(item->history(), SendAction::Type::UploadPhoto, 0);
}
@ -6929,19 +6933,21 @@ void HistoryWidget::onPhotoProgress(const FullMsgId &newId) {
}
void HistoryWidget::onDocumentProgress(const FullMsgId &newId) {
if (!MTP::authedId()) return;
if (HistoryItem *item = App::histItemById(newId)) {
HistoryMedia *media = item->getMedia();
DocumentData *doc = media ? media->getDocument() : 0;
if (!AuthSession::Current()) return;
if (auto item = App::histItemById(newId)) {
auto media = item->getMedia();
auto document = media ? media->getDocument() : nullptr;
if (!item->isPost()) {
updateSendAction(item->history(), (doc && doc->voice()) ? SendAction::Type::UploadVoice : SendAction::Type::UploadFile, doc ? doc->uploadOffset : 0);
updateSendAction(item->history(), (document && document->voice()) ? SendAction::Type::UploadVoice : SendAction::Type::UploadFile, document ? document->uploadOffset : 0);
}
Ui::repaintHistoryItem(item);
}
}
void HistoryWidget::onPhotoFailed(const FullMsgId &newId) {
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
HistoryItem *item = App::histItemById(newId);
if (item) {
if (!item->isPost()) {
@ -6952,13 +6958,13 @@ void HistoryWidget::onPhotoFailed(const FullMsgId &newId) {
}
void HistoryWidget::onDocumentFailed(const FullMsgId &newId) {
if (!MTP::authedId()) return;
HistoryItem *item = App::histItemById(newId);
if (item) {
HistoryMedia *media = item->getMedia();
DocumentData *doc = media ? media->getDocument() : 0;
if (!AuthSession::Current()) return;
if (auto item = App::histItemById(newId)) {
auto media = item->getMedia();
auto document = media ? media->getDocument() : nullptr;
if (!item->isPost()) {
updateSendAction(item->history(), (doc && doc->voice()) ? SendAction::Type::UploadVoice : SendAction::Type::UploadFile, -1);
updateSendAction(item->history(), (document && document->voice()) ? SendAction::Type::UploadVoice : SendAction::Type::UploadFile, -1);
}
Ui::repaintHistoryItem(item);
}
@ -7637,7 +7643,7 @@ void HistoryWidget::onInlineResultSend(InlineBots::Result *result, UserData *bot
flags |= MTPDmessage::Flag::f_via_bot_id;
}
UserId messageFromId = showFromName ? MTP::authedId() : 0;
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
MTPint messageDate = MTP_int(unixtime());
UserId messageViaBotId = bot ? peerToUser(bot->id) : 0;
MsgId messageId = newId.msg;
@ -7813,7 +7819,8 @@ bool HistoryWidget::sendExistingDocument(DocumentData *doc, const QString &capti
if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
}
_history->addNewDocument(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), showFromName ? MTP::authedId() : 0, doc, caption, MTPnullMarkup);
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
_history->addNewDocument(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, doc, caption, MTPnullMarkup);
_history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaDocument(mtpInput, MTP_string(caption)), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId);
App::main()->finishForwarding(_history, _silent->checked());
@ -7868,7 +7875,8 @@ void HistoryWidget::sendExistingPhoto(PhotoData *photo, const QString &caption)
if (silentPost) {
sendFlags |= MTPmessages_SendMedia::Flag::f_silent;
}
_history->addNewPhoto(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), showFromName ? MTP::authedId() : 0, photo, caption, MTPnullMarkup);
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
_history->addNewPhoto(newId.msg, flags, 0, replyToId(), date(MTP_int(unixtime())), messageFromId, photo, caption, MTPnullMarkup);
_history->sendRequestId = MTP::send(MTPmessages_SendMedia(MTP_flags(sendFlags), _peer->input, MTP_int(replyToId()), MTP_inputMediaPhoto(MTP_inputPhoto(MTP_long(photo->id), MTP_long(photo->access)), MTP_string(caption)), MTP_long(randomId), MTPnullMarkup), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::sendMessageFail), 0, 0, _history->sendRequestId);
App::main()->finishForwarding(_history, _silent->checked());

View File

@ -44,6 +44,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "styles/style_intro.h"
#include "styles/style_window.h"
#include "window/themes/window_theme.h"
#include "auth_session.h"
namespace Intro {
@ -428,7 +429,7 @@ void Widget::Step::finish(const MTPUser &user, QImage photo) {
// "this" is already deleted here by creating the main widget.
if (!photo.isNull()) {
App::app()->uploadProfilePhoto(photo, MTP::authedId());
App::app()->uploadProfilePhoto(photo, AuthSession::CurrentUserId());
}
}

View File

@ -36,6 +36,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "mtproto/dc_options.h"
#include "application.h"
#include "apiwrap.h"
#include "auth_session.h"
namespace Local {
namespace {
@ -902,12 +903,16 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting
case dbiUser: {
quint32 dcId;
qint32 uid;
stream >> uid >> dcId;
qint32 userId;
stream >> userId >> dcId;
if (!_checkStreamStatus(stream)) return false;
DEBUG_LOG(("MTP Info: user found, dc %1, uid %2").arg(dcId).arg(uid));
MTP::configure(dcId, uid);
DEBUG_LOG(("MTP Info: user found, dc %1, uid %2").arg(dcId).arg(userId));
MTP::configure(dcId);
if (userId) {
AppClass::Instance().authSessionCreate(UserId(userId));
}
} break;
case dbiKey: {
@ -1777,7 +1782,7 @@ void _writeMtpData() {
size += keys.size() * (sizeof(quint32) + sizeof(quint32) + MTP::AuthKey::kSize);
EncryptedDescriptor data(size);
data.stream << quint32(dbiUser) << qint32(MTP::authedId()) << quint32(MTP::maindc());
data.stream << quint32(dbiUser) << qint32(AuthSession::CurrentUserId()) << quint32(MTP::maindc());
for_const (auto &key, keys) {
data.stream << quint32(dbiKey) << quint32(key->getDC());
key->write(data.stream);
@ -3904,7 +3909,7 @@ PeerData *_readPeer(FileReadDescriptor &from, int32 fileVersion = 0) {
}
from.stream >> onlineTill >> contact >> botInfoVersion;
bool showPhone = !isServiceUser(user->id) && (peerToUser(user->id) != MTP::authedId()) && (contact <= 0);
bool showPhone = !isServiceUser(user->id) && (user->id != AuthSession::CurrentUserPeerId()) && (contact <= 0);
QString pname = (showPhone && !phone.isEmpty()) ? App::formatPhone(phone) : QString();
if (!wasLoaded) {
@ -3920,7 +3925,7 @@ PeerData *_readPeer(FileReadDescriptor &from, int32 fileVersion = 0) {
user->botInfo->inlinePlaceholder = inlinePlaceholder;
}
if (peerToUser(user->id) == MTP::authedId()) {
if (user->id == AuthSession::CurrentUserPeerId()) {
user->input = MTP_inputPeerSelf();
user->inputUser = MTP_inputUserSelf();
} else {

View File

@ -61,6 +61,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "window/player_wrap_widget.h"
#include "styles/style_boxes.h"
#include "mtproto/dc_options.h"
#include "auth_session.h"
StackItemSection::StackItemSection(std::unique_ptr<Window::SectionMemento> &&memento) : StackItem(nullptr)
, _memento(std::move(memento)) {
@ -375,8 +376,9 @@ void MainWidget::finishForwarding(History *history, bool silent) {
uint64 randomId = rand_value<uint64>();
if (genClientSideMessage) {
FullMsgId newId(peerToChannel(history->peer->id), clientMsgId());
HistoryMessage *msg = static_cast<HistoryMessage*>(_toForward.cbegin().value());
history->addNewForwarded(newId.msg, flags, date(MTP_int(unixtime())), showFromName ? MTP::authedId() : 0, msg);
auto msg = static_cast<HistoryMessage*>(_toForward.cbegin().value());
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
history->addNewForwarded(newId.msg, flags, date(MTP_int(unixtime())), messageFromId, msg);
App::historyRegRandom(randomId, newId);
}
if (forwardFrom != i.value()->history()->peer) {
@ -807,7 +809,7 @@ void MainWidget::deleteHistoryPart(DeleteHistoryRequest request, const MTPmessag
}
int32 offset = d.voffset.v;
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
if (offset <= 0) {
cRefReportSpamStatuses().remove(peer->id);
Local::writeReportSpamStatuses();
@ -906,7 +908,7 @@ void MainWidget::deleteAllFromUserPart(DeleteAllFromUserParams params, const MTP
}
int32 offset = d.voffset.v;
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
if (offset > 0) {
MTP::send(MTPchannels_DeleteUserHistory(params.channel->inputChannel, params.from->inputUser), rpcDone(&MainWidget::deleteAllFromUserPart, params));
} else if (History *h = App::historyLoaded(params.channel)) {
@ -1249,7 +1251,8 @@ void MainWidget::sendMessage(const MessageToSend &message) {
sendFlags |= MTPmessages_SendMessage::Flag::f_clear_draft;
history->clearCloudDraft();
}
lastMessage = history->addNewMessage(MTP_message(MTP_flags(flags), MTP_int(newId.msg), MTP_int(showFromName ? MTP::authedId() : 0), peerToMTP(history->peer->id), MTPnullFwdHeader, MTPint(), MTP_int(replyTo), MTP_int(unixtime()), msgText, media, MTPnullMarkup, localEntities, MTP_int(1), MTPint()), NewMessageUnread);
auto messageFromId = showFromName ? AuthSession::CurrentUserId() : 0;
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()), 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);
}
@ -1500,7 +1503,7 @@ void MainWidget::overviewLoaded(History *history, const MTPmessages_Messages &re
}
void MainWidget::sendReadRequest(PeerData *peer, MsgId upTo) {
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
if (peer->isChannel()) {
_readRequests.insert(peer, qMakePair(MTP::send(MTPchannels_ReadHistory(peer->asChannel()->inputChannel, MTP_int(upTo)), rpcDone(&MainWidget::channelReadDone, peer), rpcFail(&MainWidget::readRequestFail, peer)), upTo));
} else {
@ -1805,7 +1808,7 @@ void MainWidget::serviceNotification(const TextWithEntities &message, const MTPM
HistoryItem *item = nullptr;
while (textSplit(sendingText, sendingEntities, leftText, leftEntities, MaxMessageSize)) {
MTPVector<MTPMessageEntity> localEntities = linksToMTP(sendingEntities);
item = App::histories().addNewMessage(MTP_message(MTP_flags(flags), MTP_int(clientMsgId()), MTP_int(ServiceUserId), MTP_peerUser(MTP_int(MTP::authedId())), MTPnullFwdHeader, MTPint(), MTPint(), MTP_int(date), MTP_string(sendingText), media, MTPnullMarkup, localEntities, MTPint(), MTPint()), NewMessageUnread);
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(sendingText), media, MTPnullMarkup, localEntities, MTPint(), MTPint()), NewMessageUnread);
}
if (item) {
_history->peerMessagesUpdated(item->history()->peer->id);
@ -2102,7 +2105,7 @@ void MainWidget::fillPeerMenu(PeerData *peer, base::lambda<QAction*(const QStrin
}
void MainWidget::onViewsIncrement() {
if (!App::main() || !MTP::authedId()) return;
if (!App::main() || !AuthSession::Current()) return;
for (ViewsIncrement::iterator i = _viewsToIncrement.begin(); i != _viewsToIncrement.cend();) {
if (_viewsIncrementRequests.contains(i.key())) {
@ -3624,7 +3627,7 @@ bool MainWidget::failDifference(const RPCError &error) {
}
void MainWidget::onGetDifferenceTimeByPts() {
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
auto now = getms(true), wait = 0LL;
if (_getDifferenceTimeByPts) {
@ -3651,7 +3654,7 @@ void MainWidget::onGetDifferenceTimeByPts() {
}
void MainWidget::onGetDifferenceTimeAfterFail() {
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
auto now = getms(true), wait = 0LL;
if (_getDifferenceTimeAfterFail) {
@ -3729,8 +3732,13 @@ void MainWidget::mtpPing() {
void MainWidget::start(const MTPUser &user) {
int32 uid = user.c_user().vid.v;
if (MTP::authedId() != uid) {
MTP::setAuthedId(uid);
if (!uid) {
LOG(("MTP Error: incorrect user received"));
App::logOut();
return;
}
if (AuthSession::CurrentUserId() != uid) {
AppClass::Instance().authSessionCreate(uid);
Local::writeMtpData();
}
@ -4370,7 +4378,7 @@ void MainWidget::checkIdleFinish() {
}
void MainWidget::updateReceived(const mtpPrime *from, const mtpPrime *end) {
if (end <= from || !MTP::authedId()) return;
if (end <= from || !AuthSession::Current()) return;
App::wnd()->checkAutoLock();
@ -4553,7 +4561,7 @@ void MainWidget::feedUpdates(const MTPUpdates &updates, uint64 randomId) {
// update before applying skipped
MTPDmessage::Flags flags = mtpCastFlags(d.vflags.v) | MTPDmessage::Flag::f_from_id;
auto item = App::histories().addNewMessage(MTP_message(MTP_flags(flags), d.vid, d.is_out() ? MTP_int(MTP::authedId()) : d.vuser_id, MTP_peerUser(d.is_out() ? d.vuser_id : MTP_int(MTP::authedId())), 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()), NewMessageUnread);
auto item = 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()), NewMessageUnread);
if (item) {
_history->peerMessagesUpdated(item->history()->peer->id);
}
@ -4629,7 +4637,7 @@ void MainWidget::feedUpdates(const MTPUpdates &updates, uint64 randomId) {
}
void MainWidget::feedUpdate(const MTPUpdate &update) {
if (!MTP::authedId()) return;
if (!AuthSession::Current()) return;
switch (update.type()) {
case mtpc_updateNewMessage: {
@ -4796,7 +4804,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
} else if (auto channel = App::channelLoaded(d.vchat_id.v)) {
history = App::historyLoaded(channel->id);
}
auto user = (d.vuser_id.v == MTP::authedId()) ? nullptr : App::userLoaded(d.vuser_id.v);
auto user = (d.vuser_id.v == AuthSession::CurrentUserId()) ? nullptr : App::userLoaded(d.vuser_id.v);
if (history && user) {
auto when = requestingDifference() ? 0 : unixtime();
App::histories().regSendAction(history, user, d.vaction, when);
@ -4841,7 +4849,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
App::markPeerUpdated(user);
Notify::peerUpdatedDelayed(user, Notify::PeerUpdate::Flag::UserOnlineChanged);
}
if (d.vuser_id.v == MTP::authedId()) {
if (d.vuser_id.v == AuthSession::CurrentUserId()) {
if (d.vstatus.type() == mtpc_userStatusOffline || d.vstatus.type() == mtpc_userStatusEmpty) {
updateOnline(true);
if (d.vstatus.type() == mtpc_userStatusOffline) {

View File

@ -51,6 +51,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "window/themes/window_theme_warning.h"
#include "window/window_main_menu.h"
#include "core/task_queue.h"
#include "auth_session.h"
ConnectingWidget::ConnectingWidget(QWidget *parent, const QString &text, const QString &reconnect) : TWidget(parent)
, _reconnect(this, QString()) {
@ -572,7 +573,7 @@ bool MainWindow::doWeReadServerHistory() {
}
void MainWindow::checkHistoryActivation() {
if (_main && MTP::authedId() && doWeReadServerHistory()) {
if (_main && AuthSession::Current() && doWeReadServerHistory()) {
_main->markActiveHistoryAsRead();
}
}
@ -853,7 +854,7 @@ void MainWindow::closeEvent(QCloseEvent *e) {
App::quit();
} else {
e->ignore();
if (!MTP::authedId() || !Ui::hideWindowNoQuit()) {
if (!AuthSession::Current() || !Ui::hideWindowNoQuit()) {
App::quit();
}
}

View File

@ -196,14 +196,14 @@ void DcOptions::constructFromSerialized(const QByteArray &serialized) {
auto readonly = serialized;
QBuffer buffer(&readonly);
if (!buffer.open(QIODevice::ReadOnly)) {
LOG(("MTP Error: Can't open data for DcOptions::setFromSerialized()"));
LOG(("MTP Error: Can't open data for DcOptions::constructFromSerialized()"));
return;
}
QDataStream stream(&buffer);
qint32 count = 0;
stream >> count;
if (stream.status() != QDataStream::Ok) {
LOG(("MTP Error: Bad data for DcOptions::setFromSerialized()"));
LOG(("MTP Error: Bad data for DcOptions::constructFromSerialized()"));
return;
}
@ -216,7 +216,7 @@ void DcOptions::constructFromSerialized(const QByteArray &serialized) {
stream.readRawData(&ip[0], ipSize);
if (stream.status() != QDataStream::Ok) {
LOG(("MTP Error: Bad data inside DcOptions::setFromSerialized()"));
LOG(("MTP Error: Bad data inside DcOptions::constructFromSerialized()"));
return;
}

View File

@ -34,7 +34,6 @@ DcenterMap gDCs;
bool configLoadedOnce = false;
bool mainDCChanged = false;
int32 _mainDC = 2;
int32 userId = 0;
typedef QMap<int32, AuthKeyPtr> _KeysMapForWrite;
_KeysMapForWrite _keysMapForWrite;
@ -44,16 +43,6 @@ constexpr auto kEnumerateDcTimeout = 8000; // 8 seconds timeout for help_getConf
} // namespace
int32 authed() {
return userId;
}
void authed(int32 uid) {
if (userId != uid) {
userId = uid;
}
}
DcenterMap &DCMap() {
return gDCs;
}

View File

@ -95,9 +95,6 @@ int32 mainDC();
void logoutOtherDCs();
void setDC(int32 dc, bool firstOnly = false);
int32 authed();
void authed(int32 uid);
AuthKeysMap getAuthKeys();
void setAuthKey(int32 dc, AuthKeyPtr key);

View File

@ -19,10 +19,10 @@ Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "stdafx.h"
#include "mtproto/facade.h"
#include "localstorage.h"
#include "auth_session.h"
namespace MTP {
@ -76,6 +76,10 @@ namespace {
MTPSessionResetHandler sessionResetHandler = 0;
internal::GlobalSlotCarrier *_globalSlotCarrier = 0;
bool hasAuthorization() {
return (AuthSession::Current() != nullptr);
}
void importDone(const MTPauth_Authorization &result, mtpRequestId req) {
QMutexLocker locker1(&requestByDCLock);
@ -83,7 +87,7 @@ namespace {
if (i == requestsByDC.end()) {
LOG(("MTP Error: auth import request not found in requestsByDC, requestId: %1").arg(req));
RPCError error(internal::rpcClientError("AUTH_IMPORT_FAIL", QString("did not find import request in requestsByDC, request %1").arg(req)));
if (globalHandler.onFail && authedId()) (*globalHandler.onFail)(req, error); // auth failed in main dc
if (globalHandler.onFail && hasAuthorization()) (*globalHandler.onFail)(req, error); // auth failed in main dc
return;
}
DcId newdc = bareDcId(i.value());
@ -127,7 +131,7 @@ namespace {
bool importFail(const RPCError &error, mtpRequestId req) {
if (isDefaultHandledError(error)) return false;
if (globalHandler.onFail && authedId()) (*globalHandler.onFail)(req, error); // auth import failed
if (globalHandler.onFail && hasAuthorization()) (*globalHandler.onFail)(req, error); // auth import failed
return true;
}
@ -136,7 +140,7 @@ namespace {
if (i == authExportRequests.cend()) {
LOG(("MTP Error: auth export request target dcWithShift not found, requestId: %1").arg(req));
RPCError error(internal::rpcClientError("AUTH_IMPORT_FAIL", QString("did not find target dcWithShift, request %1").arg(req)));
if (globalHandler.onFail && authedId()) (*globalHandler.onFail)(req, error); // auth failed in main dc
if (globalHandler.onFail && hasAuthorization()) (*globalHandler.onFail)(req, error); // auth failed in main dc
return;
}
@ -152,7 +156,7 @@ namespace {
if (i != authExportRequests.cend()) {
authWaiters[bareDcId(i.value())].clear();
}
if (globalHandler.onFail && authedId()) (*globalHandler.onFail)(req, error); // auth failed in main dc
if (globalHandler.onFail && hasAuthorization()) (*globalHandler.onFail)(req, error); // auth failed in main dc
return true;
}
@ -181,7 +185,7 @@ namespace {
DEBUG_LOG(("MTP Info: changing request %1 from dcWithShift%2 to dc%3").arg(requestId).arg(dcWithShift).arg(newdcWithShift));
if (dcWithShift < 0) { // newdc shift = 0
if (false && authedId() && !authExportRequests.contains(requestId)) { // migrate not supported at this moment
if (false && hasAuthorization() && !authExportRequests.contains(requestId)) { // migrate not supported at this moment
DEBUG_LOG(("MTP Info: importing auth to dc %1").arg(newdcWithShift));
DCAuthWaiters &waiters(authWaiters[newdcWithShift]);
if (!waiters.size()) {
@ -249,7 +253,7 @@ namespace {
}
}
int32 newdc = bareDcId(qAbs(dcWithShift));
if (!newdc || newdc == internal::mainDC() || !authedId()) {
if (!newdc || newdc == internal::mainDC() || !hasAuthorization()) {
if (!badGuestDC && globalHandler.onFail) (*globalHandler.onFail)(requestId, error); // auth failed in main dc
return false;
}
@ -698,10 +702,9 @@ void restart(int32 dcMask) {
}
}
void configure(int32 dc, int32 user) {
void configure(int32 dc) {
if (_started) return;
internal::setDC(dc);
internal::authed(user);
}
void setdc(int32 dc, bool fromZeroOnly) {
@ -849,14 +852,6 @@ void finish() {
_started = false;
}
void setAuthedId(int32 uid) {
internal::authed(uid);
}
int32 authedId() {
return internal::authed();
}
void logoutKeys(RPCDoneHandlerPtr onDone, RPCFailHandlerPtr onFail) {
mtpRequestId req = MTP::send(MTPauth_LogOut(), onDone, onFail);
internal::logoutOtherDCs();

View File

@ -164,7 +164,7 @@ private:
};
void configure(int32 dc, int32 user);
void configure(int32 dc);
void setdc(int32 dc, bool fromZeroOnly = false);
int32 maindc();
@ -207,8 +207,6 @@ int32 state(mtpRequestId req); // < 0 means waiting for such count of ms
void finish();
void setAuthedId(int32 uid);
int32 authedId();
void logoutKeys(RPCDoneHandlerPtr onDone, RPCFailHandlerPtr onFail);
void setGlobalDoneHandler(RPCDoneHandlerPtr handler);

View File

@ -30,6 +30,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "ui/widgets/input_fields.h"
#include "styles/style_boxes.h"
#include "window/window_slide_animation.h"
#include "auth_session.h"
PasscodeWidget::PasscodeWidget(QWidget *parent) : TWidget(parent)
, _passcode(this, st::passcodeInput, lang(lng_passcode_ph))
@ -72,7 +73,7 @@ void PasscodeWidget::onSubmit() {
cSetPasscodeBadTries(0);
MTP::start();
if (MTP::authedId()) {
if (AuthSession::Current()) {
App::wnd()->setupMain();
} else {
App::wnd()->setupIntro();

View File

@ -29,6 +29,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "mainwidget.h"
#include "observer_peer.h"
#include "apiwrap.h"
#include "auth_session.h"
#include "lang.h"
namespace Profile {
@ -158,7 +159,7 @@ void ActionsWidget::refreshVisibility() {
QString ActionsWidget::getBlockButtonText() const {
auto user = peer()->asUser();
if (!user || (user->id == peerFromUser(MTP::authedId()))) return QString();
if (!user || (user->id == AuthSession::CurrentUserPeerId())) return QString();
if (user->blockStatus() == UserData::BlockStatus::Unknown) return QString();
if (user->isBlocked()) {

View File

@ -28,6 +28,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "mainwidget.h"
#include "apiwrap.h"
#include "observer_peer.h"
#include "auth_session.h"
#include "lang.h"
namespace Profile {
@ -402,7 +403,7 @@ void GroupMembersWidget::setItemFlags(Item *item, ChatData *chat) {
auto isCreator = (peerFromUser(chat->creator) == item->peer->id);
auto isAdmin = chat->admins.contains(user);
item->hasAdminStar = isCreator || isAdmin;
if (item->peer->id == peerFromUser(MTP::authedId())) {
if (item->peer->id == AuthSession::CurrentUserPeerId()) {
item->hasRemoveLink = false;
} else if (chat->amCreator() || (chat->amAdmin() && !item->hasAdminStar)) {
item->hasRemoveLink = true;
@ -468,7 +469,7 @@ bool GroupMembersWidget::addUsersToEnd(ChannelData *megagroup) {
}
void GroupMembersWidget::setItemFlags(Item *item, ChannelData *megagroup) {
auto amCreatorOrAdmin = (peerToUser(item->peer->id) == MTP::authedId()) && (megagroup->amCreator() || megagroup->amEditor());
auto amCreatorOrAdmin = (item->peer->id == AuthSession::CurrentUserPeerId()) && (megagroup->amCreator() || megagroup->amEditor());
auto isAdmin = megagroup->mgInfo->lastAdmins.contains(getMember(item)->user());
item->hasAdminStar = amCreatorOrAdmin || isAdmin;
if (item->peer->isSelf()) {

View File

@ -36,11 +36,12 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "history/history_media_types.h"
#include "styles/style_history.h"
#include "window/themes/window_theme.h"
#include "auth_session.h"
namespace {
int peerColorIndex(const PeerId &peer) {
auto myId = MTP::authedId();
auto myId = AuthSession::CurrentUserId();
auto peerId = peerToBareInt(peer);
auto both = (QByteArray::number(peerId) + QByteArray::number(myId)).mid(0, 15);
uchar md5[16];

View File

@ -101,18 +101,17 @@ inline MTPpeer peerToMTP(const PeerId &id) {
return MTP_peerUser(MTP_int(0));
}
inline PeerId peerFromMessage(const MTPmessage &msg) {
PeerId from_id = 0, to_id = 0;
auto compute = [](auto &message) {
auto from_id = message.has_from_id() ? peerFromUser(message.vfrom_id) : 0;
auto to_id = peerFromMTP(message.vto_id);
auto out = message.is_out();
return (out || !peerIsUser(to_id)) ? to_id : from_id;
};
switch (msg.type()) {
case mtpc_message:
from_id = msg.c_message().has_from_id() ? peerFromUser(msg.c_message().vfrom_id) : 0;
to_id = peerFromMTP(msg.c_message().vto_id);
break;
case mtpc_messageService:
from_id = msg.c_messageService().has_from_id() ? peerFromUser(msg.c_messageService().vfrom_id) : 0;
to_id = peerFromMTP(msg.c_messageService().vto_id);
break;
case mtpc_message: return compute(msg.c_message());
case mtpc_messageService: return compute(msg.c_messageService());
}
return (from_id && peerToUser(to_id) == MTP::authedId()) ? from_id : to_id;
return 0;
}
inline MTPDmessage::Flags flagsFromMessage(const MTPmessage &msg) {
switch (msg.type()) {

View File

@ -21,6 +21,8 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include "stdafx.h"
#include "ui/text/text_entity.h"
#include "auth_session.h"
namespace {
const QRegularExpression _reDomain(QString::fromUtf8("(?<![\\w\\$\\-\\_%=\\.])(?:([a-zA-Z]+)://)?((?:[A-Za-z" "\xd0\x90-\xd0\xaf" "\xd0\xb0-\xd1\x8f" "\xd1\x91\xd0\x81" "0-9\\-\\_]+\\.){1,10}([A-Za-z" "\xd1\x80\xd1\x84" "\\-\\d]{2,22})(\\:\\d+)?)"), QRegularExpression::UseUnicodePropertiesOption);
@ -1376,7 +1378,7 @@ EntitiesInText entitiesFromMTP(const QVector<MTPMessageEntity> &entities) {
const auto &d(entity.c_inputMessageEntityMentionName());
auto data = ([&d]() -> QString {
if (d.vuser_id.type() == mtpc_inputUserSelf) {
return QString::number(MTP::authedId());
return QString::number(AuthSession::CurrentUserId());
} else if (d.vuser_id.type() == mtpc_inputUser) {
const auto &user(d.vuser_id.c_inputUser());
return QString::number(user.vuser_id.v) + '.' + QString::number(user.vaccess_hash.v);
@ -1422,7 +1424,7 @@ MTPVector<MTPMessageEntity> linksToMTP(const EntitiesInText &links, bool sending
UserId userId = 0;
uint64 accessHash = 0;
if (mentionNameToFields(data, &userId, &accessHash)) {
if (userId == MTP::authedId()) {
if (userId == AuthSession::CurrentUserId()) {
return MTP_inputUserSelf();
}
return MTP_inputUser(MTP_int(userId), MTP_long(accessHash));

View File

@ -107,6 +107,8 @@
'<(src_loc)/app.h',
'<(src_loc)/application.cpp',
'<(src_loc)/application.h',
'<(src_loc)/auth_session.cpp',
'<(src_loc)/auth_session.h',
'<(src_loc)/autoupdater.cpp',
'<(src_loc)/autoupdater.h',
'<(src_loc)/config.h',