Remove Auth() global access point.

This commit is contained in:
John Preston 2020-06-10 14:49:10 +04:00
parent 7892ba97e6
commit 5f8d22f1f2
24 changed files with 209 additions and 109 deletions

View file

@ -46,13 +46,18 @@ using QStringView = QString;
class Inner : public Ui::RpWidget { class Inner : public Ui::RpWidget {
public: public:
Inner(QWidget *parent, Dictionaries enabledDictionaries); Inner(
QWidget *parent,
not_null<Main::Session*> session,
Dictionaries enabledDictionaries);
Dictionaries enabledRows() const; Dictionaries enabledRows() const;
QueryCallback queryCallback() const; QueryCallback queryCallback() const;
private: private:
void setupContent(Dictionaries enabledDictionaries); void setupContent(
not_null<Main::Session*> session,
Dictionaries enabledDictionaries);
Dictionaries _enabledRows; Dictionaries _enabledRows;
QueryCallback _queryCallback; QueryCallback _queryCallback;
@ -96,8 +101,10 @@ auto CreateMultiSelect(QWidget *parent) {
Inner::Inner( Inner::Inner(
QWidget *parent, QWidget *parent,
Dictionaries enabledDictionaries) : RpWidget(parent) { not_null<Main::Session*> session,
setupContent(std::move(enabledDictionaries)); Dictionaries enabledDictionaries)
: RpWidget(parent) {
setupContent(session, std::move(enabledDictionaries));
} }
QueryCallback Inner::queryCallback() const { QueryCallback Inner::queryCallback() const {
@ -110,6 +117,7 @@ Dictionaries Inner::enabledRows() const {
auto AddButtonWithLoader( auto AddButtonWithLoader(
not_null<Ui::VerticalLayout*> content, not_null<Ui::VerticalLayout*> content,
not_null<Main::Session*> session,
const Spellchecker::Dict &dict, const Spellchecker::Dict &dict,
bool buttonEnabled, bool buttonEnabled,
rpl::producer<QStringView> query) { rpl::producer<QStringView> query) {
@ -288,6 +296,7 @@ auto AddButtonWithLoader(
const auto weak = Ui::MakeWeak(button); const auto weak = Ui::MakeWeak(button);
setLocalLoader(base::make_unique_q<Loader>( setLocalLoader(base::make_unique_q<Loader>(
App::main(), App::main(),
session,
id, id,
Spellchecker::GetDownloadLocation(id), Spellchecker::GetDownloadLocation(id),
Spellchecker::DictPathByLangId(id), Spellchecker::DictPathByLangId(id),
@ -336,7 +345,9 @@ auto AddButtonWithLoader(
return button; return button;
} }
void Inner::setupContent(Dictionaries enabledDictionaries) { void Inner::setupContent(
not_null<Main::Session*> session,
Dictionaries enabledDictionaries) {
const auto content = Ui::CreateChild<Ui::VerticalLayout>(this); const auto content = Ui::CreateChild<Ui::VerticalLayout>(this);
const auto queryStream = content->lifetime() const auto queryStream = content->lifetime()
@ -346,6 +357,7 @@ void Inner::setupContent(Dictionaries enabledDictionaries) {
const auto id = dict.id; const auto id = dict.id;
const auto row = AddButtonWithLoader( const auto row = AddButtonWithLoader(
content, content,
session,
dict, dict,
ranges::contains(enabledDictionaries, id), ranges::contains(enabledDictionaries, id),
queryStream->events()); queryStream->events());
@ -389,6 +401,7 @@ void ManageDictionariesBox::prepare() {
const auto inner = setInnerWidget( const auto inner = setInnerWidget(
object_ptr<Inner>( object_ptr<Inner>(
this, this,
_session,
_session->settings().dictionariesEnabled()), _session->settings().dictionariesEnabled()),
st::boxScroll, st::boxScroll,
multiSelect->height() multiSelect->height()

View file

@ -51,7 +51,7 @@ using SetState = BlobState;
class Loader final : public BlobLoader { class Loader final : public BlobLoader {
public: public:
Loader( Loader(
QObject *parent, not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,
@ -67,16 +67,18 @@ private:
class Inner : public Ui::RpWidget { class Inner : public Ui::RpWidget {
public: public:
Inner(QWidget *parent); Inner(QWidget *parent, not_null<Main::Session*> session);
private: private:
void setupContent(); void setupContent();
const not_null<Main::Session*> _session;
}; };
class Row : public Ui::RippleButton { class Row : public Ui::RippleButton {
public: public:
Row(QWidget *widget, const Set &set); Row(QWidget *widget, not_null<Main::Session*> session, const Set &set);
protected: protected:
void paintEvent(QPaintEvent *e) override; void paintEvent(QPaintEvent *e) override;
@ -98,6 +100,7 @@ private:
void radialAnimationCallback(crl::time now); void radialAnimationCallback(crl::time now);
void updateLoadingToFinished(); void updateLoadingToFinished();
const not_null<Main::Session*> _session;
int _id = 0; int _id = 0;
bool _switching = false; bool _switching = false;
rpl::variable<SetState> _state; rpl::variable<SetState> _state;
@ -160,12 +163,12 @@ bool UnpackSet(const QString &path, const QString &folder) {
Loader::Loader( Loader::Loader(
QObject *parent, not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,
int size) int size)
: BlobLoader(parent, id, location, folder, size) { : BlobLoader(nullptr, session, id, location, folder, size) {
} }
void Loader::unpack(const QString &path) { void Loader::unpack(const QString &path) {
@ -200,7 +203,9 @@ void Loader::fail() {
BlobLoader::fail(); BlobLoader::fail();
} }
Inner::Inner(QWidget *parent) : RpWidget(parent) { Inner::Inner(QWidget *parent, not_null<Main::Session*> session)
: RpWidget(parent)
, _session(session) {
setupContent(); setupContent();
} }
@ -208,15 +213,16 @@ void Inner::setupContent() {
const auto content = Ui::CreateChild<Ui::VerticalLayout>(this); const auto content = Ui::CreateChild<Ui::VerticalLayout>(this);
for (const auto &set : kSets) { for (const auto &set : kSets) {
content->add(object_ptr<Row>(content, set)); content->add(object_ptr<Row>(content, _session, set));
} }
content->resizeToWidth(st::boxWidth); content->resizeToWidth(st::boxWidth);
Ui::ResizeFitChild(this, content); Ui::ResizeFitChild(this, content);
} }
Row::Row(QWidget *widget, const Set &set) Row::Row(QWidget *widget, not_null<Main::Session*> session, const Set &set)
: RippleButton(widget, st::contactsRipple) : RippleButton(widget, st::contactsRipple)
, _session(session)
, _id(set.id) , _id(set.id)
, _state(Available{ set.size }) { , _state(Available{ set.size }) {
setupContent(set); setupContent(set);
@ -411,7 +417,7 @@ void Row::setupHandler() {
} }
void Row::load() { void Row::load() {
LoadAndSwitchTo(_id); LoadAndSwitchTo(_session, _id);
} }
void Row::setupLabels(const Set &set) { void Row::setupLabels(const Set &set) {
@ -530,11 +536,12 @@ void Row::setupAnimation() {
} // namespace } // namespace
ManageSetsBox::ManageSetsBox(QWidget*) { ManageSetsBox::ManageSetsBox(QWidget*, not_null<Main::Session*> session)
: _session(session) {
} }
void ManageSetsBox::prepare() { void ManageSetsBox::prepare() {
const auto inner = setInnerWidget(object_ptr<Inner>(this)); const auto inner = setInnerWidget(object_ptr<Inner>(this, _session));
setTitle(tr::lng_emoji_manage_sets()); setTitle(tr::lng_emoji_manage_sets());
@ -543,15 +550,13 @@ void ManageSetsBox::prepare() {
setDimensionsToContent(st::boxWidth, inner); setDimensionsToContent(st::boxWidth, inner);
} }
void LoadAndSwitchTo(int id) { void LoadAndSwitchTo(not_null<Main::Session*> session, int id) {
Expects(App::main() != nullptr);
if (!ranges::contains(kSets, id, &Set::id)) { if (!ranges::contains(kSets, id, &Set::id)) {
ClearNeedSwitchToId(); ClearNeedSwitchToId();
return; return;
} }
SetGlobalLoader(base::make_unique_q<Loader>( SetGlobalLoader(base::make_unique_q<Loader>(
App::main(), session,
id, id,
GetDownloadLocation(id), GetDownloadLocation(id),
internal::SetDataPath(id), internal::SetDataPath(id),

View file

@ -9,19 +9,25 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/abstract_box.h" #include "boxes/abstract_box.h"
namespace Main {
class Session;
} // namespace Main
namespace Ui { namespace Ui {
namespace Emoji { namespace Emoji {
class ManageSetsBox : public Ui::BoxContent { class ManageSetsBox final : public Ui::BoxContent {
public: public:
explicit ManageSetsBox(QWidget*); ManageSetsBox(QWidget*, not_null<Main::Session*> session);
protected: private:
void prepare() override; void prepare() override;
const not_null<Main::Session*> _session;
}; };
void LoadAndSwitchTo(int id); void LoadAndSwitchTo(not_null<Main::Session*> session, int id);
} // namespace Emoji } // namespace Emoji
} // namespace Ui } // namespace Ui

View file

@ -163,6 +163,7 @@ void DownloadDictionaryInBackground(
auto sharedLoader = std::make_shared<base::unique_qptr<DictLoader>>(); auto sharedLoader = std::make_shared<base::unique_qptr<DictLoader>>();
*sharedLoader = base::make_unique_q<DictLoader>( *sharedLoader = base::make_unique_q<DictLoader>(
App::main(), App::main(),
session,
id, id,
GetDownloadLocation(id), GetDownloadLocation(id),
DictPathByLangId(id), DictPathByLangId(id),
@ -197,12 +198,13 @@ rpl::producer<int> GlobalLoaderChanged() {
DictLoader::DictLoader( DictLoader::DictLoader(
QObject *parent, QObject *parent,
not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,
int size, int size,
Fn<void()> destroyCallback) Fn<void()> destroyCallback)
: BlobLoader(parent, id, location, folder, size) : BlobLoader(parent, session, id, location, folder, size)
, _destroyCallback(std::move(destroyCallback)) { , _destroyCallback(std::move(destroyCallback)) {
} }

View file

@ -44,6 +44,7 @@ class DictLoader : public Storage::CloudBlob::BlobLoader {
public: public:
DictLoader( DictLoader(
QObject *parent, QObject *parent,
not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,

View file

@ -114,25 +114,27 @@ Application::Application(not_null<Launcher*> launcher)
}, _lifetime); }, _lifetime);
activeAccount().sessionChanges( activeAccount().sessionChanges(
) | rpl::start_with_next([=] { ) | rpl::start_with_next([=](Main::Session *session) {
if (_mediaView) { if (_mediaView) {
hideMediaView(); hideMediaView();
_mediaView->clearData(); _mediaView->clearData();
} }
if (session && !UpdaterDisabled()) {
if (const auto mtp = activeAccount().mtp()) {
UpdateChecker().setMtproto(mtp, session->userId());
}
}
}, _lifetime); }, _lifetime);
activeAccount().mtpChanges( activeAccount().mtpChanges(
) | rpl::filter([=](MTP::Instance *instance) { ) | rpl::filter([=](MTP::Instance *instance) {
return instance != nullptr; return instance != nullptr;
}) | rpl::start_with_next([=](not_null<MTP::Instance*> mtp) { }) | rpl::start_with_next([=] {
if (_window) { if (_window) {
// This should be called when user settings are read. // This should be called when user settings are read.
// Right now after they are read the startMtp() is called. // Right now after they are read the startMtp() is called.
_window->widget()->updateTrayMenu(); _window->widget()->updateTrayMenu();
} }
if (!UpdaterDisabled()) {
UpdateChecker().setMtproto(mtp.get());
}
}, _lifetime); }, _lifetime);
} }

View file

@ -172,7 +172,7 @@ private:
class MtpChecker : public Checker { class MtpChecker : public Checker {
public: public:
MtpChecker(QPointer<MTP::Instance> instance, bool testing); MtpChecker(QPointer<MTP::Instance> instance, int32 userId, bool testing);
void start() override; void start() override;
@ -191,6 +191,7 @@ private:
const FileLocation &location) const; const FileLocation &location) const;
MTP::WeakInstance _mtp; MTP::WeakInstance _mtp;
int32 _mtpUserId = 0;
}; };
@ -877,13 +878,17 @@ void HttpLoaderActor::partFailed(QNetworkReply::NetworkError e) {
_parent->threadSafeFailed(); _parent->threadSafeFailed();
} }
MtpChecker::MtpChecker(QPointer<MTP::Instance> instance, bool testing) MtpChecker::MtpChecker(
QPointer<MTP::Instance> instance,
int32 userId,
bool testing)
: Checker(testing) : Checker(testing)
, _mtp(instance) { , _mtp(instance)
, _mtpUserId(userId) {
} }
void MtpChecker::start() { void MtpChecker::start() {
if (!_mtp.valid()) { if (!_mtp.valid() || !_mtpUserId) {
LOG(("Update Info: MTP is unavailable.")); LOG(("Update Info: MTP is unavailable."));
crl::on_main(this, [=] { fail(); }); crl::on_main(this, [=] { fail(); });
return; return;
@ -891,7 +896,8 @@ void MtpChecker::start() {
const auto updaterVersion = Platform::AutoUpdateVersion(); const auto updaterVersion = Platform::AutoUpdateVersion();
const auto feed = "tdhbcfeed" const auto feed = "tdhbcfeed"
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString()); + (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
MTP::ResolveChannel(&_mtp, feed, [=](const MTPInputChannel &channel) { MTP::ResolveChannel(&_mtp, _mtpUserId, feed, [=](
const MTPInputChannel &channel) {
_mtp.send( _mtp.send(
MTPmessages_GetHistory( MTPmessages_GetHistory(
MTP_inputPeerChannel( MTP_inputPeerChannel(
@ -925,7 +931,12 @@ void MtpChecker::gotMessage(const MTPmessages_Messages &result) {
fail(); fail();
} }
}; };
MTP::StartDedicatedLoader(&_mtp, *location, UpdatesFolder(), ready); MTP::StartDedicatedLoader(
&_mtp,
_mtpUserId,
*location,
UpdatesFolder(),
ready);
} }
auto MtpChecker::parseMessage(const MTPmessages_Messages &result) const auto MtpChecker::parseMessage(const MTPmessages_Messages &result) const
@ -1033,7 +1044,7 @@ public:
int already() const; int already() const;
int size() const; int size() const;
void setMtproto(const QPointer<MTP::Instance> &mtproto); void setMtproto(const QPointer<MTP::Instance> &mtproto, int32 userId);
~Updater(); ~Updater();
@ -1079,6 +1090,7 @@ private:
std::shared_ptr<Loader> _activeLoader; std::shared_ptr<Loader> _activeLoader;
bool _usingMtprotoLoader = (cAlphaVersion() != 0); bool _usingMtprotoLoader = (cAlphaVersion() != 0);
QPointer<MTP::Instance> _mtproto; QPointer<MTP::Instance> _mtproto;
int32 _mtprotoUserId = 0;
rpl::lifetime _lifetime; rpl::lifetime _lifetime;
@ -1226,7 +1238,7 @@ void Updater::start(bool forceWait) {
std::make_unique<HttpChecker>(_testing)); std::make_unique<HttpChecker>(_testing));
startImplementation( startImplementation(
&_mtpImplementation, &_mtpImplementation,
std::make_unique<MtpChecker>(_mtproto, _testing)); std::make_unique<MtpChecker>(_mtproto, _mtprotoUserId, _testing));
_checking.fire({}); _checking.fire({});
} else { } else {
@ -1289,8 +1301,11 @@ void Updater::test() {
start(false); start(false);
} }
void Updater::setMtproto(const QPointer<MTP::Instance> &mtproto) { void Updater::setMtproto(
const QPointer<MTP::Instance> &mtproto,
int32 userId) {
_mtproto = mtproto; _mtproto = mtproto;
_mtprotoUserId = userId;
} }
void Updater::handleTimeout() { void Updater::handleTimeout() {
@ -1388,8 +1403,11 @@ Updater::~Updater() {
UpdateChecker::UpdateChecker() UpdateChecker::UpdateChecker()
: _updater(GetUpdaterInstance()) { : _updater(GetUpdaterInstance()) {
if (IsAppLaunched()) { if (IsAppLaunched()) {
if (const auto mtproto = Core::App().activeAccount().mtp()) { const auto &account = Core::App().activeAccount();
_updater->setMtproto(mtproto); if (account.sessionExists()) {
if (const auto mtproto = account.mtp()) {
_updater->setMtproto(mtproto, account.session().userId());
}
} }
} }
} }
@ -1423,8 +1441,10 @@ void UpdateChecker::test() {
_updater->test(); _updater->test();
} }
void UpdateChecker::setMtproto(const QPointer<MTP::Instance> &mtproto) { void UpdateChecker::setMtproto(
_updater->setMtproto(mtproto); const QPointer<MTP::Instance> &mtproto,
int32 userId) {
_updater->setMtproto(mtproto, userId);
} }
void UpdateChecker::stop() { void UpdateChecker::stop() {

View file

@ -41,7 +41,7 @@ public:
void stop(); void stop();
void test(); void test();
void setMtproto(const QPointer<MTP::Instance> &mtproto); void setMtproto(const QPointer<MTP::Instance> &mtproto, int32 userId);
State state() const; State state() const;
int already() const; int already() const;

View file

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

View file

@ -53,7 +53,7 @@ public:
[[nodiscard]] rpl::producer<Session*> sessionValue() const; [[nodiscard]] rpl::producer<Session*> sessionValue() const;
[[nodiscard]] rpl::producer<Session*> sessionChanges() const; [[nodiscard]] rpl::producer<Session*> sessionChanges() const;
[[nodiscard]] MTP::Instance *mtp() { [[nodiscard]] MTP::Instance *mtp() const {
return _mtp.get(); return _mtp.get();
} }
[[nodiscard]] rpl::producer<MTP::Instance*> mtpValue() const; [[nodiscard]] rpl::producer<MTP::Instance*> mtpValue() const;

View file

@ -147,8 +147,6 @@ bool Session::validateSelf(const MTPUser &user) {
} }
void Session::saveSettingsDelayed(crl::time delay) { void Session::saveSettingsDelayed(crl::time delay) {
Expects(this == &Auth());
_saveSettingsTimer.callOnce(delay); _saveSettingsTimer.callOnce(delay);
} }
@ -184,7 +182,3 @@ void Session::saveSettingsNowIfNeeded() {
} }
} // namespace Main } // namespace Main
Main::Session &Auth() {
return Core::App().activeAccount().session();
}

View file

@ -169,5 +169,3 @@ private:
}; };
} // namespace Main } // namespace Main
Main::Session &Auth();

View file

@ -365,6 +365,7 @@ Fn<void(const RPCError &)> DedicatedLoader::failHandler() {
void ResolveChannel( void ResolveChannel(
not_null<MTP::WeakInstance*> mtp, not_null<MTP::WeakInstance*> mtp,
int32 userId,
const QString &username, const QString &username,
Fn<void(const MTPInputChannel &channel)> done, Fn<void(const MTPInputChannel &channel)> done,
Fn<void()> fail) { Fn<void()> fail) {
@ -373,20 +374,20 @@ void ResolveChannel(
).arg(username)); ).arg(username));
fail(); fail();
}; };
if (!Main::Session::Exists()) { if (!userId) {
failed(); failed();
return; return;
} }
struct ResolveResult { struct ResolveResult {
base::weak_ptr<Main::Session> auth; int32 userId = 0;
MTPInputChannel channel; MTPInputChannel channel;
}; };
static std::map<QString, ResolveResult> ResolveCache; static std::map<QString, ResolveResult> ResolveCache;
const auto i = ResolveCache.find(username); const auto i = ResolveCache.find(username);
if (i != end(ResolveCache)) { if (i != end(ResolveCache)) {
if (i->second.auth.get() == &Auth()) { if (i->second.userId == userId) {
done(i->second.channel); done(i->second.channel);
return; return;
} }
@ -399,7 +400,7 @@ void ResolveChannel(
if (const auto channel = ExtractChannel(result)) { if (const auto channel = ExtractChannel(result)) {
ResolveCache.emplace( ResolveCache.emplace(
username, username,
ResolveResult { base::make_weak(&Auth()), *channel }); ResolveResult { userId, *channel });
done(*channel); done(*channel);
} else { } else {
failed(); failed();
@ -429,6 +430,7 @@ std::optional<MTPMessage> GetMessagesElement(
void StartDedicatedLoader( void StartDedicatedLoader(
not_null<MTP::WeakInstance*> mtp, not_null<MTP::WeakInstance*> mtp,
int32 userId,
const DedicatedLoader::Location &location, const DedicatedLoader::Location &location,
const QString &folder, const QString &folder,
Fn<void(std::unique_ptr<DedicatedLoader>)> ready) { Fn<void(std::unique_ptr<DedicatedLoader>)> ready) {
@ -448,7 +450,7 @@ void StartDedicatedLoader(
}; };
const auto [username, postId] = location; const auto [username, postId] = location;
ResolveChannel(mtp, username, [=, postId = postId]( ResolveChannel(mtp, userId, username, [=, postId = postId](
const MTPInputChannel &channel) { const MTPInputChannel &channel) {
mtp->send( mtp->send(
MTPchannels_GetMessages( MTPchannels_GetMessages(

View file

@ -143,6 +143,7 @@ private:
void ResolveChannel( void ResolveChannel(
not_null<MTP::WeakInstance*> mtp, not_null<MTP::WeakInstance*> mtp,
int32 userId,
const QString &username, const QString &username,
Fn<void(const MTPInputChannel &channel)> done, Fn<void(const MTPInputChannel &channel)> done,
Fn<void()> fail); Fn<void()> fail);
@ -152,6 +153,7 @@ std::optional<MTPMessage> GetMessagesElement(
void StartDedicatedLoader( void StartDedicatedLoader(
not_null<MTP::WeakInstance*> mtp, not_null<MTP::WeakInstance*> mtp,
int32 userId,
const DedicatedLoader::Location &location, const DedicatedLoader::Location &location,
const QString &folder, const QString &folder,
Fn<void(std::unique_ptr<DedicatedLoader>)> ready); Fn<void(std::unique_ptr<DedicatedLoader>)> ready);

View file

@ -737,8 +737,8 @@ void SetupStickersEmoji(
st::settingsChatButton, st::settingsChatButton,
&st::settingsIconEmoji, &st::settingsIconEmoji,
st::settingsChatIconLeft st::settingsChatIconLeft
)->addClickHandler([] { )->addClickHandler([=] {
Ui::show(Box<Ui::Emoji::ManageSetsBox>()); Ui::show(Box<Ui::Emoji::ManageSetsBox>(session));
}); });
AddSkip(container, st::settingsCheckboxesSkip); AddSkip(container, st::settingsCheckboxesSkip);

View file

@ -582,7 +582,7 @@ public:
voice->waveform[0] = -2; voice->waveform[0] = -2;
voice->wavemax = 0; voice->wavemax = 0;
} }
Auth().data().requestDocumentViewRepaint(_doc); _doc->owner().requestDocumentViewRepaint(_doc);
} }
} }
~CountWaveformTask() { ~CountWaveformTask() {

View file

@ -200,7 +200,10 @@ void writePeer(QDataStream &stream, PeerData *peer) {
} }
} }
PeerData *readPeer(int streamAppVersion, QDataStream &stream) { PeerData *readPeer(
not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream) {
quint64 peerId = 0, photoId = 0; quint64 peerId = 0, photoId = 0;
stream >> peerId >> photoId; stream >> peerId >> photoId;
if (!peerId) { if (!peerId) {
@ -213,8 +216,8 @@ PeerData *readPeer(int streamAppVersion, QDataStream &stream) {
return nullptr; return nullptr;
} }
const auto loaded = Auth().data().peerLoaded(peerId); const auto loaded = session->data().peerLoaded(peerId);
const auto result = loaded ? loaded : Auth().data().peer(peerId).get(); const auto result = loaded ? loaded : session->data().peer(peerId).get();
if (!loaded) { if (!loaded) {
result->loadedStatus = PeerData::FullLoaded; result->loadedStatus = PeerData::FullLoaded;
} }
@ -234,7 +237,7 @@ PeerData *readPeer(int streamAppVersion, QDataStream &stream) {
userpicAccessHash = access; userpicAccessHash = access;
const auto showPhone = !user->isServiceUser() const auto showPhone = !user->isServiceUser()
&& (user->id != Auth().userPeerId()) && (user->id != session->userPeerId())
&& (contact <= 0); && (contact <= 0);
const auto pname = (showPhone && !phone.isEmpty()) const auto pname = (showPhone && !phone.isEmpty())
? App::formatPhone(phone) ? App::formatPhone(phone)
@ -253,7 +256,7 @@ PeerData *readPeer(int streamAppVersion, QDataStream &stream) {
user->botInfo->inlinePlaceholder = inlinePlaceholder; user->botInfo->inlinePlaceholder = inlinePlaceholder;
} }
if (user->id == Auth().userPeerId()) { if (user->id == session->userPeerId()) {
user->input = MTP_inputPeerSelf(); user->input = MTP_inputPeerSelf();
user->inputUser = MTP_inputUserSelf(); user->inputUser = MTP_inputUserSelf();
} else { } else {

View file

@ -127,7 +127,10 @@ inline MTP::AuthKey::Data read<MTP::AuthKey::Data>(QDataStream &stream) {
uint32 peerSize(not_null<PeerData*> peer); uint32 peerSize(not_null<PeerData*> peer);
void writePeer(QDataStream &stream, PeerData *peer); void writePeer(QDataStream &stream, PeerData *peer);
PeerData *readPeer(int streamAppVersion, QDataStream &stream); PeerData *readPeer(
not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream);
QString peekUserPhone(int streamAppVersion, QDataStream &stream); QString peekUserPhone(int streamAppVersion, QDataStream &stream);
} // namespace Serialize } // namespace Serialize

View file

@ -56,7 +56,11 @@ void Document::writeToStream(QDataStream &stream, DocumentData *document) {
stream << qint32(document->videoThumbnailByteSize()); stream << qint32(document->videoThumbnailByteSize());
} }
DocumentData *Document::readFromStreamHelper(int streamAppVersion, QDataStream &stream, const StickerSetInfo *info) { DocumentData *Document::readFromStreamHelper(
not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream,
const StickerSetInfo *info) {
quint64 id, access; quint64 id, access;
QString name, mime; QString name, mime;
qint32 date, dc, size, width, height, type, versionTag, version = 0; qint32 date, dc, size, width, height, type, versionTag, version = 0;
@ -151,7 +155,7 @@ DocumentData *Document::readFromStreamHelper(int streamAppVersion, QDataStream &
// size letter ('s' or 'm') is lost, it was not saved in legacy. // size letter ('s' or 'm') is lost, it was not saved in legacy.
return nullptr; return nullptr;
} }
return Auth().data().document( return session->data().document(
id, id,
access, access,
fileReference, fileReference,
@ -171,12 +175,19 @@ DocumentData *Document::readFromStreamHelper(int streamAppVersion, QDataStream &
size); size);
} }
DocumentData *Document::readStickerFromStream(int streamAppVersion, QDataStream &stream, const StickerSetInfo &info) { DocumentData *Document::readStickerFromStream(
return readFromStreamHelper(streamAppVersion, stream, &info); not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream,
const StickerSetInfo &info) {
return readFromStreamHelper(session, streamAppVersion, stream, &info);
} }
DocumentData *Document::readFromStream(int streamAppVersion, QDataStream &stream) { DocumentData *Document::readFromStream(
return readFromStreamHelper(streamAppVersion, stream, nullptr); not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream) {
return readFromStreamHelper(session, streamAppVersion, stream, nullptr);
} }
int Document::sizeInStream(DocumentData *document) { int Document::sizeInStream(DocumentData *document) {

View file

@ -25,12 +25,23 @@ public:
}; };
static void writeToStream(QDataStream &stream, DocumentData *document); static void writeToStream(QDataStream &stream, DocumentData *document);
static DocumentData *readStickerFromStream(int streamAppVersion, QDataStream &stream, const StickerSetInfo &info); static DocumentData *readStickerFromStream(
static DocumentData *readFromStream(int streamAppVersion, QDataStream &stream); not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream,
const StickerSetInfo &info);
static DocumentData *readFromStream(
not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream);
static int sizeInStream(DocumentData *document); static int sizeInStream(DocumentData *document);
private: private:
static DocumentData *readFromStreamHelper(int streamAppVersion, QDataStream &stream, const StickerSetInfo *info); static DocumentData *readFromStreamHelper(
not_null<Main::Session*> session,
int streamAppVersion,
QDataStream &stream,
const StickerSetInfo *info);
}; };

View file

@ -421,12 +421,12 @@ void Account::writeMap() {
map.writeData(_passcodeKeyEncrypted); map.writeData(_passcodeKeyEncrypted);
uint32 mapSize = 0; uint32 mapSize = 0;
const auto self = [] { const auto self = [&] {
if (!Main::Session::Exists()) { if (!_owner->sessionExists()) {
DEBUG_LOG(("AuthSelf Warning: Session does not exist.")); DEBUG_LOG(("AuthSelf Warning: Session does not exist."));
return QByteArray(); return QByteArray();
} }
const auto self = Auth().user(); const auto self = _owner->session().user();
if (self->phone().isEmpty()) { if (self->phone().isEmpty()) {
DEBUG_LOG(("AuthSelf Error: Phone is empty.")); DEBUG_LOG(("AuthSelf Error: Phone is empty."));
return QByteArray(); return QByteArray();
@ -1343,7 +1343,7 @@ void Account::writeStickerSets(
FileKey &stickersKey, FileKey &stickersKey,
CheckSet checkSet, CheckSet checkSet,
const Data::StickersSetsOrder &order) { const Data::StickersSetsOrder &order) {
const auto &sets = Auth().data().stickers().sets(); const auto &sets = _owner->session().data().stickers().sets();
if (sets.empty()) { if (sets.empty()) {
if (stickersKey) { if (stickersKey) {
ClearKey(stickersKey, _basePath); ClearKey(stickersKey, _basePath);
@ -1444,7 +1444,7 @@ void Account::readStickerSets(
stickersKey = 0; stickersKey = 0;
}; };
auto &sets = Auth().data().stickers().setsRef(); auto &sets = _owner->session().data().stickers().setsRef();
if (outOrder) outOrder->clear(); if (outOrder) outOrder->clear();
quint32 versionTag = 0; quint32 versionTag = 0;
@ -1519,7 +1519,7 @@ void Account::readStickerSets(
// We will set this flags from order lists when reading those stickers. // We will set this flags from order lists when reading those stickers.
setFlags &= ~(MTPDstickerSet::Flag::f_installed_date | MTPDstickerSet_ClientFlag::f_featured); setFlags &= ~(MTPDstickerSet::Flag::f_installed_date | MTPDstickerSet_ClientFlag::f_featured);
it = sets.emplace(setId, std::make_unique<Data::StickersSet>( it = sets.emplace(setId, std::make_unique<Data::StickersSet>(
&Auth().data(), &_owner->session().data(),
setId, setId,
setAccess, setAccess,
setTitle, setTitle,
@ -1550,7 +1550,10 @@ void Account::readStickerSets(
Serialize::Document::StickerSetInfo info(setId, setAccess, setShortName); Serialize::Document::StickerSetInfo info(setId, setAccess, setShortName);
base::flat_set<DocumentId> read; base::flat_set<DocumentId> read;
for (int32 j = 0; j < scnt; ++j) { for (int32 j = 0; j < scnt; ++j) {
auto document = Serialize::Document::readStickerFromStream(stickers.version, stickers.stream, info); auto document = Serialize::Document::readStickerFromStream(
&_owner->session(),
stickers.version,
stickers.stream, info);
if (!CheckStreamStatus(stickers.stream)) { if (!CheckStreamStatus(stickers.stream)) {
return failed(); return failed();
} else if (!document } else if (!document
@ -1605,7 +1608,7 @@ void Account::readStickerSets(
for (int32 k = 0; k < stickersCount; ++k) { for (int32 k = 0; k < stickersCount; ++k) {
quint64 id; quint64 id;
stickers.stream >> id; stickers.stream >> id;
const auto doc = Auth().data().document(id); const auto doc = _owner->session().data().document(id);
if (!doc->sticker()) continue; if (!doc->sticker()) continue;
pack.push_back(doc); pack.push_back(doc);
@ -1673,7 +1676,7 @@ void Account::writeInstalledStickers() {
return StickerSetCheckResult::Skip; return StickerSetCheckResult::Skip;
} }
return StickerSetCheckResult::Write; return StickerSetCheckResult::Write;
}, Auth().data().stickers().setsOrder()); }, _owner->session().data().stickers().setsOrder());
} }
void Account::writeFeaturedStickers() { void Account::writeFeaturedStickers() {
@ -1691,7 +1694,7 @@ void Account::writeFeaturedStickers() {
return StickerSetCheckResult::Skip; return StickerSetCheckResult::Skip;
} }
return StickerSetCheckResult::Write; return StickerSetCheckResult::Write;
}, Auth().data().stickers().featuredSetsOrder()); }, _owner->session().data().stickers().featuredSetsOrder());
} }
void Account::writeRecentStickers() { void Account::writeRecentStickers() {
@ -1718,7 +1721,7 @@ void Account::writeArchivedStickers() {
return StickerSetCheckResult::Skip; return StickerSetCheckResult::Skip;
} }
return StickerSetCheckResult::Write; return StickerSetCheckResult::Write;
}, Auth().data().stickers().archivedSetsOrder()); }, _owner->session().data().stickers().archivedSetsOrder());
} }
void Account::importOldRecentStickers() { void Account::importOldRecentStickers() {
@ -1734,10 +1737,10 @@ void Account::importOldRecentStickers() {
return; return;
} }
auto &sets = Auth().data().stickers().setsRef(); auto &sets = _owner->session().data().stickers().setsRef();
sets.clear(); sets.clear();
auto &order = Auth().data().stickers().setsOrderRef(); auto &order = _owner->session().data().stickers().setsOrderRef();
order.clear(); order.clear();
auto &recent = cRefRecentStickers(); auto &recent = cRefRecentStickers();
@ -1746,7 +1749,7 @@ void Account::importOldRecentStickers() {
const auto def = sets.emplace( const auto def = sets.emplace(
Data::Stickers::DefaultSetId, Data::Stickers::DefaultSetId,
std::make_unique<Data::StickersSet>( std::make_unique<Data::StickersSet>(
&Auth().data(), &_owner->session().data(),
Data::Stickers::DefaultSetId, Data::Stickers::DefaultSetId,
uint64(0), uint64(0),
tr::lng_stickers_default_set(tr::now), tr::lng_stickers_default_set(tr::now),
@ -1760,7 +1763,7 @@ void Account::importOldRecentStickers() {
const auto custom = sets.emplace( const auto custom = sets.emplace(
Data::Stickers::CustomSetId, Data::Stickers::CustomSetId,
std::make_unique<Data::StickersSet>( std::make_unique<Data::StickersSet>(
&Auth().data(), &_owner->session().data(),
Data::Stickers::CustomSetId, Data::Stickers::CustomSetId,
uint64(0), uint64(0),
qsl("Custom stickers"), qsl("Custom stickers"),
@ -1795,7 +1798,7 @@ void Account::importOldRecentStickers() {
attributes.push_back(MTP_documentAttributeImageSize(MTP_int(width), MTP_int(height))); attributes.push_back(MTP_documentAttributeImageSize(MTP_int(width), MTP_int(height)));
} }
const auto doc = Auth().data().document( const auto doc = _owner->session().data().document(
id, id,
access, access,
QByteArray(), QByteArray(),
@ -1844,21 +1847,21 @@ void Account::readInstalledStickers() {
return importOldRecentStickers(); return importOldRecentStickers();
} }
Auth().data().stickers().setsRef().clear(); _owner->session().data().stickers().setsRef().clear();
readStickerSets( readStickerSets(
_installedStickersKey, _installedStickersKey,
&Auth().data().stickers().setsOrderRef(), &_owner->session().data().stickers().setsOrderRef(),
MTPDstickerSet::Flag::f_installed_date); MTPDstickerSet::Flag::f_installed_date);
} }
void Account::readFeaturedStickers() { void Account::readFeaturedStickers() {
readStickerSets( readStickerSets(
_featuredStickersKey, _featuredStickersKey,
&Auth().data().stickers().featuredSetsOrderRef(), &_owner->session().data().stickers().featuredSetsOrderRef(),
MTPDstickerSet::Flags() | MTPDstickerSet_ClientFlag::f_featured); MTPDstickerSet::Flags() | MTPDstickerSet_ClientFlag::f_featured);
const auto &sets = Auth().data().stickers().sets(); const auto &sets = _owner->session().data().stickers().sets();
const auto &order = Auth().data().stickers().featuredSetsOrder(); const auto &order = _owner->session().data().stickers().featuredSetsOrder();
int unreadCount = 0; int unreadCount = 0;
for (const auto setId : order) { for (const auto setId : order) {
auto it = sets.find(setId); auto it = sets.find(setId);
@ -1867,7 +1870,7 @@ void Account::readFeaturedStickers() {
++unreadCount; ++unreadCount;
} }
} }
Auth().data().stickers().setFeaturedSetsUnreadCount(unreadCount); _owner->session().data().stickers().setFeaturedSetsUnreadCount(unreadCount);
} }
void Account::readRecentStickers() { void Account::readRecentStickers() {
@ -1881,13 +1884,13 @@ void Account::readFavedStickers() {
void Account::readArchivedStickers() { void Account::readArchivedStickers() {
static bool archivedStickersRead = false; static bool archivedStickersRead = false;
if (!archivedStickersRead) { if (!archivedStickersRead) {
readStickerSets(_archivedStickersKey, &Auth().data().stickers().archivedSetsOrderRef()); readStickerSets(_archivedStickersKey, &_owner->session().data().stickers().archivedSetsOrderRef());
archivedStickersRead = true; archivedStickersRead = true;
} }
} }
void Account::writeSavedGifs() { void Account::writeSavedGifs() {
auto &saved = Auth().data().stickers().savedGifs(); auto &saved = _owner->session().data().stickers().savedGifs();
if (saved.isEmpty()) { if (saved.isEmpty()) {
if (_savedGifsKey) { if (_savedGifsKey) {
ClearKey(_savedGifsKey, _basePath); ClearKey(_savedGifsKey, _basePath);
@ -1925,7 +1928,7 @@ void Account::readSavedGifs() {
return; return;
} }
auto &saved = Auth().data().stickers().savedGifsRef(); auto &saved = _owner->session().data().stickers().savedGifsRef();
const auto failed = [&] { const auto failed = [&] {
ClearKey(_savedGifsKey, _basePath); ClearKey(_savedGifsKey, _basePath);
_savedGifsKey = 0; _savedGifsKey = 0;
@ -1938,7 +1941,10 @@ void Account::readSavedGifs() {
saved.reserve(cnt); saved.reserve(cnt);
OrderedSet<DocumentId> read; OrderedSet<DocumentId> read;
for (uint32 i = 0; i < cnt; ++i) { for (uint32 i = 0; i < cnt; ++i) {
auto document = Serialize::Document::readFromStream(gifs.version, gifs.stream); auto document = Serialize::Document::readFromStream(
&_owner->session(),
gifs.version,
gifs.stream);
if (!CheckStreamStatus(gifs.stream)) { if (!CheckStreamStatus(gifs.stream)) {
return failed(); return failed();
} else if (!document || !document->isGifv()) { } else if (!document || !document->isGifv()) {
@ -2229,6 +2235,7 @@ void Account::readRecentHashtagsAndBots() {
bots.reserve(botsCount); bots.reserve(botsCount);
for (auto i = 0; i < botsCount; ++i) { for (auto i = 0; i < botsCount; ++i) {
const auto peer = Serialize::readPeer( const auto peer = Serialize::readPeer(
&_owner->session(),
hashtags.version, hashtags.version,
hashtags.stream); hashtags.stream);
if (!peer) { if (!peer) {
@ -2439,11 +2446,14 @@ void Account::writeSelf() {
void Account::readSelf(const QByteArray &serialized, int32 streamVersion) { void Account::readSelf(const QByteArray &serialized, int32 streamVersion) {
QDataStream stream(serialized); QDataStream stream(serialized);
const auto user = Auth().user(); const auto user = _owner->session().user();
const auto wasLoadedStatus = std::exchange( const auto wasLoadedStatus = std::exchange(
user->loadedStatus, user->loadedStatus,
PeerData::NotLoaded); PeerData::NotLoaded);
const auto self = Serialize::readPeer(streamVersion, stream); const auto self = Serialize::readPeer(
&_owner->session(),
streamVersion,
stream);
if (!self || !self->isSelf() || self != user) { if (!self || !self->isSelf() || self != user) {
user->loadedStatus = wasLoadedStatus; user->loadedStatus = wasLoadedStatus;
return; return;

View file

@ -8,10 +8,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/storage_cloud_blob.h" #include "storage/storage_cloud_blob.h"
#include "base/zlib_help.h" #include "base/zlib_help.h"
#include "core/application.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "layout.h" #include "layout.h"
#include "main/main_account.h" #include "main/main_account.h"
#include "main/main_session.h"
namespace Storage::CloudBlob { namespace Storage::CloudBlob {
@ -95,6 +95,7 @@ QString StateDescription(const BlobState &state, tr::phrase<> activeText) {
BlobLoader::BlobLoader( BlobLoader::BlobLoader(
QObject *parent, QObject *parent,
not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,
@ -103,7 +104,8 @@ BlobLoader::BlobLoader(
, _folder(folder) , _folder(folder)
, _id(id) , _id(id)
, _state(Loading{ 0, size }) , _state(Loading{ 0, size })
, _mtproto(Core::App().activeAccount().mtp()) { , _mtproto(session->account().mtp())
, _mtprotoUserId(session->userId()) {
const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) { const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) {
if (loader) { if (loader) {
setImplementation(std::move(loader)); setImplementation(std::move(loader));
@ -111,7 +113,12 @@ BlobLoader::BlobLoader(
fail(); fail();
} }
}; };
MTP::StartDedicatedLoader(&_mtproto, location, _folder, ready); MTP::StartDedicatedLoader(
&_mtproto,
_mtprotoUserId,
location,
_folder,
ready);
} }
int BlobLoader::id() const { int BlobLoader::id() const {

View file

@ -14,6 +14,10 @@ template <typename ...>
struct phrase; struct phrase;
} // namespace tr } // namespace tr
namespace Main {
class Session;
} // namespace Main
namespace Storage::CloudBlob { namespace Storage::CloudBlob {
constexpr auto kCloudLocationUsername = "tdhbcfiles"_cs; constexpr auto kCloudLocationUsername = "tdhbcfiles"_cs;
@ -79,6 +83,7 @@ class BlobLoader : public QObject {
public: public:
BlobLoader( BlobLoader(
QObject *parent, QObject *parent,
not_null<Main::Session*> session,
int id, int id,
MTP::DedicatedLoader::Location location, MTP::DedicatedLoader::Location location,
const QString &folder, const QString &folder,
@ -102,6 +107,8 @@ private:
rpl::variable<BlobState> _state; rpl::variable<BlobState> _state;
MTP::WeakInstance _mtproto; MTP::WeakInstance _mtproto;
int32 _mtprotoUserId = 0;
std::unique_ptr<MTP::DedicatedLoader> _implementation; std::unique_ptr<MTP::DedicatedLoader> _implementation;
}; };

View file

@ -83,10 +83,12 @@ void Controller::setupIntro() {
} }
void Controller::setupMain() { void Controller::setupMain() {
Expects(_account->sessionExists());
_widget.setupMain(); _widget.setupMain();
if (const auto id = Ui::Emoji::NeedToSwitchBackToId()) { if (const auto id = Ui::Emoji::NeedToSwitchBackToId()) {
Ui::Emoji::LoadAndSwitchTo(id); Ui::Emoji::LoadAndSwitchTo(&_account->session(), id);
} }
} }