Remove Session::Exists() global access point.

This commit is contained in:
John Preston 2020-06-10 17:24:41 +04:00
parent 5f8d22f1f2
commit 598fb67cdf
19 changed files with 119 additions and 133 deletions

View File

@ -557,7 +557,7 @@ void EmojiKeywords::refresh() {
}
std::vector<QString> EmojiKeywords::languages() {
if (!Main::Session::Exists()) {
if (!_api) {
return {};
}
refreshInputLanguages();

View File

@ -120,9 +120,7 @@ Application::Application(not_null<Launcher*> launcher)
_mediaView->clearData();
}
if (session && !UpdaterDisabled()) {
if (const auto mtp = activeAccount().mtp()) {
UpdateChecker().setMtproto(mtp, session->userId());
}
UpdateChecker().setMtproto(session);
}
}, _lifetime);
@ -580,6 +578,16 @@ bool Application::unreadBadgeMuted() const {
: false;
}
bool Application::offerLangPackSwitch() const {
// #TODO multi we offer only if we were upgraded from an old authed app.
return activeAccount().sessionExists();
}
bool Application::canApplyLangPackWithoutRestart() const {
// #TODO multi we can't if at least one account is authorized.
return !activeAccount().sessionExists();
}
void Application::setInternalLinkDomain(const QString &domain) const {
// This domain should start with 'http[s]://' and end with '/'.
// Like 'https://telegram.me/' or 'https://t.me/'.

View File

@ -85,23 +85,23 @@ public:
Application &operator=(const Application &other) = delete;
~Application();
not_null<Launcher*> launcher() const {
[[nodiscard]] not_null<Launcher*> launcher() const {
return _launcher;
}
void run();
Ui::Animations::Manager &animationManager() const {
[[nodiscard]] Ui::Animations::Manager &animationManager() const {
return *_animationsManager;
}
// Windows interface.
Window::Controller *activeWindow() const;
[[nodiscard]] Window::Controller *activeWindow() const;
bool closeActiveWindow();
bool minimizeActiveWindow();
QWidget *getFileDialogParent();
[[nodiscard]] QWidget *getFileDialogParent();
void notifyFileDialogShown(bool shown);
QWidget *getModalParent();
[[nodiscard]] QWidget *getModalParent();
// Media view interface.
void checkMediaViewActivation();
@ -113,13 +113,13 @@ public:
void showTheme(
not_null<DocumentData*> document,
const Data::CloudTheme &cloud);
PeerData *ui_getPeerForMouseAction();
[[nodiscard]] PeerData *ui_getPeerForMouseAction();
QPoint getPointForCallPanelCenter() const;
QImage logo() const {
[[nodiscard]] QPoint getPointForCallPanelCenter() const;
[[nodiscard]] QImage logo() const {
return _logo;
}
QImage logoNoMargin() const {
[[nodiscard]] QImage logoNoMargin() const {
return _logoNoMargin;
}
@ -129,7 +129,7 @@ public:
void saveSettingsDelayed(crl::time delay = kDefaultSaveDelay);
// Dc options and proxy.
not_null<MTP::DcOptions*> dcOptions() {
[[nodiscard]] not_null<MTP::DcOptions*> dcOptions() {
return _dcOptions.get();
}
struct ProxyChange {
@ -155,28 +155,30 @@ public:
// Main::Session component.
[[nodiscard]] int unreadBadge() const;
bool unreadBadgeMuted() const;
[[nodiscard]] bool unreadBadgeMuted() const;
// Media component.
Media::Audio::Instance &audio() {
[[nodiscard]] Media::Audio::Instance &audio() {
return *_audio;
}
// Langpack and emoji keywords.
Lang::Instance &langpack() {
[[nodiscard]] Lang::Instance &langpack() {
return *_langpack;
}
Lang::CloudManager *langCloudManager() {
[[nodiscard]] Lang::CloudManager *langCloudManager() {
return _langCloudManager.get();
}
ChatHelpers::EmojiKeywords &emojiKeywords() {
[[nodiscard]] bool offerLangPackSwitch() const;
[[nodiscard]] bool canApplyLangPackWithoutRestart() const;
[[nodiscard]] ChatHelpers::EmojiKeywords &emojiKeywords() {
return *_emojiKeywords;
}
// Internal links.
void setInternalLinkDomain(const QString &domain) const;
QString createInternalLink(const QString &query) const;
QString createInternalLinkFull(const QString &query) const;
[[nodiscard]] QString createInternalLink(const QString &query) const;
[[nodiscard]] QString createInternalLinkFull(const QString &query) const;
void checkStartUrl();
bool openLocalUrl(const QString &url, QVariant context);
bool openInternalUrl(const QString &url, QVariant context);

View File

@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/click_handler_types.h"
#include "mainwindow.h"
#include "main/main_account.h"
#include "main/main_session.h"
#include "info/info_memento.h"
#include "info/settings/info_settings_widget.h"
#include "window/window_session_controller.h"
@ -172,7 +173,7 @@ private:
class MtpChecker : public Checker {
public:
MtpChecker(QPointer<MTP::Instance> instance, int32 userId, bool testing);
MtpChecker(base::weak_ptr<Main::Session> session, bool testing);
void start() override;
@ -879,16 +880,14 @@ void HttpLoaderActor::partFailed(QNetworkReply::NetworkError e) {
}
MtpChecker::MtpChecker(
QPointer<MTP::Instance> instance,
int32 userId,
base::weak_ptr<Main::Session> session,
bool testing)
: Checker(testing)
, _mtp(instance)
, _mtpUserId(userId) {
, _mtp(session) {
}
void MtpChecker::start() {
if (!_mtp.valid() || !_mtpUserId) {
if (!_mtp.valid()) {
LOG(("Update Info: MTP is unavailable."));
crl::on_main(this, [=] { fail(); });
return;
@ -896,7 +895,7 @@ void MtpChecker::start() {
const auto updaterVersion = Platform::AutoUpdateVersion();
const auto feed = "tdhbcfeed"
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
MTP::ResolveChannel(&_mtp, _mtpUserId, feed, [=](
MTP::ResolveChannel(&_mtp, feed, [=](
const MTPInputChannel &channel) {
_mtp.send(
MTPmessages_GetHistory(
@ -931,12 +930,7 @@ void MtpChecker::gotMessage(const MTPmessages_Messages &result) {
fail();
}
};
MTP::StartDedicatedLoader(
&_mtp,
_mtpUserId,
*location,
UpdatesFolder(),
ready);
MTP::StartDedicatedLoader(&_mtp, *location, UpdatesFolder(), ready);
}
auto MtpChecker::parseMessage(const MTPmessages_Messages &result) const
@ -1044,7 +1038,7 @@ public:
int already() const;
int size() const;
void setMtproto(const QPointer<MTP::Instance> &mtproto, int32 userId);
void setMtproto(base::weak_ptr<Main::Session> session);
~Updater();
@ -1089,8 +1083,7 @@ private:
Implementation _mtpImplementation;
std::shared_ptr<Loader> _activeLoader;
bool _usingMtprotoLoader = (cAlphaVersion() != 0);
QPointer<MTP::Instance> _mtproto;
int32 _mtprotoUserId = 0;
base::weak_ptr<Main::Session> _session;
rpl::lifetime _lifetime;
@ -1238,7 +1231,7 @@ void Updater::start(bool forceWait) {
std::make_unique<HttpChecker>(_testing));
startImplementation(
&_mtpImplementation,
std::make_unique<MtpChecker>(_mtproto, _mtprotoUserId, _testing));
std::make_unique<MtpChecker>(_session, _testing));
_checking.fire({});
} else {
@ -1301,11 +1294,8 @@ void Updater::test() {
start(false);
}
void Updater::setMtproto(
const QPointer<MTP::Instance> &mtproto,
int32 userId) {
_mtproto = mtproto;
_mtprotoUserId = userId;
void Updater::setMtproto(base::weak_ptr<Main::Session> session) {
_session = session;
}
void Updater::handleTimeout() {
@ -1405,9 +1395,7 @@ UpdateChecker::UpdateChecker()
if (IsAppLaunched()) {
const auto &account = Core::App().activeAccount();
if (account.sessionExists()) {
if (const auto mtproto = account.mtp()) {
_updater->setMtproto(mtproto, account.session().userId());
}
_updater->setMtproto(&account.session());
}
}
}
@ -1441,10 +1429,8 @@ void UpdateChecker::test() {
_updater->test();
}
void UpdateChecker::setMtproto(
const QPointer<MTP::Instance> &mtproto,
int32 userId) {
_updater->setMtproto(mtproto, userId);
void UpdateChecker::setMtproto(base::weak_ptr<Main::Session> session) {
_updater->setMtproto(session);
}
void UpdateChecker::stop() {

View File

@ -9,9 +9,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/dedicated_file_loader.h"
namespace MTP {
class Instance;
} // namespace MTP
namespace Main {
class Session;
} // namespace Main
namespace Core {
@ -41,7 +41,7 @@ public:
void stop();
void test();
void setMtproto(const QPointer<MTP::Instance> &mtproto, int32 userId);
void setMtproto(base::weak_ptr<Main::Session> session);
State state() const;
int already() const;

View File

@ -249,7 +249,7 @@ void CloudManager::setSuggestedLanguage(const QString &langCode) {
_languageWasSuggested = true;
_firstLanguageSuggestion.notify();
if (Main::Session::Exists()
if (Core::App().offerLegacyLangPackSwitch()
&& _langpack.id().isEmpty()
&& !_suggestedLanguage.isEmpty()) {
_offerSwitchToId = _suggestedLanguage;
@ -386,9 +386,7 @@ bool CloudManager::canApplyWithoutRestart(const QString &id) const {
if (id == qstr("#TEST_X") || id == qstr("#TEST_0")) {
return true;
}
// We don't support instant language switch if the auth session exists :(
return !Main::Session::Exists();
return Core::App().canApplyLangPackWithoutRestart();
}
void CloudManager::resetToDefault() {

View File

@ -126,12 +126,10 @@ void Account::createSession(
Expects(_sessionValue.current() == nullptr);
_session = std::make_unique<Session>(this, user, std::move(settings));
if (!serialized.isEmpty()) {
// For now it depends on Auth() which depends on _sessionValue.
local().readSelf(serialized, streamVersion);
local().readSelf(_session.get(), serialized, streamVersion);
}
_sessionValue = _session.get();
}
@ -154,13 +152,7 @@ bool Account::sessionExists() const {
return (_sessionValue.current() != nullptr);
}
Session &Account::session() {
Expects(sessionExists());
return *_sessionValue.current();
}
const Session &Account::session() const {
Session &Account::session() const {
Expects(sessionExists());
return *_sessionValue.current();

View File

@ -48,8 +48,7 @@ public:
}
[[nodiscard]] bool sessionExists() const;
[[nodiscard]] Session &session();
[[nodiscard]] const Session &session() const;
[[nodiscard]] Session &session() const;
[[nodiscard]] rpl::producer<Session*> sessionValue() const;
[[nodiscard]] rpl::producer<Session*> sessionChanges() const;

View File

@ -117,11 +117,6 @@ Storage::Account &Session::local() const {
return _account->local();
}
bool Session::Exists() {
return Core::IsAppLaunched()
&& Core::App().activeAccount().sessionExists();
}
base::Observable<void> &Session::downloaderTaskFinished() {
return downloader().taskFinished();
}

View File

@ -71,8 +71,6 @@ public:
Session(const Session &other) = delete;
Session &operator=(const Session &other) = delete;
[[nodiscard]] static bool Exists();
[[nodiscard]] Main::Account &account() const;
[[nodiscard]] Storage::Account &local() const;

View File

@ -8,8 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/dedicated_file_loader.h"
#include "mtproto/facade.h"
#include "main/main_session.h"
#include "main/main_account.h" // Account::sessionChanges.
#include "main/main_session.h" // Session::account.
#include "core/application.h"
#include "base/call_delayed.h"
@ -82,17 +82,19 @@ std::optional<DedicatedLoader::File> ParseFile(
} // namespace
WeakInstance::WeakInstance(QPointer<MTP::Instance> instance)
: _instance(instance) {
WeakInstance::WeakInstance(base::weak_ptr<Main::Session> session)
: _session(session)
, _instance(_session ? _session->account().mtp() : nullptr) {
if (!valid()) {
return;
}
connect(_instance, &QObject::destroyed, this, [=] {
_instance = nullptr;
_session = nullptr;
die();
});
Core::App().activeAccount().sessionChanges(
_session->account().sessionChanges(
) | rpl::filter([](Main::Session *session) {
return !session;
}) | rpl::start_with_next([=] {
@ -100,19 +102,22 @@ WeakInstance::WeakInstance(QPointer<MTP::Instance> instance)
}, _lifetime);
}
bool WeakInstance::valid() const {
return (_instance != nullptr) && Main::Session::Exists();
base::weak_ptr<Main::Session> WeakInstance::session() const {
return _session;
}
QPointer<MTP::Instance> WeakInstance::instance() const {
bool WeakInstance::valid() const {
return (_session != nullptr);
}
Instance *WeakInstance::instance() const {
return _instance;
}
void WeakInstance::die() {
const auto instance = _instance.data();
for (const auto &[requestId, fail] : base::take(_requests)) {
if (instance) {
instance->cancel(requestId);
if (_instance) {
_instance->cancel(requestId);
}
fail(RPCError::Local(
"UNAVAILABLE",
@ -138,9 +143,9 @@ void WeakInstance::reportUnavailable(
}
WeakInstance::~WeakInstance() {
if (const auto instance = _instance.data()) {
if (_instance) {
for (const auto &[requestId, fail] : base::take(_requests)) {
instance->cancel(requestId);
_instance->cancel(requestId);
}
}
}
@ -280,14 +285,14 @@ rpl::lifetime &AbstractDedicatedLoader::lifetime() {
}
DedicatedLoader::DedicatedLoader(
QPointer<MTP::Instance> instance,
base::weak_ptr<Main::Session> session,
const QString &folder,
const File &file)
: AbstractDedicatedLoader(folder + '/' + file.name, kChunkSize)
, _size(file.size)
, _dcId(file.dcId)
, _location(file.location)
, _mtp(instance) {
, _mtp(session) {
Expects(_size > 0);
}
@ -365,7 +370,6 @@ Fn<void(const RPCError &)> DedicatedLoader::failHandler() {
void ResolveChannel(
not_null<MTP::WeakInstance*> mtp,
int32 userId,
const QString &username,
Fn<void(const MTPInputChannel &channel)> done,
Fn<void()> fail) {
@ -374,20 +378,21 @@ void ResolveChannel(
).arg(username));
fail();
};
if (!userId) {
const auto session = mtp->session();
if (!mtp->valid()) {
failed();
return;
}
struct ResolveResult {
int32 userId = 0;
base::weak_ptr<Main::Session> session;
MTPInputChannel channel;
};
static std::map<QString, ResolveResult> ResolveCache;
const auto i = ResolveCache.find(username);
if (i != end(ResolveCache)) {
if (i->second.userId == userId) {
if (i->second.session.get() == session.get()) {
done(i->second.channel);
return;
}
@ -400,7 +405,7 @@ void ResolveChannel(
if (const auto channel = ExtractChannel(result)) {
ResolveCache.emplace(
username,
ResolveResult { userId, *channel });
ResolveResult { session, *channel });
done(*channel);
} else {
failed();
@ -430,7 +435,6 @@ std::optional<MTPMessage> GetMessagesElement(
void StartDedicatedLoader(
not_null<MTP::WeakInstance*> mtp,
int32 userId,
const DedicatedLoader::Location &location,
const QString &folder,
Fn<void(std::unique_ptr<DedicatedLoader>)> ready) {
@ -438,7 +442,7 @@ void StartDedicatedLoader(
const auto file = ParseFile(result);
ready(file
? std::make_unique<MTP::DedicatedLoader>(
mtp->instance(),
mtp->session(),
folder,
*file)
: nullptr);
@ -450,7 +454,7 @@ void StartDedicatedLoader(
};
const auto [username, postId] = location;
ResolveChannel(mtp, userId, username, [=, postId = postId](
ResolveChannel(mtp, username, [=, postId = postId](
const MTPInputChannel &channel) {
mtp->send(
MTPchannels_GetMessages(

View File

@ -9,11 +9,15 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/mtp_instance.h"
namespace Main {
class Session;
} // namespace Main
namespace MTP {
class WeakInstance : private QObject, private base::Subscriber {
public:
WeakInstance(QPointer<Instance> instance);
explicit WeakInstance(base::weak_ptr<Main::Session> session);
template <typename T>
void send(
@ -22,8 +26,9 @@ public:
Fn<void(const RPCError &error)> fail,
ShiftedDcId dcId = 0);
bool valid() const;
QPointer<Instance> instance() const;
[[nodiscard]] base::weak_ptr<Main::Session> session() const;
[[nodiscard]] bool valid() const;
[[nodiscard]] Instance *instance() const;
~WeakInstance();
@ -32,7 +37,8 @@ private:
bool removeRequest(mtpRequestId requestId);
void reportUnavailable(Fn<void(const RPCError &error)> callback);
QPointer<Instance> _instance;
base::weak_ptr<Main::Session> _session;
Instance *_instance = nullptr;
std::map<mtpRequestId, Fn<void(const RPCError &)>> _requests;
rpl::lifetime _lifetime;
@ -115,7 +121,7 @@ public:
};
DedicatedLoader(
QPointer<Instance> instance,
base::weak_ptr<Main::Session> session,
const QString &folder,
const File &file);
@ -143,7 +149,6 @@ private:
void ResolveChannel(
not_null<MTP::WeakInstance*> mtp,
int32 userId,
const QString &username,
Fn<void(const MTPInputChannel &channel)> done,
Fn<void()> fail);
@ -153,7 +158,6 @@ std::optional<MTPMessage> GetMessagesElement(
void StartDedicatedLoader(
not_null<MTP::WeakInstance*> mtp,
int32 userId,
const DedicatedLoader::Location &location,
const QString &folder,
Fn<void(std::unique_ptr<DedicatedLoader>)> ready);

View File

@ -16,7 +16,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/sender.h"
#include "storage/localstorage.h"
#include "calls/calls_instance.h"
#include "main/main_session.h" // Session::Exists.
#include "main/main_account.h" // Account::configUpdated.
#include "apiwrap.h"
#include "core/application.h"
@ -164,7 +163,6 @@ public:
[[nodiscard]] rpl::lifetime &lifetime();
private:
bool hasAuthorization();
void importDone(const MTPauth_Authorization &result, mtpRequestId requestId);
bool importFail(const RPCError &error, mtpRequestId requestId);
void exportDone(const MTPauth_ExportedAuthorization &result, mtpRequestId requestId);
@ -1106,10 +1104,6 @@ bool Instance::Private::rpcErrorOccured(mtpRequestId requestId, const RPCFailHan
return true;
}
bool Instance::Private::hasAuthorization() {
return Main::Session::Exists();
}
void Instance::Private::importDone(const MTPauth_Authorization &result, mtpRequestId requestId) {
const auto shiftedDcId = queryRequestByDc(requestId);
if (!shiftedDcId) {
@ -1230,7 +1224,7 @@ bool Instance::Private::onErrorDefault(mtpRequestId requestId, const RPCError &e
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 && hasAuthorization() && _authExportRequests.find(requestId) == _authExportRequests.cend()) {
if (false/* && hasAuthorization() && _authExportRequests.find(requestId) == _authExportRequests.cend()*/) {
//
// migrate not supported at this moment
// this was not tested even once
@ -1305,7 +1299,7 @@ bool Instance::Private::onErrorDefault(mtpRequestId requestId, const RPCError &e
LOG(("MTP Error: unauthorized request without dc info, requestId %1").arg(requestId));
}
auto newdc = BareDcId(qAbs(dcWithShift));
if (!newdc || newdc == mainDcId() || !hasAuthorization()) {
if (!newdc || newdc == mainDcId()) {
if (!badGuestDc && _globalHandler.onFail) {
(*_globalHandler.onFail)(requestId, error); // auth failed in main dc
}

View File

@ -163,18 +163,19 @@ auto GenerateCodes() {
return;
}
const auto weak = base::make_weak(&window->session());
FileDialog::GetOpenPath(Core::App().getFileDialogParent(), "Open audio file", audioFilters, crl::guard(&window->session(), [=](const FileDialog::OpenResult &result) {
if (Main::Session::Exists() && !result.paths.isEmpty()) {
if (weak && !result.paths.isEmpty()) {
auto track = Media::Audio::Current().createTrack();
track->fillFromFile(result.paths.front());
if (track->failed()) {
Ui::show(Box<InformBox>(
"Could not audio :( Errors in 'log.txt'."));
} else {
window->session().settings().setSoundOverride(
weak->settings().setSoundOverride(
key,
result.paths.front());
window->session().saveSettingsDelayed();
weak->saveSettingsDelayed();
}
}
}));

View File

@ -216,7 +216,10 @@ PeerData *readPeer(
return nullptr;
}
const auto loaded = session->data().peerLoaded(peerId);
const auto selfId = session->userPeerId();
const auto loaded = (peerId == selfId)
? session->user().get()
: session->data().peerLoaded(peerId);
const auto result = loaded ? loaded : session->data().peer(peerId).get();
if (!loaded) {
result->loadedStatus = PeerData::FullLoaded;
@ -237,7 +240,7 @@ PeerData *readPeer(
userpicAccessHash = access;
const auto showPhone = !user->isServiceUser()
&& (user->id != session->userPeerId())
&& (user->id != selfId)
&& (contact <= 0);
const auto pname = (showPhone && !phone.isEmpty())
? App::formatPhone(phone)
@ -256,7 +259,7 @@ PeerData *readPeer(
user->botInfo->inlinePlaceholder = inlinePlaceholder;
}
if (user->id == session->userPeerId()) {
if (user->id == selfId) {
user->input = MTP_inputPeerSelf();
user->inputUser = MTP_inputUserSelf();
} else {

View File

@ -2444,14 +2444,17 @@ void Account::writeSelf() {
writeMapDelayed();
}
void Account::readSelf(const QByteArray &serialized, int32 streamVersion) {
void Account::readSelf(
not_null<Main::Session*> session,
const QByteArray &serialized,
int32 streamVersion) {
QDataStream stream(serialized);
const auto user = _owner->session().user();
const auto user = session->user();
const auto wasLoadedStatus = std::exchange(
user->loadedStatus,
PeerData::NotLoaded);
const auto self = Serialize::readPeer(
&_owner->session(),
session,
streamVersion,
stream);
if (!self || !self->isSelf() || self != user) {

View File

@ -120,7 +120,13 @@ public:
[[nodiscard]] Export::Settings readExportSettings();
void writeSelf();
void readSelf(const QByteArray &serialized, int32 streamVersion);
// Read self is special, it can't get session from account, because
// it is not really there yet - it is still being constructed.
void readSelf(
not_null<Main::Session*> session,
const QByteArray& serialized,
int32 streamVersion);
void markBotTrusted(not_null<UserData*> bot);
[[nodiscard]] bool isBotTrusted(not_null<UserData*> bot);

View File

@ -104,8 +104,7 @@ BlobLoader::BlobLoader(
, _folder(folder)
, _id(id)
, _state(Loading{ 0, size })
, _mtproto(session->account().mtp())
, _mtprotoUserId(session->userId()) {
, _mtproto(session.get()) {
const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) {
if (loader) {
setImplementation(std::move(loader));
@ -113,12 +112,7 @@ BlobLoader::BlobLoader(
fail();
}
};
MTP::StartDedicatedLoader(
&_mtproto,
_mtprotoUserId,
location,
_folder,
ready);
MTP::StartDedicatedLoader(&_mtproto, location, _folder, ready);
}
int BlobLoader::id() const {

View File

@ -107,7 +107,6 @@ private:
rpl::variable<BlobState> _state;
MTP::WeakInstance _mtproto;
int32 _mtprotoUserId = 0;
std::unique_ptr<MTP::DedicatedLoader> _implementation;