main_account.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "main/main_account.h"
  8. #include "base/platform/base_platform_info.h"
  9. #include "core/application.h"
  10. #include "storage/storage_account.h"
  11. #include "storage/storage_domain.h" // Storage::StartResult.
  12. #include "storage/serialize_common.h"
  13. #include "storage/serialize_peer.h"
  14. #include "storage/localstorage.h"
  15. #include "data/data_session.h"
  16. #include "data/data_user.h"
  17. #include "data/data_changes.h"
  18. #include "window/window_controller.h"
  19. #include "media/audio/media_audio.h"
  20. #include "mtproto/mtproto_config.h"
  21. #include "mainwidget.h"
  22. #include "api/api_updates.h"
  23. #include "ui/ui_utility.h"
  24. #include "main/main_app_config.h"
  25. #include "main/main_session.h"
  26. #include "main/main_domain.h"
  27. #include "main/main_session_settings.h"
  28. namespace Main {
  29. namespace {
  30. constexpr auto kWideIdsTag = ~uint64(0);
  31. [[nodiscard]] QString ComposeDataString(const QString &dataName, int index) {
  32. auto result = dataName;
  33. result.replace('#', QString());
  34. if (index > 0) {
  35. result += '#' + QString::number(index + 1);
  36. }
  37. return result;
  38. }
  39. } // namespace
  40. Account::Account(not_null<Domain*> domain, const QString &dataName, int index)
  41. : _domain(domain)
  42. , _local(std::make_unique<Storage::Account>(
  43. this,
  44. ComposeDataString(dataName, index))) {
  45. }
  46. Account::~Account() {
  47. if (const auto session = maybeSession()) {
  48. session->saveSettingsNowIfNeeded();
  49. _local->writeSearchSuggestionsIfNeeded();
  50. }
  51. destroySession(DestroyReason::Quitting);
  52. }
  53. Storage::Domain &Account::domainLocal() const {
  54. return _domain->local();
  55. }
  56. [[nodiscard]] Storage::StartResult Account::legacyStart(
  57. const QByteArray &passcode) {
  58. Expects(!_appConfig);
  59. return _local->legacyStart(passcode);
  60. }
  61. std::unique_ptr<MTP::Config> Account::prepareToStart(
  62. std::shared_ptr<MTP::AuthKey> localKey) {
  63. return _local->start(std::move(localKey));
  64. }
  65. void Account::start(std::unique_ptr<MTP::Config> config) {
  66. _appConfig = std::make_unique<AppConfig>(this);
  67. startMtp(config
  68. ? std::move(config)
  69. : std::make_unique<MTP::Config>(
  70. Core::App().fallbackProductionConfig()));
  71. _appConfig->start();
  72. watchProxyChanges();
  73. watchSessionChanges();
  74. }
  75. void Account::prepareToStartAdded(
  76. std::shared_ptr<MTP::AuthKey> localKey) {
  77. _local->startAdded(std::move(localKey));
  78. }
  79. void Account::watchProxyChanges() {
  80. using ProxyChange = Core::Application::ProxyChange;
  81. Core::App().proxyChanges(
  82. ) | rpl::start_with_next([=](const ProxyChange &change) {
  83. const auto key = [&](const MTP::ProxyData &proxy) {
  84. return (proxy.type == MTP::ProxyData::Type::Mtproto)
  85. ? std::make_pair(proxy.host, proxy.port)
  86. : std::make_pair(QString(), uint32(0));
  87. };
  88. if (_mtp) {
  89. _mtp->restart();
  90. if (key(change.was) != key(change.now)) {
  91. _mtp->reInitConnection(_mtp->mainDcId());
  92. }
  93. }
  94. if (_mtpForKeysDestroy) {
  95. _mtpForKeysDestroy->restart();
  96. }
  97. }, _lifetime);
  98. }
  99. void Account::watchSessionChanges() {
  100. sessionChanges(
  101. ) | rpl::start_with_next([=](Session *session) {
  102. if (!session && _mtp) {
  103. _mtp->setUserPhone(QString());
  104. }
  105. }, _lifetime);
  106. }
  107. uint64 Account::willHaveSessionUniqueId(MTP::Config *config) const {
  108. // See also Session::uniqueId.
  109. if (!_sessionUserId) {
  110. return 0;
  111. }
  112. return _sessionUserId.bare
  113. | (config && config->isTestMode() ? 0x0100'0000'0000'0000ULL : 0ULL);
  114. }
  115. void Account::createSession(
  116. const MTPUser &user,
  117. std::unique_ptr<SessionSettings> settings) {
  118. createSession(
  119. user,
  120. QByteArray(),
  121. 0,
  122. settings ? std::move(settings) : std::make_unique<SessionSettings>());
  123. }
  124. void Account::createSession(
  125. UserId id,
  126. QByteArray serialized,
  127. int streamVersion,
  128. std::unique_ptr<SessionSettings> settings) {
  129. DEBUG_LOG(("sessionUserSerialized.size: %1").arg(serialized.size()));
  130. QDataStream peekStream(serialized);
  131. const auto phone = Serialize::peekUserPhone(streamVersion, peekStream);
  132. const auto flags = MTPDuser::Flag::f_self | (phone.isEmpty()
  133. ? MTPDuser::Flag()
  134. : MTPDuser::Flag::f_phone);
  135. createSession(
  136. MTP_user(
  137. MTP_flags(flags),
  138. MTP_long(base::take(_sessionUserId).bare),
  139. MTPlong(), // access_hash
  140. MTPstring(), // first_name
  141. MTPstring(), // last_name
  142. MTPstring(), // username
  143. MTP_string(phone),
  144. MTPUserProfilePhoto(),
  145. MTPUserStatus(),
  146. MTPint(), // bot_info_version
  147. MTPVector<MTPRestrictionReason>(),
  148. MTPstring(), // bot_inline_placeholder
  149. MTPstring(), // lang_code
  150. MTPEmojiStatus(),
  151. MTPVector<MTPUsername>(),
  152. MTPint(), // stories_max_id
  153. MTPPeerColor(), // color
  154. MTPPeerColor(), // profile_color
  155. MTPint(), // bot_active_users
  156. MTPlong(), // bot_verification_icon
  157. MTPlong()), // send_paid_messages_stars
  158. serialized,
  159. streamVersion,
  160. std::move(settings));
  161. }
  162. void Account::createSession(
  163. const MTPUser &user,
  164. QByteArray serialized,
  165. int streamVersion,
  166. std::unique_ptr<SessionSettings> settings) {
  167. Expects(_mtp != nullptr);
  168. Expects(_session == nullptr);
  169. Expects(_sessionValue.current() == nullptr);
  170. _session = std::make_unique<Session>(this, user, std::move(settings));
  171. if (!serialized.isEmpty()) {
  172. local().readSelf(_session.get(), serialized, streamVersion);
  173. }
  174. _sessionValue = _session.get();
  175. Ensures(_session != nullptr);
  176. }
  177. void Account::destroySession(DestroyReason reason) {
  178. _storedSessionSettings.reset();
  179. _sessionUserId = 0;
  180. _sessionUserSerialized = {};
  181. if (!sessionExists()) {
  182. return;
  183. }
  184. _sessionValue = nullptr;
  185. if (reason == DestroyReason::LoggedOut) {
  186. _session->finishLogout();
  187. }
  188. _session = nullptr;
  189. }
  190. bool Account::sessionExists() const {
  191. return (_sessionValue.current() != nullptr);
  192. }
  193. Session &Account::session() const {
  194. Expects(sessionExists());
  195. return *_sessionValue.current();
  196. }
  197. Session *Account::maybeSession() const {
  198. return _sessionValue.current();
  199. }
  200. rpl::producer<Session*> Account::sessionValue() const {
  201. return _sessionValue.value();
  202. }
  203. rpl::producer<Session*> Account::sessionChanges() const {
  204. return _sessionValue.changes();
  205. }
  206. rpl::producer<not_null<MTP::Instance*>> Account::mtpValue() const {
  207. return _mtpValue.value() | rpl::map([](MTP::Instance *instance) {
  208. return not_null{ instance };
  209. });
  210. }
  211. rpl::producer<not_null<MTP::Instance*>> Account::mtpMainSessionValue() const {
  212. return mtpValue() | rpl::map([=](not_null<MTP::Instance*> instance) {
  213. return instance->mainDcIdValue() | rpl::map_to(instance);
  214. }) | rpl::flatten_latest();
  215. }
  216. rpl::producer<MTPUpdates> Account::mtpUpdates() const {
  217. return _mtpUpdates.events();
  218. }
  219. rpl::producer<> Account::mtpNewSessionCreated() const {
  220. return _mtpNewSessionCreated.events();
  221. }
  222. void Account::setMtpMainDcId(MTP::DcId mainDcId) {
  223. Expects(!_mtp);
  224. _mtpFields.mainDcId = mainDcId;
  225. }
  226. void Account::setLegacyMtpKey(std::shared_ptr<MTP::AuthKey> key) {
  227. Expects(!_mtp);
  228. Expects(key != nullptr);
  229. _mtpFields.keys.push_back(std::move(key));
  230. }
  231. QByteArray Account::serializeMtpAuthorization() const {
  232. const auto serialize = [&](
  233. MTP::DcId mainDcId,
  234. const MTP::AuthKeysList &keys,
  235. const MTP::AuthKeysList &keysToDestroy) {
  236. const auto keysSize = [](auto &list) {
  237. const auto keyDataSize = MTP::AuthKey::Data().size();
  238. return sizeof(qint32)
  239. + list.size() * (sizeof(qint32) + keyDataSize);
  240. };
  241. const auto writeKeys = [](
  242. QDataStream &stream,
  243. const MTP::AuthKeysList &keys) {
  244. stream << qint32(keys.size());
  245. for (const auto &key : keys) {
  246. stream << qint32(key->dcId());
  247. key->write(stream);
  248. }
  249. };
  250. auto result = QByteArray();
  251. // wide tag + userId + mainDcId
  252. auto size = 2 * sizeof(quint64) + sizeof(qint32);
  253. size += keysSize(keys) + keysSize(keysToDestroy);
  254. result.reserve(size);
  255. {
  256. QDataStream stream(&result, QIODevice::WriteOnly);
  257. stream.setVersion(QDataStream::Qt_5_1);
  258. const auto currentUserId = sessionExists()
  259. ? session().userId()
  260. : UserId();
  261. stream
  262. << quint64(kWideIdsTag)
  263. << quint64(currentUserId.bare)
  264. << qint32(mainDcId);
  265. writeKeys(stream, keys);
  266. writeKeys(stream, keysToDestroy);
  267. DEBUG_LOG(("MTP Info: Keys written, userId: %1, dcId: %2"
  268. ).arg(currentUserId.bare
  269. ).arg(mainDcId));
  270. }
  271. return result;
  272. };
  273. if (_mtp) {
  274. const auto keys = _mtp->getKeysForWrite();
  275. const auto keysToDestroy = _mtpForKeysDestroy
  276. ? _mtpForKeysDestroy->getKeysForWrite()
  277. : MTP::AuthKeysList();
  278. return serialize(_mtp->mainDcId(), keys, keysToDestroy);
  279. }
  280. const auto &keys = _mtpFields.keys;
  281. const auto &keysToDestroy = _mtpKeysToDestroy;
  282. return serialize(_mtpFields.mainDcId, keys, keysToDestroy);
  283. }
  284. void Account::setSessionUserId(UserId userId) {
  285. Expects(!sessionExists());
  286. _sessionUserId = userId;
  287. }
  288. void Account::setSessionFromStorage(
  289. std::unique_ptr<SessionSettings> data,
  290. QByteArray &&selfSerialized,
  291. int32 selfStreamVersion) {
  292. Expects(!sessionExists());
  293. DEBUG_LOG(("sessionUserSerialized set: %1"
  294. ).arg(selfSerialized.size()));
  295. _storedSessionSettings = std::move(data);
  296. _sessionUserSerialized = std::move(selfSerialized);
  297. _sessionUserStreamVersion = selfStreamVersion;
  298. }
  299. SessionSettings *Account::getSessionSettings() {
  300. if (_sessionUserId) {
  301. return _storedSessionSettings
  302. ? _storedSessionSettings.get()
  303. : nullptr;
  304. } else if (const auto session = maybeSession()) {
  305. return &session->settings();
  306. }
  307. return nullptr;
  308. }
  309. void Account::setMtpAuthorization(const QByteArray &serialized) {
  310. Expects(!_mtp);
  311. QDataStream stream(serialized);
  312. stream.setVersion(QDataStream::Qt_5_1);
  313. auto legacyUserId = Serialize::read<qint32>(stream);
  314. auto legacyMainDcId = Serialize::read<qint32>(stream);
  315. auto userId = quint64();
  316. auto mainDcId = qint32();
  317. if (((uint64(legacyUserId) << 32) | uint64(legacyMainDcId))
  318. == kWideIdsTag) {
  319. userId = Serialize::read<quint64>(stream);
  320. mainDcId = Serialize::read<qint32>(stream);
  321. } else {
  322. userId = legacyUserId;
  323. mainDcId = legacyMainDcId;
  324. }
  325. if (stream.status() != QDataStream::Ok) {
  326. LOG(("MTP Error: "
  327. "Could not read main fields from mtp authorization."));
  328. return;
  329. }
  330. setSessionUserId(userId);
  331. _mtpFields.mainDcId = mainDcId;
  332. const auto readKeys = [&](auto &keys) {
  333. const auto count = Serialize::read<qint32>(stream);
  334. if (stream.status() != QDataStream::Ok) {
  335. LOG(("MTP Error: "
  336. "Could not read keys count from mtp authorization."));
  337. return;
  338. }
  339. keys.reserve(count);
  340. for (auto i = 0; i != count; ++i) {
  341. const auto dcId = Serialize::read<qint32>(stream);
  342. const auto keyData = Serialize::read<MTP::AuthKey::Data>(stream);
  343. if (stream.status() != QDataStream::Ok) {
  344. LOG(("MTP Error: "
  345. "Could not read key from mtp authorization."));
  346. return;
  347. }
  348. keys.push_back(std::make_shared<MTP::AuthKey>(MTP::AuthKey::Type::ReadFromFile, dcId, keyData));
  349. }
  350. };
  351. readKeys(_mtpFields.keys);
  352. readKeys(_mtpKeysToDestroy);
  353. LOG(("MTP Info: "
  354. "read keys, current: %1, to destroy: %2"
  355. ).arg(_mtpFields.keys.size()
  356. ).arg(_mtpKeysToDestroy.size()));
  357. }
  358. void Account::startMtp(std::unique_ptr<MTP::Config> config) {
  359. Expects(!_mtp);
  360. auto fields = base::take(_mtpFields);
  361. fields.config = std::move(config);
  362. fields.deviceModel = Platform::DeviceModelPretty();
  363. fields.systemVersion = Platform::SystemVersionPretty();
  364. _mtp = std::make_unique<MTP::Instance>(
  365. MTP::Instance::Mode::Normal,
  366. std::move(fields));
  367. const auto writingKeys = _mtp->lifetime().make_state<bool>(false);
  368. _mtp->writeKeysRequests(
  369. ) | rpl::filter([=] {
  370. return !*writingKeys;
  371. }) | rpl::start_with_next([=] {
  372. *writingKeys = true;
  373. Ui::PostponeCall(_mtp.get(), [=] {
  374. local().writeMtpData();
  375. *writingKeys = false;
  376. });
  377. }, _mtp->lifetime());
  378. const auto writingConfig = _lifetime.make_state<bool>(false);
  379. rpl::merge(
  380. _mtp->config().updates(),
  381. _mtp->dcOptions().changed() | rpl::to_empty
  382. ) | rpl::filter([=] {
  383. return !*writingConfig;
  384. }) | rpl::start_with_next([=] {
  385. *writingConfig = true;
  386. Ui::PostponeCall(_mtp.get(), [=] {
  387. local().writeMtpConfig();
  388. *writingConfig = false;
  389. });
  390. }, _lifetime);
  391. _mtpFields.mainDcId = _mtp->mainDcId();
  392. _mtp->setUpdatesHandler([=](const MTP::Response &message) {
  393. checkForUpdates(message) || checkForNewSession(message);
  394. });
  395. _mtp->setGlobalFailHandler([=](const MTP::Error &, const MTP::Response &) {
  396. if (const auto session = maybeSession()) {
  397. crl::on_main(session, [=] { logOut(); });
  398. }
  399. });
  400. _mtp->setStateChangedHandler([=](MTP::ShiftedDcId dc, int32 state) {
  401. if (dc == _mtp->mainDcId()) {
  402. Core::App().settings().proxy().connectionTypeChangesNotify();
  403. }
  404. });
  405. _mtp->setSessionResetHandler([=](MTP::ShiftedDcId shiftedDcId) {
  406. if (const auto session = maybeSession()) {
  407. if (shiftedDcId == _mtp->mainDcId()) {
  408. session->updates().getDifference();
  409. }
  410. }
  411. });
  412. if (!_mtpKeysToDestroy.empty()) {
  413. destroyMtpKeys(base::take(_mtpKeysToDestroy));
  414. }
  415. if (_sessionUserId) {
  416. createSession(
  417. _sessionUserId,
  418. base::take(_sessionUserSerialized),
  419. base::take(_sessionUserStreamVersion),
  420. (_storedSessionSettings
  421. ? std::move(_storedSessionSettings)
  422. : std::make_unique<SessionSettings>()));
  423. }
  424. _storedSessionSettings = nullptr;
  425. if (const auto session = maybeSession()) {
  426. // Skip all pending self updates so that we won't local().writeSelf.
  427. session->changes().sendNotifications();
  428. }
  429. _mtpValue = _mtp.get();
  430. }
  431. bool Account::checkForUpdates(const MTP::Response &message) {
  432. auto updates = MTPUpdates();
  433. auto from = message.reply.constData();
  434. if (!updates.read(from, from + message.reply.size())) {
  435. return false;
  436. }
  437. _mtpUpdates.fire(std::move(updates));
  438. return true;
  439. }
  440. bool Account::checkForNewSession(const MTP::Response &message) {
  441. auto newSession = MTPNewSession();
  442. auto from = message.reply.constData();
  443. if (!newSession.read(from, from + message.reply.size())) {
  444. return false;
  445. }
  446. _mtpNewSessionCreated.fire({});
  447. return true;
  448. }
  449. void Account::logOut() {
  450. if (_loggingOut) {
  451. return;
  452. }
  453. _loggingOut = true;
  454. if (_mtp) {
  455. _mtp->logout([=] { loggedOut(); });
  456. } else {
  457. // We log out because we've forgotten passcode.
  458. loggedOut();
  459. }
  460. }
  461. bool Account::loggingOut() const {
  462. return _loggingOut;
  463. }
  464. void Account::forcedLogOut() {
  465. if (sessionExists()) {
  466. resetAuthorizationKeys();
  467. loggedOut();
  468. }
  469. }
  470. void Account::loggedOut() {
  471. _loggingOut = false;
  472. Media::Player::mixer()->stopAndClear();
  473. destroySession(DestroyReason::LoggedOut);
  474. local().reset();
  475. cSetOtherOnline(0);
  476. }
  477. void Account::destroyMtpKeys(MTP::AuthKeysList &&keys) {
  478. Expects(_mtp != nullptr);
  479. if (keys.empty()) {
  480. return;
  481. }
  482. if (_mtpForKeysDestroy) {
  483. _mtpForKeysDestroy->addKeysForDestroy(std::move(keys));
  484. local().writeMtpData();
  485. return;
  486. }
  487. auto destroyFields = MTP::Instance::Fields();
  488. destroyFields.mainDcId = MTP::Instance::Fields::kNoneMainDc;
  489. destroyFields.config = std::make_unique<MTP::Config>(_mtp->config());
  490. destroyFields.keys = std::move(keys);
  491. destroyFields.deviceModel = Platform::DeviceModelPretty();
  492. destroyFields.systemVersion = Platform::SystemVersionPretty();
  493. _mtpForKeysDestroy = std::make_unique<MTP::Instance>(
  494. MTP::Instance::Mode::KeysDestroyer,
  495. std::move(destroyFields));
  496. _mtpForKeysDestroy->writeKeysRequests(
  497. ) | rpl::start_with_next([=] {
  498. local().writeMtpData();
  499. }, _mtpForKeysDestroy->lifetime());
  500. _mtpForKeysDestroy->allKeysDestroyed(
  501. ) | rpl::start_with_next([=] {
  502. LOG(("MTP Info: all keys scheduled for destroy are destroyed."));
  503. crl::on_main(this, [=] {
  504. _mtpForKeysDestroy = nullptr;
  505. local().writeMtpData();
  506. });
  507. }, _mtpForKeysDestroy->lifetime());
  508. }
  509. void Account::suggestMainDcId(MTP::DcId mainDcId) {
  510. Expects(_mtp != nullptr);
  511. _mtp->suggestMainDcId(mainDcId);
  512. if (_mtpFields.mainDcId != MTP::Instance::Fields::kNotSetMainDc) {
  513. _mtpFields.mainDcId = mainDcId;
  514. }
  515. }
  516. void Account::destroyStaleAuthorizationKeys() {
  517. Expects(_mtp != nullptr);
  518. for (const auto &key : _mtp->getKeysForWrite()) {
  519. // Disable this for now.
  520. if (key->type() == MTP::AuthKey::Type::ReadFromFile) {
  521. _mtpKeysToDestroy = _mtp->getKeysForWrite();
  522. LOG(("MTP Info: destroying stale keys, count: %1"
  523. ).arg(_mtpKeysToDestroy.size()));
  524. resetAuthorizationKeys();
  525. return;
  526. }
  527. }
  528. }
  529. void Account::setHandleLoginCode(Fn<void(QString)> callback) {
  530. _handleLoginCode = std::move(callback);
  531. }
  532. void Account::handleLoginCode(const QString &code) const {
  533. if (_handleLoginCode) {
  534. _handleLoginCode(code);
  535. }
  536. }
  537. void Account::resetAuthorizationKeys() {
  538. Expects(_mtp != nullptr);
  539. {
  540. const auto old = base::take(_mtp);
  541. auto config = std::make_unique<MTP::Config>(old->config());
  542. startMtp(std::move(config));
  543. }
  544. local().writeMtpData();
  545. }
  546. } // namespace Main