localstorage.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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 "storage/localstorage.h"
  8. #include "storage/serialize_common.h"
  9. #include "storage/storage_account.h"
  10. #include "storage/details/storage_file_utilities.h"
  11. #include "storage/details/storage_settings_scheme.h"
  12. #include "data/data_session.h"
  13. #include "data/data_document.h"
  14. #include "data/data_document_media.h"
  15. #include "base/platform/base_platform_info.h"
  16. #include "base/random.h"
  17. #include "ui/power_saving.h"
  18. #include "core/update_checker.h"
  19. #include "core/file_location.h"
  20. #include "core/application.h"
  21. #include "core/core_settings.h"
  22. #include "media/audio/media_audio.h"
  23. #include "mtproto/mtproto_config.h"
  24. #include "mtproto/mtproto_dc_options.h"
  25. #include "main/main_domain.h"
  26. #include "main/main_account.h"
  27. #include "main/main_session.h"
  28. #include "window/themes/window_theme.h"
  29. #include "lang/lang_instance.h"
  30. #include <QtCore/QDirIterator>
  31. #ifndef Q_OS_WIN
  32. #include <unistd.h>
  33. #endif // Q_OS_WIN
  34. //extern "C" {
  35. //#include <openssl/evp.h>
  36. //} // extern "C"
  37. namespace Local {
  38. namespace {
  39. constexpr auto kThemeFileSizeLimit = 5 * 1024 * 1024;
  40. constexpr auto kFileLoaderQueueStopTimeout = crl::time(5000);
  41. constexpr auto kSavedBackgroundFormat = QImage::Format_ARGB32_Premultiplied;
  42. constexpr auto kWallPaperLegacySerializeTagId = int32(-111);
  43. constexpr auto kWallPaperSerializeTagId = int32(-112);
  44. constexpr auto kWallPaperSidesLimit = 10'000;
  45. const auto kThemeNewPathRelativeTag = u"special://new_tag"_q;
  46. using namespace Storage::details;
  47. using Storage::FileKey;
  48. using Database = Storage::Cache::Database;
  49. QString _basePath, _userBasePath, _userDbPath;
  50. TaskQueue *_localLoader = nullptr;
  51. QByteArray _settingsSalt;
  52. auto OldKey = MTP::AuthKeyPtr();
  53. auto SettingsKey = MTP::AuthKeyPtr();
  54. FileKey _themeKeyDay = 0;
  55. FileKey _themeKeyNight = 0;
  56. // Theme key legacy may be read in start() with settings.
  57. // But it should be moved to keyDay or keyNight inside InitialLoadTheme()
  58. // and never used after.
  59. FileKey _themeKeyLegacy = 0;
  60. FileKey _langPackKey = 0;
  61. FileKey _languagesKey = 0;
  62. FileKey _backgroundKeyDay = 0;
  63. FileKey _backgroundKeyNight = 0;
  64. bool _useGlobalBackgroundKeys = false;
  65. bool _backgroundCanWrite = true;
  66. int32 _oldSettingsVersion = 0;
  67. bool _settingsRewriteNeeded = false;
  68. bool _settingsWriteAllowed = false;
  69. enum class WriteMapWhen {
  70. Now,
  71. Fast,
  72. Soon,
  73. };
  74. bool CheckStreamStatus(QDataStream &stream) {
  75. if (stream.status() != QDataStream::Ok) {
  76. LOG(("Bad data stream status: %1").arg(stream.status()));
  77. return false;
  78. }
  79. return true;
  80. }
  81. [[nodiscard]] const MTP::Config &LookupFallbackConfig() {
  82. static const auto lookupConfig = [](not_null<Main::Account*> account) {
  83. const auto mtp = &account->mtp();
  84. const auto production = MTP::Environment::Production;
  85. return (mtp->environment() == production)
  86. ? &mtp->config()
  87. : nullptr;
  88. };
  89. const auto &app = Core::App();
  90. const auto &domain = app.domain();
  91. if (!domain.started()) {
  92. return app.fallbackProductionConfig();
  93. }
  94. if (const auto result = lookupConfig(&app.activeAccount())) {
  95. return *result;
  96. }
  97. for (const auto &[_, account] : domain.accounts()) {
  98. if (const auto result = lookupConfig(account.get())) {
  99. return *result;
  100. }
  101. }
  102. return app.fallbackProductionConfig();
  103. }
  104. void applyReadContext(ReadSettingsContext &&context) {
  105. ApplyReadFallbackConfig(context);
  106. DEBUG_LOG(("Theme: applying context, legacy: %1, day: %2, night: %3"
  107. ).arg(context.themeKeyLegacy
  108. ).arg(context.themeKeyDay
  109. ).arg(context.themeKeyNight));
  110. _themeKeyLegacy = context.themeKeyLegacy;
  111. _themeKeyDay = context.themeKeyDay;
  112. _themeKeyNight = context.themeKeyNight;
  113. _backgroundKeyDay = context.backgroundKeyDay;
  114. _backgroundKeyNight = context.backgroundKeyNight;
  115. _useGlobalBackgroundKeys = context.backgroundKeysRead;
  116. _langPackKey = context.langPackKey;
  117. _languagesKey = context.languagesKey;
  118. }
  119. bool _readOldSettings(bool remove, ReadSettingsContext &context) {
  120. bool result = false;
  121. auto file = QFile(cWorkingDir() + u"tdata/config"_q);
  122. if (file.open(QIODevice::ReadOnly)) {
  123. LOG(("App Info: reading old config..."));
  124. QDataStream stream(&file);
  125. stream.setVersion(QDataStream::Qt_5_1);
  126. qint32 version = 0;
  127. while (!stream.atEnd()) {
  128. quint32 blockId;
  129. stream >> blockId;
  130. if (!CheckStreamStatus(stream)) break;
  131. if (blockId == dbiVersion) {
  132. stream >> version;
  133. if (!CheckStreamStatus(stream)) break;
  134. if (version > AppVersion) break;
  135. } else if (!ReadSetting(blockId, stream, version, context)) {
  136. break;
  137. }
  138. }
  139. file.close();
  140. result = true;
  141. }
  142. if (remove) file.remove();
  143. return result;
  144. }
  145. void _readOldUserSettingsFields(
  146. QIODevice *device,
  147. qint32 &version,
  148. ReadSettingsContext &context) {
  149. QDataStream stream(device);
  150. stream.setVersion(QDataStream::Qt_5_1);
  151. while (!stream.atEnd()) {
  152. quint32 blockId;
  153. stream >> blockId;
  154. if (!CheckStreamStatus(stream)) {
  155. break;
  156. }
  157. if (blockId == dbiVersion) {
  158. stream >> version;
  159. if (!CheckStreamStatus(stream)) {
  160. break;
  161. }
  162. if (version > AppVersion) return;
  163. } else if (blockId == dbiEncryptedWithSalt) {
  164. QByteArray salt, data, decrypted;
  165. stream >> salt >> data;
  166. if (!CheckStreamStatus(stream)) {
  167. break;
  168. }
  169. if (salt.size() != 32) {
  170. LOG(("App Error: bad salt in old user config encrypted part, size: %1").arg(salt.size()));
  171. continue;
  172. }
  173. OldKey = CreateLegacyLocalKey(QByteArray(), salt);
  174. if (data.size() <= 16 || (data.size() & 0x0F)) {
  175. LOG(("App Error: bad encrypted part size in old user config: %1").arg(data.size()));
  176. continue;
  177. }
  178. uint32 fullDataLen = data.size() - 16;
  179. decrypted.resize(fullDataLen);
  180. const char *dataKey = data.constData(), *encrypted = data.constData() + 16;
  181. aesDecryptLocal(encrypted, decrypted.data(), fullDataLen, OldKey, dataKey);
  182. uchar sha1Buffer[20];
  183. if (memcmp(hashSha1(decrypted.constData(), decrypted.size(), sha1Buffer), dataKey, 16)) {
  184. LOG(("App Error: bad decrypt key, data from old user config not decrypted"));
  185. continue;
  186. }
  187. uint32 dataLen = *(const uint32*)decrypted.constData();
  188. if (dataLen > uint32(decrypted.size()) || dataLen <= fullDataLen - 16 || dataLen < 4) {
  189. LOG(("App Error: bad decrypted part size in old user config: %1, fullDataLen: %2, decrypted size: %3").arg(dataLen).arg(fullDataLen).arg(decrypted.size()));
  190. continue;
  191. }
  192. decrypted.resize(dataLen);
  193. QBuffer decryptedStream(&decrypted);
  194. decryptedStream.open(QIODevice::ReadOnly);
  195. decryptedStream.seek(4); // skip size
  196. LOG(("App Info: reading encrypted old user config..."));
  197. _readOldUserSettingsFields(&decryptedStream, version, context);
  198. } else if (!ReadSetting(blockId, stream, version, context)) {
  199. return;
  200. }
  201. }
  202. }
  203. bool _readOldUserSettings(bool remove, ReadSettingsContext &context) {
  204. bool result = false;
  205. // We dropped old test authorizations when migrated to multi auth.
  206. //const auto testPrefix = (cTestMode() ? u"_test"_q : QString());
  207. const auto testPrefix = QString();
  208. QFile file(cWorkingDir() + cDataFile() + testPrefix + u"_config"_q);
  209. if (file.open(QIODevice::ReadOnly)) {
  210. LOG(("App Info: reading old user config..."));
  211. qint32 version = 0;
  212. _readOldUserSettingsFields(&file, version, context);
  213. file.close();
  214. result = true;
  215. }
  216. if (remove) file.remove();
  217. return result;
  218. }
  219. void _readOldMtpDataFields(
  220. QIODevice *device,
  221. qint32 &version,
  222. ReadSettingsContext &context) {
  223. QDataStream stream(device);
  224. stream.setVersion(QDataStream::Qt_5_1);
  225. while (!stream.atEnd()) {
  226. quint32 blockId;
  227. stream >> blockId;
  228. if (!CheckStreamStatus(stream)) {
  229. break;
  230. }
  231. if (blockId == dbiVersion) {
  232. stream >> version;
  233. if (!CheckStreamStatus(stream)) {
  234. break;
  235. }
  236. if (version > AppVersion) return;
  237. } else if (blockId == dbiEncrypted) {
  238. QByteArray data, decrypted;
  239. stream >> data;
  240. if (!CheckStreamStatus(stream)) {
  241. break;
  242. }
  243. if (!OldKey) {
  244. LOG(("MTP Error: reading old encrypted keys without old key!"));
  245. continue;
  246. }
  247. if (data.size() <= 16 || (data.size() & 0x0F)) {
  248. LOG(("MTP Error: bad encrypted part size in old keys: %1").arg(data.size()));
  249. continue;
  250. }
  251. uint32 fullDataLen = data.size() - 16;
  252. decrypted.resize(fullDataLen);
  253. const char *dataKey = data.constData(), *encrypted = data.constData() + 16;
  254. aesDecryptLocal(encrypted, decrypted.data(), fullDataLen, OldKey, dataKey);
  255. uchar sha1Buffer[20];
  256. if (memcmp(hashSha1(decrypted.constData(), decrypted.size(), sha1Buffer), dataKey, 16)) {
  257. LOG(("MTP Error: bad decrypt key, data from old keys not decrypted"));
  258. continue;
  259. }
  260. uint32 dataLen = *(const uint32*)decrypted.constData();
  261. if (dataLen > uint32(decrypted.size()) || dataLen <= fullDataLen - 16 || dataLen < 4) {
  262. LOG(("MTP Error: bad decrypted part size in old keys: %1, fullDataLen: %2, decrypted size: %3").arg(dataLen).arg(fullDataLen).arg(decrypted.size()));
  263. continue;
  264. }
  265. decrypted.resize(dataLen);
  266. QBuffer decryptedStream(&decrypted);
  267. decryptedStream.open(QIODevice::ReadOnly);
  268. decryptedStream.seek(4); // skip size
  269. LOG(("App Info: reading encrypted old keys..."));
  270. _readOldMtpDataFields(&decryptedStream, version, context);
  271. } else if (!ReadSetting(blockId, stream, version, context)) {
  272. return;
  273. }
  274. }
  275. }
  276. bool _readOldMtpData(bool remove, ReadSettingsContext &context) {
  277. bool result = false;
  278. // We dropped old test authorizations when migrated to multi auth.
  279. //const auto testPostfix = (cTestMode() ? u"_test"_q : QString());
  280. const auto testPostfix = QString();
  281. QFile file(cWorkingDir() + cDataFile() + testPostfix);
  282. if (file.open(QIODevice::ReadOnly)) {
  283. LOG(("App Info: reading old keys..."));
  284. qint32 version = 0;
  285. _readOldMtpDataFields(&file, version, context);
  286. file.close();
  287. result = true;
  288. }
  289. if (remove) file.remove();
  290. return result;
  291. }
  292. } // namespace
  293. void sync() {
  294. Storage::details::Sync();
  295. }
  296. void finish() {
  297. delete base::take(_localLoader);
  298. Storage::details::Finish();
  299. }
  300. void InitialLoadTheme();
  301. bool ApplyDefaultNightMode();
  302. void readLangPack();
  303. void start() {
  304. Expects(_basePath.isEmpty());
  305. _localLoader = new TaskQueue(kFileLoaderQueueStopTimeout);
  306. _basePath = cWorkingDir() + u"tdata/"_q;
  307. if (!QDir().exists(_basePath)) QDir().mkpath(_basePath);
  308. ReadSettingsContext context;
  309. FileReadDescriptor settingsData;
  310. // We dropped old test authorizations when migrated to multi auth.
  311. //const auto name = cTestMode() ? u"settings_test"_q : u"settings"_q;
  312. const auto name = u"settings"_q;
  313. if (!ReadFile(settingsData, name, _basePath)) {
  314. _readOldSettings(true, context);
  315. _readOldUserSettings(false, context); // needed further in _readUserSettings
  316. _readOldMtpData(false, context); // needed further in _readMtpData
  317. applyReadContext(std::move(context));
  318. _settingsRewriteNeeded = true;
  319. ApplyDefaultNightMode();
  320. return;
  321. }
  322. LOG(("App Info: reading settings..."));
  323. QByteArray salt, settingsEncrypted;
  324. settingsData.stream >> salt >> settingsEncrypted;
  325. if (!CheckStreamStatus(settingsData.stream)) {
  326. return writeSettings();
  327. }
  328. if (salt.size() != LocalEncryptSaltSize) {
  329. LOG(("App Error: bad salt in settings file, size: %1").arg(salt.size()));
  330. return writeSettings();
  331. }
  332. SettingsKey = CreateLegacyLocalKey(QByteArray(), salt);
  333. EncryptedDescriptor settings;
  334. if (!DecryptLocal(settings, settingsEncrypted, SettingsKey)) {
  335. LOG(("App Error: could not decrypt settings from settings file..."));
  336. return writeSettings();
  337. }
  338. LOG(("App Info: reading encrypted settings..."));
  339. while (!settings.stream.atEnd()) {
  340. quint32 blockId;
  341. settings.stream >> blockId;
  342. if (!CheckStreamStatus(settings.stream)) {
  343. return writeSettings();
  344. }
  345. if (!ReadSetting(blockId, settings.stream, settingsData.version, context)) {
  346. return writeSettings();
  347. }
  348. }
  349. _oldSettingsVersion = settingsData.version;
  350. _settingsSalt = salt;
  351. applyReadContext(std::move(context));
  352. if (context.legacyRead) {
  353. writeSettings();
  354. }
  355. InitialLoadTheme();
  356. if (context.tileRead && _useGlobalBackgroundKeys) {
  357. Window::Theme::Background()->setTileDayValue(context.tileDay);
  358. Window::Theme::Background()->setTileNightValue(context.tileNight);
  359. }
  360. readLangPack();
  361. }
  362. void writeSettings() {
  363. if (!_settingsWriteAllowed) {
  364. _settingsRewriteNeeded = true;
  365. // We need to generate SettingsKey anyway,
  366. // for the moveLegacyBackground to work.
  367. if (SettingsKey) {
  368. return;
  369. }
  370. }
  371. if (_basePath.isEmpty()) {
  372. LOG(("App Error: _basePath is empty in writeSettings()"));
  373. return;
  374. }
  375. if (!QDir().exists(_basePath)) QDir().mkpath(_basePath);
  376. // We dropped old test authorizations when migrated to multi auth.
  377. //const auto name = cTestMode() ? u"settings_test"_q : u"settings"_q;
  378. const auto name = u"settings"_q;
  379. FileWriteDescriptor settings(name, _basePath);
  380. if (_settingsSalt.isEmpty() || !SettingsKey) {
  381. _settingsSalt.resize(LocalEncryptSaltSize);
  382. base::RandomFill(_settingsSalt.data(), _settingsSalt.size());
  383. SettingsKey = CreateLegacyLocalKey(QByteArray(), _settingsSalt);
  384. }
  385. settings.writeData(_settingsSalt);
  386. if (!_settingsWriteAllowed) {
  387. EncryptedDescriptor data(0);
  388. settings.writeEncrypted(data, SettingsKey);
  389. return;
  390. }
  391. const auto configSerialized = LookupFallbackConfig().serialize();
  392. const auto applicationSettings = Core::App().settings().serialize();
  393. quint32 size = 9 * (sizeof(quint32) + sizeof(qint32));
  394. size += sizeof(quint32) + Serialize::bytearraySize(configSerialized);
  395. size += sizeof(quint32) + Serialize::bytearraySize(applicationSettings);
  396. size += sizeof(quint32) + Serialize::stringSize(cDialogLastPath());
  397. // Theme keys and night mode.
  398. size += sizeof(quint32) + sizeof(quint64) * 2 + sizeof(quint32);
  399. size += sizeof(quint32) + sizeof(quint64) * 2;
  400. if (_langPackKey) {
  401. size += sizeof(quint32) + sizeof(quint64);
  402. }
  403. size += sizeof(quint32) + sizeof(qint32) * 8;
  404. const auto powerSaving = PowerSaving::Current().value();
  405. EncryptedDescriptor data(size);
  406. data.stream << quint32(dbiAutoStart) << qint32(cAutoStart());
  407. data.stream << quint32(dbiStartMinimized) << qint32(cStartMinimized());
  408. data.stream << quint32(dbiSendToMenu) << qint32(cSendToMenu());
  409. data.stream << quint32(dbiSeenTrayTooltip) << qint32(cSeenTrayTooltip());
  410. data.stream << quint32(dbiAutoUpdate) << qint32(cAutoUpdate());
  411. data.stream << quint32(dbiLastUpdateCheck) << qint32(cLastUpdateCheck());
  412. data.stream << quint32(dbiScalePercent) << qint32(cConfigScale());
  413. data.stream << quint32(dbiFallbackProductionConfig) << configSerialized;
  414. data.stream << quint32(dbiApplicationSettings) << applicationSettings;
  415. data.stream << quint32(dbiDialogLastPath) << cDialogLastPath();
  416. data.stream << quint32(dbiPowerSaving) << qint32(powerSaving);
  417. data.stream
  418. << quint32(dbiThemeKey)
  419. << quint64(_themeKeyDay)
  420. << quint64(_themeKeyNight)
  421. << quint32(Window::Theme::IsNightMode() ? 1 : 0);
  422. if (_useGlobalBackgroundKeys) {
  423. data.stream
  424. << quint32(dbiBackgroundKey)
  425. << quint64(_backgroundKeyDay)
  426. << quint64(_backgroundKeyNight);
  427. data.stream
  428. << quint32(dbiTileBackground)
  429. << qint32(Window::Theme::Background()->tileDay() ? 1 : 0)
  430. << qint32(Window::Theme::Background()->tileNight() ? 1 : 0);
  431. }
  432. if (_langPackKey) {
  433. data.stream << quint32(dbiLangPackKey) << quint64(_langPackKey);
  434. }
  435. if (_languagesKey) {
  436. data.stream << quint32(dbiLanguagesKey) << quint64(_languagesKey);
  437. }
  438. settings.writeEncrypted(data, SettingsKey);
  439. }
  440. void rewriteSettingsIfNeeded() {
  441. if (_settingsWriteAllowed) {
  442. return;
  443. }
  444. _settingsWriteAllowed = true;
  445. if (_oldSettingsVersion < AppVersion || _settingsRewriteNeeded) {
  446. writeSettings();
  447. }
  448. }
  449. const QString &AutoupdatePrefix(const QString &replaceWith = {}) {
  450. Expects(!Core::UpdaterDisabled());
  451. static auto value = QString();
  452. if (!replaceWith.isEmpty()) {
  453. value = replaceWith;
  454. }
  455. return value;
  456. }
  457. QString autoupdatePrefixFile() {
  458. Expects(!Core::UpdaterDisabled());
  459. return cWorkingDir() + "tdata/prefix";
  460. }
  461. const QString &readAutoupdatePrefixRaw() {
  462. Expects(!Core::UpdaterDisabled());
  463. const auto &result = AutoupdatePrefix();
  464. if (!result.isEmpty()) {
  465. return result;
  466. }
  467. QFile f(autoupdatePrefixFile());
  468. if (f.open(QIODevice::ReadOnly)) {
  469. const auto value = QString::fromUtf8(f.readAll());
  470. if (!value.isEmpty()) {
  471. return AutoupdatePrefix(value);
  472. }
  473. }
  474. return AutoupdatePrefix("https://td.telegram.org");
  475. }
  476. void writeAutoupdatePrefix(const QString &prefix) {
  477. if (Core::UpdaterDisabled()) {
  478. return;
  479. }
  480. const auto current = readAutoupdatePrefixRaw();
  481. if (current != prefix) {
  482. AutoupdatePrefix(prefix);
  483. QFile f(autoupdatePrefixFile());
  484. if (f.open(QIODevice::WriteOnly)) {
  485. f.write(prefix.toUtf8());
  486. f.close();
  487. }
  488. if (cAutoUpdate()) {
  489. Core::UpdateChecker checker;
  490. checker.start();
  491. }
  492. }
  493. }
  494. QString readAutoupdatePrefix() {
  495. Expects(!Core::UpdaterDisabled());
  496. static const auto RegExp = QRegularExpression("/+$");
  497. auto result = readAutoupdatePrefixRaw();
  498. return result.replace(RegExp, QString());
  499. }
  500. void writeBackground(const Data::WallPaper &paper, const QImage &image) {
  501. Expects(_settingsWriteAllowed);
  502. if (!_backgroundCanWrite) {
  503. return;
  504. }
  505. _useGlobalBackgroundKeys = true;
  506. auto &backgroundKey = Window::Theme::IsNightMode()
  507. ? _backgroundKeyNight
  508. : _backgroundKeyDay;
  509. auto imageData = QByteArray();
  510. if (!image.isNull()) {
  511. const auto width = qint32(image.width());
  512. const auto height = qint32(image.height());
  513. const auto perpixel = (image.depth() >> 3);
  514. const auto srcperline = image.bytesPerLine();
  515. const auto srcsize = srcperline * height;
  516. const auto dstperline = width * perpixel;
  517. const auto dstsize = dstperline * height;
  518. const auto copy = (image.format() != kSavedBackgroundFormat)
  519. ? image.convertToFormat(kSavedBackgroundFormat)
  520. : image;
  521. imageData.resize(2 * sizeof(qint32) + dstsize);
  522. auto dst = bytes::make_detached_span(imageData);
  523. bytes::copy(dst, bytes::object_as_span(&width));
  524. dst = dst.subspan(sizeof(qint32));
  525. bytes::copy(dst, bytes::object_as_span(&height));
  526. dst = dst.subspan(sizeof(qint32));
  527. const auto src = bytes::make_span(copy.constBits(), srcsize);
  528. if (srcsize == dstsize) {
  529. bytes::copy(dst, src);
  530. } else {
  531. for (auto y = 0; y != height; ++y) {
  532. bytes::copy(dst, src.subspan(y * srcperline, dstperline));
  533. dst = dst.subspan(dstperline);
  534. }
  535. }
  536. }
  537. if (!backgroundKey) {
  538. backgroundKey = GenerateKey(_basePath);
  539. writeSettings();
  540. }
  541. const auto serialized = paper.serialize();
  542. quint32 size = sizeof(qint32)
  543. + Serialize::bytearraySize(serialized)
  544. + Serialize::bytearraySize(imageData);
  545. EncryptedDescriptor data(size);
  546. data.stream
  547. << qint32(kWallPaperSerializeTagId)
  548. << serialized
  549. << imageData;
  550. FileWriteDescriptor file(backgroundKey, _basePath);
  551. file.writeEncrypted(data, SettingsKey);
  552. }
  553. bool readBackground() {
  554. FileReadDescriptor bg;
  555. auto &backgroundKey = Window::Theme::IsNightMode()
  556. ? _backgroundKeyNight
  557. : _backgroundKeyDay;
  558. if (!ReadEncryptedFile(bg, backgroundKey, _basePath, SettingsKey)) {
  559. if (backgroundKey) {
  560. ClearKey(backgroundKey, _basePath);
  561. backgroundKey = 0;
  562. writeSettings();
  563. }
  564. return false;
  565. }
  566. qint32 legacyId = 0;
  567. bg.stream >> legacyId;
  568. const auto paper = [&] {
  569. if (legacyId == kWallPaperLegacySerializeTagId) {
  570. quint64 id = 0;
  571. quint64 accessHash = 0;
  572. quint32 flags = 0;
  573. QString slug;
  574. bg.stream
  575. >> id
  576. >> accessHash
  577. >> flags
  578. >> slug;
  579. return Data::WallPaper::FromLegacySerialized(
  580. id,
  581. accessHash,
  582. flags,
  583. slug);
  584. } else if (legacyId == kWallPaperSerializeTagId) {
  585. QByteArray serialized;
  586. bg.stream >> serialized;
  587. return Data::WallPaper::FromSerialized(serialized);
  588. } else {
  589. return Data::WallPaper::FromLegacyId(legacyId);
  590. }
  591. }();
  592. if (bg.stream.status() != QDataStream::Ok || !paper) {
  593. return false;
  594. }
  595. QByteArray imageData;
  596. bg.stream >> imageData;
  597. const auto isOldEmptyImage = (bg.stream.status() != QDataStream::Ok);
  598. if (isOldEmptyImage
  599. || Data::IsLegacy1DefaultWallPaper(*paper)
  600. || (Data::IsLegacy2DefaultWallPaper(*paper) && bg.version < 3000000)
  601. || (Data::IsLegacy3DefaultWallPaper(*paper) && bg.version < 3000000)
  602. || (Data::IsLegacy4DefaultWallPaper(*paper) && bg.version < 3000000)
  603. || Data::IsDefaultWallPaper(*paper)) {
  604. _backgroundCanWrite = false;
  605. if (isOldEmptyImage || bg.version < 3000000) {
  606. Window::Theme::Background()->set(Data::DefaultWallPaper());
  607. } else {
  608. Window::Theme::Background()->set(*paper);
  609. }
  610. _backgroundCanWrite = true;
  611. return true;
  612. } else if (Data::IsThemeWallPaper(*paper) && imageData.isEmpty()) {
  613. _backgroundCanWrite = false;
  614. Window::Theme::Background()->set(*paper);
  615. _backgroundCanWrite = true;
  616. return true;
  617. }
  618. auto image = QImage();
  619. if (legacyId == kWallPaperSerializeTagId) {
  620. const auto perpixel = 4;
  621. auto src = bytes::make_span(imageData);
  622. auto width = qint32();
  623. auto height = qint32();
  624. if (src.size() > 2 * sizeof(qint32)) {
  625. bytes::copy(
  626. bytes::object_as_span(&width),
  627. src.subspan(0, sizeof(qint32)));
  628. src = src.subspan(sizeof(qint32));
  629. bytes::copy(
  630. bytes::object_as_span(&height),
  631. src.subspan(0, sizeof(qint32)));
  632. src = src.subspan(sizeof(qint32));
  633. if (width + height <= kWallPaperSidesLimit
  634. && src.size() == width * height * perpixel) {
  635. image = QImage(
  636. width,
  637. height,
  638. QImage::Format_ARGB32_Premultiplied);
  639. if (!image.isNull()) {
  640. const auto srcperline = width * perpixel;
  641. const auto srcsize = srcperline * height;
  642. const auto dstperline = image.bytesPerLine();
  643. const auto dstsize = dstperline * height;
  644. Assert(srcsize == dstsize);
  645. bytes::copy(
  646. bytes::make_span(image.bits(), dstsize),
  647. src);
  648. }
  649. }
  650. }
  651. } else {
  652. auto buffer = QBuffer(&imageData);
  653. auto reader = QImageReader(&buffer);
  654. reader.setAutoTransform(true);
  655. if (!reader.read(&image)) {
  656. image = QImage();
  657. }
  658. }
  659. if (!image.isNull() || !paper->backgroundColors().empty()) {
  660. _backgroundCanWrite = false;
  661. Window::Theme::Background()->set(*paper, std::move(image));
  662. _backgroundCanWrite = true;
  663. return true;
  664. }
  665. return false;
  666. }
  667. void moveLegacyBackground(
  668. const QString &fromBasePath,
  669. const MTP::AuthKeyPtr &fromLocalKey,
  670. uint64 legacyBackgroundKeyDay,
  671. uint64 legacyBackgroundKeyNight) {
  672. if (_useGlobalBackgroundKeys
  673. || (!legacyBackgroundKeyDay && !legacyBackgroundKeyNight)) {
  674. return;
  675. }
  676. const auto move = [&](uint64 from, FileKey &to) {
  677. if (!from || to) {
  678. return;
  679. }
  680. to = GenerateKey(_basePath);
  681. FileReadDescriptor read;
  682. if (!ReadEncryptedFile(read, from, fromBasePath, fromLocalKey)) {
  683. return;
  684. }
  685. EncryptedDescriptor data;
  686. data.data = read.data;
  687. FileWriteDescriptor write(to, _basePath);
  688. write.writeEncrypted(data, SettingsKey);
  689. };
  690. move(legacyBackgroundKeyDay, _backgroundKeyDay);
  691. move(legacyBackgroundKeyNight, _backgroundKeyNight);
  692. _useGlobalBackgroundKeys = true;
  693. _settingsRewriteNeeded = true;
  694. }
  695. void reset() {
  696. if (_localLoader) {
  697. _localLoader->stop();
  698. }
  699. Window::Theme::Background()->reset();
  700. _oldSettingsVersion = 0;
  701. Core::App().settings().resetOnLastLogout();
  702. writeSettings();
  703. }
  704. int32 oldSettingsVersion() {
  705. return _oldSettingsVersion;
  706. }
  707. class CountWaveformTask : public Task {
  708. public:
  709. CountWaveformTask(not_null<Data::DocumentMedia*> media)
  710. : _doc(media->owner())
  711. , _loc(_doc->location(true))
  712. , _data(media->bytes())
  713. , _wavemax(0) {
  714. if (_data.isEmpty() && !_loc.accessEnable()) {
  715. _doc = nullptr;
  716. }
  717. }
  718. void process() override {
  719. if (!_doc) return;
  720. _waveform = audioCountWaveform(_loc, _data);
  721. _wavemax = _waveform.empty()
  722. ? char(0)
  723. : *ranges::max_element(_waveform);
  724. }
  725. void finish() override {
  726. if (const auto voice = _doc ? _doc->voice() : nullptr) {
  727. if (!_waveform.isEmpty()) {
  728. voice->waveform = _waveform;
  729. voice->wavemax = _wavemax;
  730. }
  731. if (voice->waveform.isEmpty()) {
  732. voice->waveform.resize(1);
  733. voice->waveform[0] = -2;
  734. voice->wavemax = 0;
  735. } else if (voice->waveform[0] < 0) {
  736. voice->waveform[0] = -2;
  737. voice->wavemax = 0;
  738. }
  739. _doc->owner().requestDocumentViewRepaint(_doc);
  740. }
  741. }
  742. ~CountWaveformTask() {
  743. if (_data.isEmpty() && _doc) {
  744. _loc.accessDisable();
  745. }
  746. }
  747. protected:
  748. DocumentData *_doc = nullptr;
  749. Core::FileLocation _loc;
  750. QByteArray _data;
  751. VoiceWaveform _waveform;
  752. char _wavemax;
  753. };
  754. void countVoiceWaveform(not_null<Data::DocumentMedia*> media) {
  755. const auto document = media->owner();
  756. if (const auto voice = document->voice()) {
  757. if (_localLoader) {
  758. voice->waveform.resize(1 + sizeof(TaskId));
  759. voice->waveform[0] = -1; // counting
  760. TaskId taskId = _localLoader->addTask(
  761. std::make_unique<CountWaveformTask>(media));
  762. memcpy(voice->waveform.data() + 1, &taskId, sizeof(taskId));
  763. }
  764. }
  765. }
  766. void cancelTask(TaskId id) {
  767. if (_localLoader) {
  768. _localLoader->cancelTask(id);
  769. }
  770. }
  771. Window::Theme::Saved readThemeUsingKey(FileKey key) {
  772. using namespace Window::Theme;
  773. FileReadDescriptor theme;
  774. if (!ReadEncryptedFile(theme, key, _basePath, SettingsKey)) {
  775. DEBUG_LOG(("Theme: Could not read file for key: %1").arg(key));
  776. return {};
  777. }
  778. auto tag = QString();
  779. auto result = Saved();
  780. auto &object = result.object;
  781. auto &cache = result.cache;
  782. auto field1 = qint32();
  783. auto field2 = quint32();
  784. theme.stream >> object.content;
  785. theme.stream >> tag >> object.pathAbsolute;
  786. if (tag == kThemeNewPathRelativeTag) {
  787. theme.stream
  788. >> object.pathRelative
  789. >> object.cloud.id
  790. >> object.cloud.accessHash
  791. >> object.cloud.slug
  792. >> object.cloud.title
  793. >> object.cloud.documentId
  794. >> field1;
  795. } else {
  796. object.pathRelative = tag;
  797. }
  798. if (theme.stream.status() != QDataStream::Ok) {
  799. DEBUG_LOG(("Theme: Bad status for key: %1, tag: %2"
  800. ).arg(key
  801. ).arg(tag));
  802. return {};
  803. }
  804. auto ignoreCache = false;
  805. if (!object.cloud.id) {
  806. auto file = QFile(object.pathRelative);
  807. if (object.pathRelative.isEmpty() || !file.exists()) {
  808. file.setFileName(object.pathAbsolute);
  809. }
  810. if (!file.fileName().isEmpty()
  811. && file.exists()
  812. && file.open(QIODevice::ReadOnly)) {
  813. if (file.size() > kThemeFileSizeLimit) {
  814. LOG(("Error: theme file too large: %1 "
  815. "(should be less than 5 MB, got %2)"
  816. ).arg(file.fileName()
  817. ).arg(file.size()));
  818. return {};
  819. }
  820. auto fileContent = file.readAll();
  821. file.close();
  822. if (object.content != fileContent) {
  823. object.content = fileContent;
  824. ignoreCache = true;
  825. }
  826. }
  827. }
  828. int32 cachePaletteChecksum = 0;
  829. int32 cacheContentChecksum = 0;
  830. QByteArray cacheColors;
  831. QByteArray cacheBackground;
  832. theme.stream
  833. >> cachePaletteChecksum
  834. >> cacheContentChecksum
  835. >> cacheColors
  836. >> cacheBackground
  837. >> field2;
  838. if (!ignoreCache) {
  839. if (theme.stream.status() != QDataStream::Ok) {
  840. DEBUG_LOG(("Theme: Bad status for cache, key: %1, tag: %2"
  841. ).arg(key
  842. ).arg(tag));
  843. return {};
  844. }
  845. cache.paletteChecksum = cachePaletteChecksum;
  846. cache.contentChecksum = cacheContentChecksum;
  847. cache.colors = std::move(cacheColors);
  848. cache.background = std::move(cacheBackground);
  849. cache.tiled = ((field2 & quint32(0xFF)) == 1);
  850. }
  851. if (tag == kThemeNewPathRelativeTag) {
  852. object.cloud.createdBy = UserId(
  853. ((quint64(field2) >> 8) << 32) | quint64(quint32(field1)));
  854. }
  855. return result;
  856. }
  857. std::optional<QString> InitialLoadThemeUsingKey(FileKey key) {
  858. auto read = readThemeUsingKey(key);
  859. const auto result = read.object.pathAbsolute;
  860. if (read.object.content.isEmpty()) {
  861. DEBUG_LOG(("Theme: Could not read content for key: %1").arg(key));
  862. }
  863. if (read.object.content.isEmpty()
  864. || !Window::Theme::Initialize(std::move(read))) {
  865. DEBUG_LOG(("Theme: Could not initialized for key: %1").arg(key));
  866. return std::nullopt;
  867. }
  868. return result;
  869. }
  870. void writeTheme(const Window::Theme::Saved &saved) {
  871. using namespace Window::Theme;
  872. if (_themeKeyLegacy) {
  873. DEBUG_LOG(("Theme: skipping write, because legacy: %1"
  874. ).arg(_themeKeyLegacy));
  875. return;
  876. }
  877. auto &themeKey = IsNightMode()
  878. ? _themeKeyNight
  879. : _themeKeyDay;
  880. DEBUG_LOG(("Theme: writing (night: %1), key_day: %2, key_night: %3"
  881. ).arg(Logs::b(IsNightMode())
  882. ).arg(_themeKeyDay
  883. ).arg(_themeKeyNight));
  884. if (saved.object.content.isEmpty()) {
  885. if (themeKey) {
  886. if (IsNightMode()) {
  887. DEBUG_LOG(("Theme: cleared for night mode."));
  888. SetNightModeValue(false);
  889. }
  890. ClearKey(themeKey, _basePath);
  891. themeKey = 0;
  892. writeSettings();
  893. }
  894. return;
  895. }
  896. if (!themeKey) {
  897. themeKey = GenerateKey(_basePath);
  898. writeSettings();
  899. }
  900. const auto &object = saved.object;
  901. const auto &cache = saved.cache;
  902. const auto tag = QString(kThemeNewPathRelativeTag);
  903. quint32 size = Serialize::bytearraySize(object.content)
  904. + Serialize::stringSize(tag)
  905. + Serialize::stringSize(object.pathAbsolute)
  906. + Serialize::stringSize(object.pathRelative)
  907. + sizeof(uint64) * 3
  908. + Serialize::stringSize(object.cloud.slug)
  909. + Serialize::stringSize(object.cloud.title)
  910. + sizeof(qint32)
  911. + sizeof(qint32) * 2
  912. + Serialize::bytearraySize(cache.colors)
  913. + Serialize::bytearraySize(cache.background)
  914. + sizeof(quint32);
  915. const auto bareCreatedById = object.cloud.createdBy.bare;
  916. Assert((bareCreatedById & PeerId::kChatTypeMask) == bareCreatedById);
  917. const auto field1 = qint32(quint32(bareCreatedById & 0xFFFFFFFFULL));
  918. const auto field2 = quint32(cache.tiled ? 1 : 0)
  919. | (quint32(bareCreatedById >> 32) << 8);
  920. EncryptedDescriptor data(size);
  921. data.stream
  922. << object.content
  923. << tag
  924. << object.pathAbsolute
  925. << object.pathRelative
  926. << object.cloud.id
  927. << object.cloud.accessHash
  928. << object.cloud.slug
  929. << object.cloud.title
  930. << object.cloud.documentId
  931. << field1
  932. << cache.paletteChecksum
  933. << cache.contentChecksum
  934. << cache.colors
  935. << cache.background
  936. << field2;
  937. FileWriteDescriptor file(themeKey, _basePath);
  938. file.writeEncrypted(data, SettingsKey);
  939. }
  940. void clearTheme() {
  941. writeTheme(Window::Theme::Saved());
  942. }
  943. void InitialLoadTheme() {
  944. const auto key = (_themeKeyLegacy != 0)
  945. ? _themeKeyLegacy
  946. : (Window::Theme::IsNightMode()
  947. ? _themeKeyNight
  948. : _themeKeyDay);
  949. DEBUG_LOG(("Theme: initial load (night: %1), "
  950. "key_legacy: %2, key_day: %3, key_night: %4"
  951. ).arg(Logs::b(Window::Theme::IsNightMode())
  952. ).arg(_themeKeyLegacy
  953. ).arg(_themeKeyDay
  954. ).arg(_themeKeyNight));
  955. if (!key) {
  956. if (Window::Theme::IsNightMode()) {
  957. DEBUG_LOG(("Theme: zero key for night mode."));
  958. Window::Theme::SetNightModeValue(false);
  959. }
  960. return;
  961. } else if (const auto path = InitialLoadThemeUsingKey(key)) {
  962. DEBUG_LOG(("Theme: loaded with result: %1").arg(*path));
  963. if (_themeKeyLegacy) {
  964. Window::Theme::SetNightModeValue(*path
  965. == Window::Theme::NightThemePath());
  966. (Window::Theme::IsNightMode()
  967. ? _themeKeyNight
  968. : _themeKeyDay) = base::take(_themeKeyLegacy);
  969. DEBUG_LOG(("Theme: now (night: %1), "
  970. "key_legacy: %2, key_day: %3, key_night: %4 (path: %5)"
  971. ).arg(Logs::b(Window::Theme::IsNightMode())
  972. ).arg(_themeKeyLegacy
  973. ).arg(_themeKeyDay
  974. ).arg(_themeKeyNight
  975. ).arg(*path));
  976. }
  977. } else {
  978. DEBUG_LOG(("Theme: could not load, clearing.."));
  979. clearTheme();
  980. }
  981. }
  982. bool ApplyDefaultNightMode() {
  983. const auto NightByDefault = Platform::IsMacStoreBuild();
  984. if (!NightByDefault
  985. || Window::Theme::IsNightMode()
  986. || _themeKeyDay
  987. || _themeKeyNight
  988. || _themeKeyLegacy) {
  989. return false;
  990. }
  991. Core::App().startSettingsAndBackground();
  992. Window::Theme::ToggleNightMode();
  993. Window::Theme::KeepApplied();
  994. return true;
  995. }
  996. Window::Theme::Saved readThemeAfterSwitch() {
  997. const auto key = Window::Theme::IsNightMode()
  998. ? _themeKeyNight
  999. : _themeKeyDay;
  1000. return readThemeUsingKey(key);
  1001. }
  1002. void readLangPack() {
  1003. FileReadDescriptor langpack;
  1004. if (!_langPackKey || !ReadEncryptedFile(langpack, _langPackKey, _basePath, SettingsKey)) {
  1005. return;
  1006. }
  1007. auto data = QByteArray();
  1008. langpack.stream >> data;
  1009. if (langpack.stream.status() == QDataStream::Ok) {
  1010. Lang::GetInstance().fillFromSerialized(data, langpack.version);
  1011. }
  1012. }
  1013. void writeLangPack() {
  1014. auto langpack = Lang::GetInstance().serialize();
  1015. if (!_langPackKey) {
  1016. _langPackKey = GenerateKey(_basePath);
  1017. writeSettings();
  1018. }
  1019. EncryptedDescriptor data(Serialize::bytearraySize(langpack));
  1020. data.stream << langpack;
  1021. FileWriteDescriptor file(_langPackKey, _basePath);
  1022. file.writeEncrypted(data, SettingsKey);
  1023. }
  1024. void saveRecentLanguages(const std::vector<Lang::Language> &list) {
  1025. if (list.empty()) {
  1026. if (_languagesKey) {
  1027. ClearKey(_languagesKey, _basePath);
  1028. _languagesKey = 0;
  1029. writeSettings();
  1030. }
  1031. return;
  1032. }
  1033. auto size = sizeof(qint32);
  1034. for (const auto &language : list) {
  1035. size += Serialize::stringSize(language.id)
  1036. + Serialize::stringSize(language.pluralId)
  1037. + Serialize::stringSize(language.baseId)
  1038. + Serialize::stringSize(language.name)
  1039. + Serialize::stringSize(language.nativeName);
  1040. }
  1041. if (!_languagesKey) {
  1042. _languagesKey = GenerateKey(_basePath);
  1043. writeSettings();
  1044. }
  1045. EncryptedDescriptor data(size);
  1046. data.stream << qint32(list.size());
  1047. for (const auto &language : list) {
  1048. data.stream
  1049. << language.id
  1050. << language.pluralId
  1051. << language.baseId
  1052. << language.name
  1053. << language.nativeName;
  1054. }
  1055. FileWriteDescriptor file(_languagesKey, _basePath);
  1056. file.writeEncrypted(data, SettingsKey);
  1057. }
  1058. void pushRecentLanguage(const Lang::Language &language) {
  1059. if (language.id.startsWith('#')) {
  1060. return;
  1061. }
  1062. auto list = readRecentLanguages();
  1063. list.erase(
  1064. ranges::remove_if(
  1065. list,
  1066. [&](const Lang::Language &v) { return (v.id == language.id); }),
  1067. end(list));
  1068. list.insert(list.begin(), language);
  1069. saveRecentLanguages(list);
  1070. }
  1071. void removeRecentLanguage(const QString &id) {
  1072. auto list = readRecentLanguages();
  1073. list.erase(
  1074. ranges::remove_if(
  1075. list,
  1076. [&](const Lang::Language &v) { return (v.id == id); }),
  1077. end(list));
  1078. saveRecentLanguages(list);
  1079. }
  1080. std::vector<Lang::Language> readRecentLanguages() {
  1081. FileReadDescriptor languages;
  1082. if (!_languagesKey || !ReadEncryptedFile(languages, _languagesKey, _basePath, SettingsKey)) {
  1083. return {};
  1084. }
  1085. qint32 count = 0;
  1086. languages.stream >> count;
  1087. if (count <= 0) {
  1088. return {};
  1089. }
  1090. auto result = std::vector<Lang::Language>();
  1091. result.reserve(count);
  1092. for (auto i = 0; i != count; ++i) {
  1093. auto language = Lang::Language();
  1094. languages.stream
  1095. >> language.id
  1096. >> language.pluralId
  1097. >> language.baseId
  1098. >> language.name
  1099. >> language.nativeName;
  1100. result.push_back(language);
  1101. }
  1102. if (languages.stream.status() != QDataStream::Ok) {
  1103. return {};
  1104. }
  1105. return result;
  1106. }
  1107. Window::Theme::Object ReadThemeContent() {
  1108. using namespace Window::Theme;
  1109. auto &themeKey = IsNightMode() ? _themeKeyNight : _themeKeyDay;
  1110. if (!themeKey) {
  1111. return Object();
  1112. }
  1113. FileReadDescriptor theme;
  1114. if (!ReadEncryptedFile(theme, themeKey, _basePath, SettingsKey)) {
  1115. return Object();
  1116. }
  1117. QByteArray content;
  1118. QString pathRelative, pathAbsolute;
  1119. theme.stream >> content >> pathRelative >> pathAbsolute;
  1120. if (theme.stream.status() != QDataStream::Ok) {
  1121. return Object();
  1122. }
  1123. auto result = Object();
  1124. result.pathAbsolute = pathAbsolute;
  1125. result.content = content;
  1126. return result;
  1127. }
  1128. void incrementRecentHashtag(RecentHashtagPack &recent, const QString &tag) {
  1129. auto i = recent.begin(), e = recent.end();
  1130. for (; i != e; ++i) {
  1131. if (i->first == tag) {
  1132. ++i->second;
  1133. if (qAbs(i->second) > 0x4000) {
  1134. for (auto j = recent.begin(); j != e; ++j) {
  1135. if (j->second > 1) {
  1136. j->second /= 2;
  1137. } else if (j->second > 0) {
  1138. j->second = 1;
  1139. }
  1140. }
  1141. }
  1142. for (; i != recent.begin(); --i) {
  1143. if (qAbs((i - 1)->second) > qAbs(i->second)) {
  1144. break;
  1145. }
  1146. qSwap(*i, *(i - 1));
  1147. }
  1148. break;
  1149. }
  1150. }
  1151. if (i == e) {
  1152. while (recent.size() >= 64) recent.pop_back();
  1153. recent.push_back(qMakePair(tag, 1));
  1154. for (i = recent.end() - 1; i != recent.begin(); --i) {
  1155. if ((i - 1)->second > i->second) {
  1156. break;
  1157. }
  1158. qSwap(*i, *(i - 1));
  1159. }
  1160. }
  1161. }
  1162. bool readOldMtpData(bool remove, ReadSettingsContext &context) {
  1163. return _readOldMtpData(remove, context);
  1164. }
  1165. bool readOldUserSettings(bool remove, ReadSettingsContext &context) {
  1166. return _readOldUserSettings(remove, context);
  1167. }
  1168. } // namespace Local