storage_account.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514
  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/storage_account.h"
  8. #include "storage/localstorage.h"
  9. #include "storage/storage_domain.h"
  10. #include "storage/storage_encryption.h"
  11. #include "storage/storage_clear_legacy.h"
  12. #include "storage/cache/storage_cache_types.h"
  13. #include "storage/details/storage_file_utilities.h"
  14. #include "storage/details/storage_settings_scheme.h"
  15. #include "storage/serialize_common.h"
  16. #include "storage/serialize_peer.h"
  17. #include "storage/serialize_document.h"
  18. #include "main/main_account.h"
  19. #include "main/main_domain.h"
  20. #include "main/main_session.h"
  21. #include "mtproto/mtproto_config.h"
  22. #include "mtproto/mtproto_dc_options.h"
  23. #include "mtproto/mtp_instance.h"
  24. #include "lang/lang_keys.h"
  25. #include "history/history.h"
  26. #include "core/application.h"
  27. #include "core/core_settings.h"
  28. #include "core/file_location.h"
  29. #include "data/components/recent_peers.h"
  30. #include "data/components/top_peers.h"
  31. #include "data/stickers/data_stickers.h"
  32. #include "data/data_session.h"
  33. #include "data/data_document.h"
  34. #include "data/data_user.h"
  35. #include "data/data_drafts.h"
  36. #include "export/export_settings.h"
  37. #include "webview/webview_interface.h"
  38. #include "window/themes/window_theme.h"
  39. namespace Storage {
  40. namespace {
  41. using namespace details;
  42. using Database = Cache::Database;
  43. constexpr auto kDelayedWriteTimeout = crl::time(1000);
  44. constexpr auto kWriteSearchSuggestionsDelay = 5 * crl::time(1000);
  45. constexpr auto kMaxSavedPlaybackPositions = 256;
  46. constexpr auto kStickersVersionTag = quint32(-1);
  47. constexpr auto kStickersSerializeVersion = 4;
  48. constexpr auto kMaxSavedStickerSetsCount = 1000;
  49. constexpr auto kDefaultStickerInstallDate = TimeId(1);
  50. constexpr auto kSinglePeerTypeUserOld = qint32(1);
  51. constexpr auto kSinglePeerTypeChatOld = qint32(2);
  52. constexpr auto kSinglePeerTypeChannelOld = qint32(3);
  53. constexpr auto kSinglePeerTypeUser = qint32(8 + 1);
  54. constexpr auto kSinglePeerTypeChat = qint32(8 + 2);
  55. constexpr auto kSinglePeerTypeChannel = qint32(8 + 3);
  56. constexpr auto kSinglePeerTypeSelf = qint32(4);
  57. constexpr auto kSinglePeerTypeEmpty = qint32(0);
  58. constexpr auto kMultiDraftTagOld = quint64(0xFFFF'FFFF'FFFF'FF01ULL);
  59. constexpr auto kMultiDraftCursorsTagOld = quint64(0xFFFF'FFFF'FFFF'FF02ULL);
  60. constexpr auto kMultiDraftTag = quint64(0xFFFF'FFFF'FFFF'FF03ULL);
  61. constexpr auto kMultiDraftCursorsTag = quint64(0xFFFF'FFFF'FFFF'FF04ULL);
  62. constexpr auto kRichDraftsTag = quint64(0xFFFF'FFFF'FFFF'FF05ULL);
  63. enum { // Local Storage Keys
  64. lskUserMap = 0x00,
  65. lskDraft = 0x01, // data: PeerId peer
  66. lskDraftPosition = 0x02, // data: PeerId peer
  67. lskLegacyImages = 0x03, // legacy
  68. lskLocations = 0x04, // no data
  69. lskLegacyStickerImages = 0x05, // legacy
  70. lskLegacyAudios = 0x06, // legacy
  71. lskRecentStickersOld = 0x07, // no data
  72. lskBackgroundOldOld = 0x08, // no data
  73. lskUserSettings = 0x09, // no data
  74. lskRecentHashtagsAndBots = 0x0a, // no data
  75. lskStickersOld = 0x0b, // no data
  76. lskSavedPeersOld = 0x0c, // no data
  77. lskReportSpamStatusesOld = 0x0d, // no data
  78. lskSavedGifsOld = 0x0e, // no data
  79. lskSavedGifs = 0x0f, // no data
  80. lskStickersKeys = 0x10, // no data
  81. lskTrustedPeers = 0x11, // no data
  82. lskFavedStickers = 0x12, // no data
  83. lskExportSettings = 0x13, // no data
  84. lskBackgroundOld = 0x14, // no data
  85. lskSelfSerialized = 0x15, // serialized self
  86. lskMasksKeys = 0x16, // no data
  87. lskCustomEmojiKeys = 0x17, // no data
  88. lskSearchSuggestions = 0x18, // no data
  89. lskWebviewTokens = 0x19, // data: QByteArray bots, QByteArray other
  90. lskRoundPlaceholder = 0x1a, // no data
  91. lskInlineBotsDownloads = 0x1b, // no data
  92. lskMediaLastPlaybackPositions = 0x1c, // no data
  93. };
  94. auto EmptyMessageDraftSources()
  95. -> const base::flat_map<Data::DraftKey, MessageDraftSource> & {
  96. static const auto result = base::flat_map<
  97. Data::DraftKey,
  98. MessageDraftSource>();
  99. return result;
  100. }
  101. [[nodiscard]] FileKey ComputeDataNameKey(const QString &dataName) {
  102. // We dropped old test authorizations when migrated to multi auth.
  103. //const auto testAddition = (cTestMode() ? u":/test/"_q : QString());
  104. const auto testAddition = QString();
  105. const auto dataNameUtf8 = (dataName + testAddition).toUtf8();
  106. FileKey dataNameHash[2] = { 0 };
  107. hashMd5(dataNameUtf8.constData(), dataNameUtf8.size(), dataNameHash);
  108. return dataNameHash[0];
  109. }
  110. [[nodiscard]] QString BaseGlobalPath() {
  111. return cWorkingDir() + u"tdata/"_q;
  112. }
  113. [[nodiscard]] QString ComputeDatabasePath(const QString &dataName) {
  114. return BaseGlobalPath()
  115. + "user_" + dataName
  116. // We dropped old test authorizations when migrated to multi auth.
  117. //+ (cTestMode() ? "[test]" : "")
  118. + '/';
  119. }
  120. [[nodiscard]] QString LegacyTempDirectory() {
  121. return cWorkingDir() + u"tdata/tdld/"_q;
  122. }
  123. } // namespace
  124. Account::Account(not_null<Main::Account*> owner, const QString &dataName)
  125. : _owner(owner)
  126. , _dataName(dataName)
  127. , _dataNameKey(ComputeDataNameKey(dataName))
  128. , _basePath(BaseGlobalPath() + ToFilePart(_dataNameKey) + QChar('/'))
  129. , _tempPath(BaseGlobalPath() + "temp_" + _dataName + QChar('/'))
  130. , _databasePath(ComputeDatabasePath(dataName))
  131. , _cacheTotalSizeLimit(Database::Settings().totalSizeLimit)
  132. , _cacheBigFileTotalSizeLimit(Database::Settings().totalSizeLimit)
  133. , _cacheTotalTimeLimit(Database::Settings().totalTimeLimit)
  134. , _cacheBigFileTotalTimeLimit(Database::Settings().totalTimeLimit)
  135. , _writeMapTimer([=] { writeMap(); })
  136. , _writeLocationsTimer([=] { writeLocations(); })
  137. , _writeSearchSuggestionsTimer([=] { writeSearchSuggestions(); }) {
  138. }
  139. Account::~Account() {
  140. Expects(!_writeSearchSuggestionsTimer.isActive());
  141. if (_localKey && _mapChanged) {
  142. writeMap();
  143. }
  144. }
  145. QString Account::tempDirectory() const {
  146. return _tempPath;
  147. }
  148. QString Account::supportModePath() const {
  149. return _databasePath + u"support"_q;
  150. }
  151. StartResult Account::legacyStart(const QByteArray &passcode) {
  152. const auto result = readMapWith(MTP::AuthKeyPtr(), passcode);
  153. if (result == ReadMapResult::Failed) {
  154. Assert(_localKey == nullptr);
  155. } else if (result == ReadMapResult::IncorrectPasscode) {
  156. return StartResult::IncorrectPasscodeLegacy;
  157. }
  158. clearLegacyFiles();
  159. return StartResult::Success;
  160. }
  161. std::unique_ptr<MTP::Config> Account::start(MTP::AuthKeyPtr localKey) {
  162. Expects(localKey != nullptr);
  163. _localKey = std::move(localKey);
  164. readMapWith(_localKey);
  165. clearLegacyFiles();
  166. return readMtpConfig();
  167. }
  168. void Account::startAdded(MTP::AuthKeyPtr localKey) {
  169. Expects(localKey != nullptr);
  170. _localKey = std::move(localKey);
  171. clearLegacyFiles();
  172. }
  173. void Account::clearLegacyFiles() {
  174. const auto weak = base::make_weak(_owner);
  175. ClearLegacyFiles(_basePath, [weak, this](
  176. FnMut<void(base::flat_set<QString>&&)> then) {
  177. crl::on_main(weak, [this, then = std::move(then)]() mutable {
  178. then(collectGoodNames());
  179. });
  180. });
  181. }
  182. base::flat_set<QString> Account::collectGoodNames() const {
  183. const auto keys = {
  184. _locationsKey,
  185. _settingsKey,
  186. _installedStickersKey,
  187. _featuredStickersKey,
  188. _recentStickersKey,
  189. _favedStickersKey,
  190. _archivedStickersKey,
  191. _recentStickersKeyOld,
  192. _savedGifsKey,
  193. _legacyBackgroundKeyNight,
  194. _legacyBackgroundKeyDay,
  195. _recentHashtagsAndBotsKey,
  196. _exportSettingsKey,
  197. _trustedPeersKey,
  198. _installedMasksKey,
  199. _recentMasksKey,
  200. _archivedMasksKey,
  201. _installedCustomEmojiKey,
  202. _featuredCustomEmojiKey,
  203. _archivedCustomEmojiKey,
  204. _searchSuggestionsKey,
  205. _roundPlaceholderKey,
  206. _inlineBotsDownloadsKey,
  207. _mediaLastPlaybackPositionsKey,
  208. };
  209. auto result = base::flat_set<QString>{
  210. "map0",
  211. "map1",
  212. "maps",
  213. "configs",
  214. };
  215. const auto push = [&](FileKey key) {
  216. if (!key) {
  217. return;
  218. }
  219. auto name = ToFilePart(key) + '0';
  220. result.emplace(name);
  221. name[name.size() - 1] = '1';
  222. result.emplace(name);
  223. name[name.size() - 1] = 's';
  224. result.emplace(name);
  225. };
  226. for (const auto &[key, value] : _draftsMap) {
  227. push(value);
  228. }
  229. for (const auto &[key, value] : _draftCursorsMap) {
  230. push(value);
  231. }
  232. for (const auto &value : keys) {
  233. push(value);
  234. }
  235. return result;
  236. }
  237. Account::ReadMapResult Account::readMapWith(
  238. MTP::AuthKeyPtr localKey,
  239. const QByteArray &legacyPasscode) {
  240. auto ms = crl::now();
  241. FileReadDescriptor mapData;
  242. if (!ReadFile(mapData, u"map"_q, _basePath)) {
  243. return ReadMapResult::Failed;
  244. }
  245. LOG(("App Info: reading map..."));
  246. QByteArray legacySalt, legacyKeyEncrypted, mapEncrypted;
  247. mapData.stream >> legacySalt >> legacyKeyEncrypted >> mapEncrypted;
  248. if (!CheckStreamStatus(mapData.stream)) {
  249. return ReadMapResult::Failed;
  250. }
  251. if (!localKey) {
  252. if (legacySalt.size() != LocalEncryptSaltSize) {
  253. LOG(("App Error: bad salt in map file, size: %1").arg(legacySalt.size()));
  254. return ReadMapResult::Failed;
  255. }
  256. auto legacyPasscodeKey = CreateLegacyLocalKey(legacyPasscode, legacySalt);
  257. EncryptedDescriptor keyData;
  258. if (!DecryptLocal(keyData, legacyKeyEncrypted, legacyPasscodeKey)) {
  259. LOG(("App Info: could not decrypt pass-protected key from map file, maybe bad password..."));
  260. return ReadMapResult::IncorrectPasscode;
  261. }
  262. auto key = Serialize::read<MTP::AuthKey::Data>(keyData.stream);
  263. if (keyData.stream.status() != QDataStream::Ok || !keyData.stream.atEnd()) {
  264. LOG(("App Error: could not read pass-protected key from map file"));
  265. return ReadMapResult::Failed;
  266. }
  267. localKey = std::make_shared<MTP::AuthKey>(key);
  268. }
  269. EncryptedDescriptor map;
  270. if (!DecryptLocal(map, mapEncrypted, localKey)) {
  271. LOG(("App Error: could not decrypt map."));
  272. return ReadMapResult::Failed;
  273. }
  274. LOG(("App Info: reading encrypted map..."));
  275. QByteArray selfSerialized;
  276. base::flat_map<PeerId, FileKey> draftsMap;
  277. base::flat_map<PeerId, FileKey> draftCursorsMap;
  278. base::flat_map<PeerId, bool> draftsNotReadMap;
  279. quint64 locationsKey = 0, reportSpamStatusesKey = 0, trustedPeersKey = 0;
  280. quint64 recentStickersKeyOld = 0;
  281. quint64 installedStickersKey = 0, featuredStickersKey = 0, recentStickersKey = 0, favedStickersKey = 0, archivedStickersKey = 0;
  282. quint64 installedMasksKey = 0, recentMasksKey = 0, archivedMasksKey = 0;
  283. quint64 installedCustomEmojiKey = 0, featuredCustomEmojiKey = 0, archivedCustomEmojiKey = 0;
  284. quint64 savedGifsKey = 0;
  285. quint64 legacyBackgroundKeyDay = 0, legacyBackgroundKeyNight = 0;
  286. quint64 userSettingsKey = 0, recentHashtagsAndBotsKey = 0, exportSettingsKey = 0;
  287. quint64 searchSuggestionsKey = 0;
  288. quint64 roundPlaceholderKey = 0;
  289. quint64 inlineBotsDownloadsKey = 0;
  290. quint64 mediaLastPlaybackPositionsKey = 0;
  291. QByteArray webviewStorageTokenBots, webviewStorageTokenOther;
  292. while (!map.stream.atEnd()) {
  293. quint32 keyType;
  294. map.stream >> keyType;
  295. switch (keyType) {
  296. case lskDraft: {
  297. quint32 count = 0;
  298. map.stream >> count;
  299. for (quint32 i = 0; i < count; ++i) {
  300. FileKey key;
  301. quint64 peerIdSerialized;
  302. map.stream >> key >> peerIdSerialized;
  303. const auto peerId = DeserializePeerId(peerIdSerialized);
  304. draftsMap.emplace(peerId, key);
  305. draftsNotReadMap.emplace(peerId, true);
  306. }
  307. } break;
  308. case lskSelfSerialized: {
  309. map.stream >> selfSerialized;
  310. } break;
  311. case lskDraftPosition: {
  312. quint32 count = 0;
  313. map.stream >> count;
  314. for (quint32 i = 0; i < count; ++i) {
  315. FileKey key;
  316. quint64 peerIdSerialized;
  317. map.stream >> key >> peerIdSerialized;
  318. const auto peerId = DeserializePeerId(peerIdSerialized);
  319. draftCursorsMap.emplace(peerId, key);
  320. }
  321. } break;
  322. case lskLegacyImages:
  323. case lskLegacyStickerImages:
  324. case lskLegacyAudios: {
  325. quint32 count = 0;
  326. map.stream >> count;
  327. for (quint32 i = 0; i < count; ++i) {
  328. FileKey key;
  329. quint64 first, second;
  330. qint32 size;
  331. map.stream >> key >> first >> second >> size;
  332. // Just ignore the key, it will be removed as a leaked one.
  333. }
  334. } break;
  335. case lskLocations: {
  336. map.stream >> locationsKey;
  337. } break;
  338. case lskReportSpamStatusesOld: {
  339. map.stream >> reportSpamStatusesKey;
  340. ClearKey(reportSpamStatusesKey, _basePath);
  341. } break;
  342. case lskTrustedPeers: {
  343. map.stream >> trustedPeersKey;
  344. } break;
  345. case lskRecentStickersOld: {
  346. map.stream >> recentStickersKeyOld;
  347. } break;
  348. case lskBackgroundOldOld: {
  349. map.stream >> (Window::Theme::IsNightMode()
  350. ? legacyBackgroundKeyNight
  351. : legacyBackgroundKeyDay);
  352. } break;
  353. case lskBackgroundOld: {
  354. map.stream >> legacyBackgroundKeyDay >> legacyBackgroundKeyNight;
  355. } break;
  356. case lskUserSettings: {
  357. map.stream >> userSettingsKey;
  358. } break;
  359. case lskRecentHashtagsAndBots: {
  360. map.stream >> recentHashtagsAndBotsKey;
  361. } break;
  362. case lskStickersOld: {
  363. map.stream >> installedStickersKey;
  364. } break;
  365. case lskStickersKeys: {
  366. map.stream >> installedStickersKey >> featuredStickersKey >> recentStickersKey >> archivedStickersKey;
  367. } break;
  368. case lskFavedStickers: {
  369. map.stream >> favedStickersKey;
  370. } break;
  371. case lskSavedGifsOld: {
  372. quint64 key;
  373. map.stream >> key;
  374. } break;
  375. case lskSavedGifs: {
  376. map.stream >> savedGifsKey;
  377. } break;
  378. case lskSavedPeersOld: {
  379. quint64 key;
  380. map.stream >> key;
  381. } break;
  382. case lskExportSettings: {
  383. map.stream >> exportSettingsKey;
  384. } break;
  385. case lskMasksKeys: {
  386. map.stream
  387. >> installedMasksKey
  388. >> recentMasksKey
  389. >> archivedMasksKey;
  390. } break;
  391. case lskCustomEmojiKeys: {
  392. map.stream
  393. >> installedCustomEmojiKey
  394. >> featuredCustomEmojiKey
  395. >> archivedCustomEmojiKey;
  396. } break;
  397. case lskSearchSuggestions: {
  398. map.stream >> searchSuggestionsKey;
  399. } break;
  400. case lskRoundPlaceholder: {
  401. map.stream >> roundPlaceholderKey;
  402. } break;
  403. case lskInlineBotsDownloads: {
  404. map.stream >> inlineBotsDownloadsKey;
  405. } break;
  406. case lskMediaLastPlaybackPositions: {
  407. map.stream >> mediaLastPlaybackPositionsKey;
  408. } break;
  409. case lskWebviewTokens: {
  410. map.stream
  411. >> webviewStorageTokenBots
  412. >> webviewStorageTokenOther;
  413. } break;
  414. default:
  415. LOG(("App Error: unknown key type in encrypted map: %1").arg(keyType));
  416. return ReadMapResult::Failed;
  417. }
  418. if (!CheckStreamStatus(map.stream)) {
  419. return ReadMapResult::Failed;
  420. }
  421. }
  422. _localKey = std::move(localKey);
  423. _draftsMap = draftsMap;
  424. _draftCursorsMap = draftCursorsMap;
  425. _draftsNotReadMap = draftsNotReadMap;
  426. _locationsKey = locationsKey;
  427. _trustedPeersKey = trustedPeersKey;
  428. _recentStickersKeyOld = recentStickersKeyOld;
  429. _installedStickersKey = installedStickersKey;
  430. _featuredStickersKey = featuredStickersKey;
  431. _recentStickersKey = recentStickersKey;
  432. _favedStickersKey = favedStickersKey;
  433. _archivedStickersKey = archivedStickersKey;
  434. _savedGifsKey = savedGifsKey;
  435. _installedMasksKey = installedMasksKey;
  436. _recentMasksKey = recentMasksKey;
  437. _archivedMasksKey = archivedMasksKey;
  438. _installedCustomEmojiKey = installedCustomEmojiKey;
  439. _featuredCustomEmojiKey = featuredCustomEmojiKey;
  440. _archivedCustomEmojiKey = archivedCustomEmojiKey;
  441. _legacyBackgroundKeyDay = legacyBackgroundKeyDay;
  442. _legacyBackgroundKeyNight = legacyBackgroundKeyNight;
  443. _settingsKey = userSettingsKey;
  444. _recentHashtagsAndBotsKey = recentHashtagsAndBotsKey;
  445. _exportSettingsKey = exportSettingsKey;
  446. _searchSuggestionsKey = searchSuggestionsKey;
  447. _roundPlaceholderKey = roundPlaceholderKey;
  448. _inlineBotsDownloadsKey = inlineBotsDownloadsKey;
  449. _mediaLastPlaybackPositionsKey = mediaLastPlaybackPositionsKey;
  450. _oldMapVersion = mapData.version;
  451. _webviewStorageIdBots.token = webviewStorageTokenBots;
  452. _webviewStorageIdOther.token = webviewStorageTokenOther;
  453. if (_oldMapVersion < AppVersion) {
  454. writeMapDelayed();
  455. } else {
  456. _mapChanged = false;
  457. }
  458. if (_locationsKey) {
  459. readLocations();
  460. }
  461. if (_legacyBackgroundKeyDay || _legacyBackgroundKeyNight) {
  462. Local::moveLegacyBackground(
  463. _basePath,
  464. _localKey,
  465. _legacyBackgroundKeyDay,
  466. _legacyBackgroundKeyNight);
  467. }
  468. auto stored = readSessionSettings();
  469. readMtpData();
  470. DEBUG_LOG(("selfSerialized set: %1").arg(selfSerialized.size()));
  471. _owner->setSessionFromStorage(
  472. std::move(stored),
  473. std::move(selfSerialized),
  474. _oldMapVersion);
  475. LOG(("Map read time: %1").arg(crl::now() - ms));
  476. return ReadMapResult::Success;
  477. }
  478. void Account::writeMapDelayed() {
  479. _mapChanged = true;
  480. _writeMapTimer.callOnce(kDelayedWriteTimeout);
  481. }
  482. void Account::writeMapQueued() {
  483. _mapChanged = true;
  484. crl::on_main(_owner, [=] {
  485. writeMap();
  486. });
  487. }
  488. void Account::writeMap() {
  489. Expects(_localKey != nullptr);
  490. _writeMapTimer.cancel();
  491. if (!_mapChanged) {
  492. return;
  493. }
  494. _mapChanged = false;
  495. if (!QDir().exists(_basePath)) {
  496. QDir().mkpath(_basePath);
  497. }
  498. FileWriteDescriptor map(u"map"_q, _basePath);
  499. map.writeData(QByteArray());
  500. map.writeData(QByteArray());
  501. uint32 mapSize = 0;
  502. const auto self = [&] {
  503. if (!_owner->sessionExists()) {
  504. DEBUG_LOG(("AuthSelf Warning: Session does not exist."));
  505. return QByteArray();
  506. }
  507. const auto self = _owner->session().user();
  508. if (self->phone().isEmpty()) {
  509. DEBUG_LOG(("AuthSelf Error: Phone is empty."));
  510. return QByteArray();
  511. }
  512. auto result = QByteArray();
  513. result.reserve(Serialize::peerSize(self)
  514. + Serialize::stringSize(self->about()));
  515. {
  516. QBuffer buffer(&result);
  517. buffer.open(QIODevice::WriteOnly);
  518. QDataStream stream(&buffer);
  519. Serialize::writePeer(stream, self);
  520. stream << self->about();
  521. }
  522. return result;
  523. }();
  524. if (!self.isEmpty()) mapSize += sizeof(quint32) + Serialize::bytearraySize(self);
  525. if (!_draftsMap.empty()) mapSize += sizeof(quint32) * 2 + _draftsMap.size() * sizeof(quint64) * 2;
  526. if (!_draftCursorsMap.empty()) mapSize += sizeof(quint32) * 2 + _draftCursorsMap.size() * sizeof(quint64) * 2;
  527. if (_locationsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  528. if (_trustedPeersKey) mapSize += sizeof(quint32) + sizeof(quint64);
  529. if (_recentStickersKeyOld) mapSize += sizeof(quint32) + sizeof(quint64);
  530. if (_installedStickersKey || _featuredStickersKey || _recentStickersKey || _archivedStickersKey) {
  531. mapSize += sizeof(quint32) + 4 * sizeof(quint64);
  532. }
  533. if (_favedStickersKey) mapSize += sizeof(quint32) + sizeof(quint64);
  534. if (_savedGifsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  535. if (_settingsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  536. if (_recentHashtagsAndBotsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  537. if (_exportSettingsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  538. if (_installedMasksKey || _recentMasksKey || _archivedMasksKey) {
  539. mapSize += sizeof(quint32) + 3 * sizeof(quint64);
  540. }
  541. if (_installedCustomEmojiKey || _featuredCustomEmojiKey || _archivedCustomEmojiKey) {
  542. mapSize += sizeof(quint32) + 3 * sizeof(quint64);
  543. }
  544. if (_searchSuggestionsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  545. if (!_webviewStorageIdBots.token.isEmpty()
  546. || !_webviewStorageIdOther.token.isEmpty()) {
  547. mapSize += sizeof(quint32)
  548. + Serialize::bytearraySize(_webviewStorageIdBots.token)
  549. + Serialize::bytearraySize(_webviewStorageIdOther.token);
  550. }
  551. if (_roundPlaceholderKey) mapSize += sizeof(quint32) + sizeof(quint64);
  552. if (_inlineBotsDownloadsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  553. if (_mediaLastPlaybackPositionsKey) mapSize += sizeof(quint32) + sizeof(quint64);
  554. EncryptedDescriptor mapData(mapSize);
  555. if (!self.isEmpty()) {
  556. mapData.stream << quint32(lskSelfSerialized) << self;
  557. }
  558. if (!_draftsMap.empty()) {
  559. mapData.stream << quint32(lskDraft) << quint32(_draftsMap.size());
  560. for (const auto &[key, value] : _draftsMap) {
  561. mapData.stream << quint64(value) << SerializePeerId(key);
  562. }
  563. }
  564. if (!_draftCursorsMap.empty()) {
  565. mapData.stream << quint32(lskDraftPosition) << quint32(_draftCursorsMap.size());
  566. for (const auto &[key, value] : _draftCursorsMap) {
  567. mapData.stream << quint64(value) << SerializePeerId(key);
  568. }
  569. }
  570. if (_locationsKey) {
  571. mapData.stream << quint32(lskLocations) << quint64(_locationsKey);
  572. }
  573. if (_trustedPeersKey) {
  574. mapData.stream << quint32(lskTrustedPeers) << quint64(_trustedPeersKey);
  575. }
  576. if (_recentStickersKeyOld) {
  577. mapData.stream << quint32(lskRecentStickersOld) << quint64(_recentStickersKeyOld);
  578. }
  579. if (_installedStickersKey || _featuredStickersKey || _recentStickersKey || _archivedStickersKey) {
  580. mapData.stream << quint32(lskStickersKeys);
  581. mapData.stream << quint64(_installedStickersKey) << quint64(_featuredStickersKey) << quint64(_recentStickersKey) << quint64(_archivedStickersKey);
  582. }
  583. if (_favedStickersKey) {
  584. mapData.stream << quint32(lskFavedStickers) << quint64(_favedStickersKey);
  585. }
  586. if (_savedGifsKey) {
  587. mapData.stream << quint32(lskSavedGifs) << quint64(_savedGifsKey);
  588. }
  589. if (_settingsKey) {
  590. mapData.stream << quint32(lskUserSettings) << quint64(_settingsKey);
  591. }
  592. if (_recentHashtagsAndBotsKey) {
  593. mapData.stream << quint32(lskRecentHashtagsAndBots) << quint64(_recentHashtagsAndBotsKey);
  594. }
  595. if (_exportSettingsKey) {
  596. mapData.stream << quint32(lskExportSettings) << quint64(_exportSettingsKey);
  597. }
  598. if (_installedMasksKey || _recentMasksKey || _archivedMasksKey) {
  599. mapData.stream << quint32(lskMasksKeys);
  600. mapData.stream
  601. << quint64(_installedMasksKey)
  602. << quint64(_recentMasksKey)
  603. << quint64(_archivedMasksKey);
  604. }
  605. if (_installedCustomEmojiKey || _featuredCustomEmojiKey || _archivedCustomEmojiKey) {
  606. mapData.stream << quint32(lskCustomEmojiKeys);
  607. mapData.stream
  608. << quint64(_installedCustomEmojiKey)
  609. << quint64(_featuredCustomEmojiKey)
  610. << quint64(_archivedCustomEmojiKey);
  611. }
  612. if (_searchSuggestionsKey) {
  613. mapData.stream << quint32(lskSearchSuggestions);
  614. mapData.stream << quint64(_searchSuggestionsKey);
  615. }
  616. if (!_webviewStorageIdBots.token.isEmpty()
  617. || !_webviewStorageIdOther.token.isEmpty()) {
  618. mapData.stream << quint32(lskWebviewTokens);
  619. mapData.stream
  620. << _webviewStorageIdBots.token
  621. << _webviewStorageIdOther.token;
  622. }
  623. if (_roundPlaceholderKey) {
  624. mapData.stream << quint32(lskRoundPlaceholder);
  625. mapData.stream << quint64(_roundPlaceholderKey);
  626. }
  627. if (_inlineBotsDownloadsKey) {
  628. mapData.stream << quint32(lskInlineBotsDownloads);
  629. mapData.stream << quint64(_inlineBotsDownloadsKey);
  630. }
  631. if (_mediaLastPlaybackPositionsKey) {
  632. mapData.stream << quint32(lskMediaLastPlaybackPositions);
  633. mapData.stream << quint64(_mediaLastPlaybackPositionsKey);
  634. }
  635. map.writeEncrypted(mapData, _localKey);
  636. _mapChanged = false;
  637. }
  638. void Account::reset() {
  639. _writeSearchSuggestionsTimer.cancel();
  640. auto names = collectGoodNames();
  641. _draftsMap.clear();
  642. _draftCursorsMap.clear();
  643. _draftsNotReadMap.clear();
  644. _locationsKey = _trustedPeersKey = 0;
  645. _recentStickersKeyOld = 0;
  646. _installedStickersKey = 0;
  647. _featuredStickersKey = 0;
  648. _recentStickersKey = 0;
  649. _favedStickersKey = 0;
  650. _archivedStickersKey = 0;
  651. _savedGifsKey = 0;
  652. _installedMasksKey = 0;
  653. _recentMasksKey = 0;
  654. _archivedMasksKey = 0;
  655. _installedCustomEmojiKey = 0;
  656. _featuredCustomEmojiKey = 0;
  657. _archivedCustomEmojiKey = 0;
  658. _legacyBackgroundKeyDay = _legacyBackgroundKeyNight = 0;
  659. _settingsKey = _recentHashtagsAndBotsKey = _exportSettingsKey = 0;
  660. _searchSuggestionsKey = 0;
  661. _roundPlaceholderKey = 0;
  662. _inlineBotsDownloadsKey = 0;
  663. _mediaLastPlaybackPositionsKey = 0;
  664. _oldMapVersion = 0;
  665. _fileLocations.clear();
  666. _fileLocationPairs.clear();
  667. _fileLocationAliases.clear();
  668. _downloadsSerialize = nullptr;
  669. _downloadsSerialized = QByteArray();
  670. _cacheTotalSizeLimit = Database::Settings().totalSizeLimit;
  671. _cacheTotalTimeLimit = Database::Settings().totalTimeLimit;
  672. _cacheBigFileTotalSizeLimit = Database::Settings().totalSizeLimit;
  673. _cacheBigFileTotalTimeLimit = Database::Settings().totalTimeLimit;
  674. _mediaLastPlaybackPosition.clear();
  675. const auto wvbots = _webviewStorageIdBots.path;
  676. const auto wvother = _webviewStorageIdOther.path;
  677. const auto wvclear = [](Webview::StorageId &storageId) {
  678. Webview::ClearStorageDataByToken(
  679. base::take(storageId).token.toStdString());
  680. };
  681. wvclear(_webviewStorageIdBots);
  682. wvclear(_webviewStorageIdOther);
  683. _mapChanged = true;
  684. writeMap();
  685. writeMtpData();
  686. crl::async([
  687. base = _basePath,
  688. temp = _tempPath,
  689. names = std::move(names),
  690. wvbots,
  691. wvother
  692. ] {
  693. for (const auto &name : names) {
  694. if (!name.endsWith(u"map0"_q)
  695. && !name.endsWith(u"map1"_q)
  696. && !name.endsWith(u"maps"_q)
  697. && !name.endsWith(u"configs"_q)) {
  698. QFile::remove(base + name);
  699. }
  700. }
  701. QDir(LegacyTempDirectory()).removeRecursively();
  702. if (!wvbots.isEmpty()) {
  703. QDir(wvbots).removeRecursively();
  704. }
  705. if (!wvother.isEmpty()) {
  706. QDir(wvother).removeRecursively();
  707. }
  708. QDir(temp).removeRecursively();
  709. });
  710. Local::sync();
  711. }
  712. void Account::writeLocations() {
  713. _writeLocationsTimer.cancel();
  714. if (!_locationsChanged) {
  715. return;
  716. }
  717. _locationsChanged = false;
  718. if (_downloadsSerialize) {
  719. if (auto serialized = _downloadsSerialize()) {
  720. _downloadsSerialized = std::move(*serialized);
  721. }
  722. }
  723. if (_fileLocations.isEmpty() && _downloadsSerialized.isEmpty()) {
  724. if (_locationsKey) {
  725. ClearKey(_locationsKey, _basePath);
  726. _locationsKey = 0;
  727. writeMapDelayed();
  728. }
  729. } else {
  730. if (!_locationsKey) {
  731. _locationsKey = GenerateKey(_basePath);
  732. writeMapQueued();
  733. }
  734. quint32 size = 0;
  735. for (auto i = _fileLocations.cbegin(), e = _fileLocations.cend(); i != e; ++i) {
  736. // location + type + namelen + name
  737. size += sizeof(quint64) * 2 + sizeof(quint32) + Serialize::stringSize(i.value().name());
  738. if (AppVersion > 9013) {
  739. // bookmark
  740. size += Serialize::bytearraySize(i.value().bookmark());
  741. }
  742. // date + size
  743. size += Serialize::dateTimeSize() + sizeof(quint32);
  744. }
  745. //end mark
  746. size += sizeof(quint64) * 2 + sizeof(quint32) + Serialize::stringSize(QString());
  747. if (AppVersion > 9013) {
  748. size += Serialize::bytearraySize(QByteArray());
  749. }
  750. size += Serialize::dateTimeSize() + sizeof(quint32);
  751. size += sizeof(quint32); // aliases count
  752. for (auto i = _fileLocationAliases.cbegin(), e = _fileLocationAliases.cend(); i != e; ++i) {
  753. // alias + location
  754. size += sizeof(quint64) * 2 + sizeof(quint64) * 2;
  755. }
  756. size += sizeof(quint32); // legacy webLocationsCount
  757. size += Serialize::bytearraySize(_downloadsSerialized);
  758. EncryptedDescriptor data(size);
  759. auto legacyTypeField = 0;
  760. for (auto i = _fileLocations.cbegin(); i != _fileLocations.cend(); ++i) {
  761. data.stream << quint64(i.key().first) << quint64(i.key().second) << quint32(legacyTypeField) << i.value().name();
  762. if (AppVersion > 9013) {
  763. data.stream << i.value().bookmark();
  764. }
  765. data.stream << i.value().modified << quint32(i.value().size);
  766. }
  767. data.stream << quint64(0) << quint64(0) << quint32(0) << QString();
  768. if (AppVersion > 9013) {
  769. data.stream << QByteArray();
  770. }
  771. data.stream << QDateTime::currentDateTime() << quint32(0);
  772. data.stream << quint32(_fileLocationAliases.size());
  773. for (auto i = _fileLocationAliases.cbegin(), e = _fileLocationAliases.cend(); i != e; ++i) {
  774. data.stream << quint64(i.key().first) << quint64(i.key().second) << quint64(i.value().first) << quint64(i.value().second);
  775. }
  776. data.stream << quint32(0) << _downloadsSerialized;
  777. FileWriteDescriptor file(_locationsKey, _basePath);
  778. file.writeEncrypted(data, _localKey);
  779. }
  780. }
  781. void Account::writeLocationsQueued() {
  782. _locationsChanged = true;
  783. crl::on_main(_owner, [=] {
  784. writeLocations();
  785. });
  786. }
  787. void Account::writeLocationsDelayed() {
  788. _locationsChanged = true;
  789. _writeLocationsTimer.callOnce(kDelayedWriteTimeout);
  790. }
  791. void Account::readLocations() {
  792. FileReadDescriptor locations;
  793. if (!ReadEncryptedFile(locations, _locationsKey, _basePath, _localKey)) {
  794. ClearKey(_locationsKey, _basePath);
  795. _locationsKey = 0;
  796. writeMapDelayed();
  797. return;
  798. }
  799. bool endMarkFound = false;
  800. while (!locations.stream.atEnd()) {
  801. quint64 first, second;
  802. QByteArray bookmark;
  803. Core::FileLocation loc;
  804. quint32 legacyTypeField = 0;
  805. quint32 size = 0;
  806. locations.stream >> first >> second >> legacyTypeField >> loc.fname;
  807. if (locations.version > 9013) {
  808. locations.stream >> bookmark;
  809. }
  810. locations.stream >> loc.modified >> size;
  811. loc.setBookmark(bookmark);
  812. loc.size = int64(size);
  813. if (!first && !second && !legacyTypeField && loc.fname.isEmpty() && !loc.size) { // end mark
  814. endMarkFound = true;
  815. break;
  816. }
  817. MediaKey key(first, second);
  818. _fileLocations.insert(key, loc);
  819. if (!loc.inMediaCache()) {
  820. _fileLocationPairs.insert(loc.fname, { key, loc });
  821. }
  822. }
  823. if (endMarkFound) {
  824. quint32 cnt;
  825. locations.stream >> cnt;
  826. for (quint32 i = 0; i < cnt; ++i) {
  827. quint64 kfirst, ksecond, vfirst, vsecond;
  828. locations.stream >> kfirst >> ksecond >> vfirst >> vsecond;
  829. _fileLocationAliases.insert(MediaKey(kfirst, ksecond), MediaKey(vfirst, vsecond));
  830. }
  831. if (!locations.stream.atEnd()) {
  832. quint32 webLocationsCount;
  833. locations.stream >> webLocationsCount;
  834. for (quint32 i = 0; i < webLocationsCount; ++i) {
  835. QString url;
  836. quint64 key;
  837. qint32 size;
  838. locations.stream >> url >> key >> size;
  839. ClearKey(key, _basePath);
  840. }
  841. if (!locations.stream.atEnd()) {
  842. locations.stream >> _downloadsSerialized;
  843. }
  844. }
  845. }
  846. }
  847. void Account::updateDownloads(
  848. Fn<std::optional<QByteArray>()> downloadsSerialize) {
  849. _downloadsSerialize = std::move(downloadsSerialize);
  850. writeLocationsDelayed();
  851. }
  852. QByteArray Account::downloadsSerialized() const {
  853. return _downloadsSerialized;
  854. }
  855. void Account::writeSessionSettings() {
  856. writeSessionSettings(nullptr);
  857. }
  858. void Account::writeSessionSettings(Main::SessionSettings *stored) {
  859. if (_readingUserSettings) {
  860. LOG(("App Error: attempt to write settings while reading them!"));
  861. return;
  862. }
  863. LOG(("App Info: writing encrypted user settings..."));
  864. if (!_settingsKey) {
  865. _settingsKey = GenerateKey(_basePath);
  866. writeMapQueued();
  867. }
  868. auto userDataInstance = stored
  869. ? stored
  870. : _owner->getSessionSettings();
  871. auto userData = userDataInstance
  872. ? userDataInstance->serialize()
  873. : QByteArray();
  874. auto recentStickers = cRecentStickersPreload();
  875. if (recentStickers.isEmpty() && _owner->sessionExists()) {
  876. const auto &stickers = _owner->session().data().stickers();
  877. recentStickers.reserve(stickers.getRecentPack().size());
  878. for (const auto &pair : std::as_const(stickers.getRecentPack())) {
  879. recentStickers.push_back(qMakePair(pair.first->id, pair.second));
  880. }
  881. }
  882. uint32 size = 24 * (sizeof(quint32) + sizeof(qint32));
  883. size += sizeof(quint32);
  884. size += sizeof(quint32) + sizeof(qint32) + recentStickers.size() * (sizeof(uint64) + sizeof(ushort));
  885. size += sizeof(quint32) + 3 * sizeof(qint32);
  886. size += sizeof(quint32) + 2 * sizeof(qint32);
  887. size += sizeof(quint32) + sizeof(qint64) + sizeof(qint32);
  888. if (!userData.isEmpty()) {
  889. size += sizeof(quint32) + Serialize::bytearraySize(userData);
  890. }
  891. EncryptedDescriptor data(size);
  892. data.stream << quint32(dbiCacheSettings) << qint64(_cacheTotalSizeLimit) << qint32(_cacheTotalTimeLimit) << qint64(_cacheBigFileTotalSizeLimit) << qint32(_cacheBigFileTotalTimeLimit);
  893. if (!userData.isEmpty()) {
  894. data.stream << quint32(dbiSessionSettings) << userData;
  895. }
  896. data.stream << quint32(dbiRecentStickers) << recentStickers;
  897. FileWriteDescriptor file(_settingsKey, _basePath);
  898. file.writeEncrypted(data, _localKey);
  899. }
  900. ReadSettingsContext Account::prepareReadSettingsContext() const {
  901. return ReadSettingsContext{
  902. .legacyHasCustomDayBackground = (_legacyBackgroundKeyDay != 0)
  903. };
  904. }
  905. std::unique_ptr<Main::SessionSettings> Account::readSessionSettings() {
  906. ReadSettingsContext context;
  907. FileReadDescriptor userSettings;
  908. if (!ReadEncryptedFile(userSettings, _settingsKey, _basePath, _localKey)) {
  909. LOG(("App Info: could not read encrypted user settings..."));
  910. Local::readOldUserSettings(true, context);
  911. auto result = applyReadContext(std::move(context));
  912. writeSessionSettings(result.get());
  913. return result;
  914. }
  915. LOG(("App Info: reading encrypted user settings..."));
  916. _readingUserSettings = true;
  917. while (!userSettings.stream.atEnd()) {
  918. quint32 blockId;
  919. userSettings.stream >> blockId;
  920. if (!CheckStreamStatus(userSettings.stream)) {
  921. _readingUserSettings = false;
  922. writeSessionSettings();
  923. return nullptr;
  924. }
  925. if (!ReadSetting(blockId, userSettings.stream, userSettings.version, context)) {
  926. _readingUserSettings = false;
  927. writeSessionSettings();
  928. return nullptr;
  929. }
  930. }
  931. _readingUserSettings = false;
  932. LOG(("App Info: encrypted user settings read."));
  933. auto result = applyReadContext(std::move(context));
  934. if (context.legacyRead) {
  935. writeSessionSettings(result.get());
  936. }
  937. return result;
  938. }
  939. std::unique_ptr<Main::SessionSettings> Account::applyReadContext(
  940. ReadSettingsContext &&context) {
  941. ApplyReadFallbackConfig(context);
  942. if (context.cacheTotalSizeLimit) {
  943. _cacheTotalSizeLimit = context.cacheTotalSizeLimit;
  944. _cacheTotalTimeLimit = context.cacheTotalTimeLimit;
  945. _cacheBigFileTotalSizeLimit = context.cacheBigFileTotalSizeLimit;
  946. _cacheBigFileTotalTimeLimit = context.cacheBigFileTotalTimeLimit;
  947. const auto &normal = Database::Settings();
  948. Assert(_cacheTotalSizeLimit > normal.maxDataSize);
  949. Assert(_cacheBigFileTotalSizeLimit > normal.maxDataSize);
  950. }
  951. if (!context.mtpAuthorization.isEmpty()) {
  952. _owner->setMtpAuthorization(context.mtpAuthorization);
  953. } else {
  954. for (auto &key : context.mtpLegacyKeys) {
  955. _owner->setLegacyMtpKey(std::move(key));
  956. }
  957. if (context.mtpLegacyMainDcId) {
  958. _owner->setMtpMainDcId(context.mtpLegacyMainDcId);
  959. _owner->setSessionUserId(context.mtpLegacyUserId);
  960. }
  961. }
  962. if (context.tileRead) {
  963. Window::Theme::Background()->setTileDayValue(context.tileDay);
  964. Window::Theme::Background()->setTileNightValue(context.tileNight);
  965. }
  966. return std::move(context.sessionSettingsStorage);
  967. }
  968. void Account::writeMtpData() {
  969. Expects(_localKey != nullptr);
  970. const auto serialized = _owner->serializeMtpAuthorization();
  971. const auto size = sizeof(quint32) + Serialize::bytearraySize(serialized);
  972. FileWriteDescriptor mtp(ToFilePart(_dataNameKey), BaseGlobalPath());
  973. EncryptedDescriptor data(size);
  974. data.stream << quint32(dbiMtpAuthorization) << serialized;
  975. mtp.writeEncrypted(data, _localKey);
  976. }
  977. void Account::readMtpData() {
  978. auto context = prepareReadSettingsContext();
  979. FileReadDescriptor mtp;
  980. if (!ReadEncryptedFile(mtp, ToFilePart(_dataNameKey), BaseGlobalPath(), _localKey)) {
  981. if (_localKey) {
  982. Local::readOldMtpData(true, context);
  983. applyReadContext(std::move(context));
  984. writeMtpData();
  985. }
  986. return;
  987. }
  988. LOG(("App Info: reading encrypted mtp data..."));
  989. while (!mtp.stream.atEnd()) {
  990. quint32 blockId;
  991. mtp.stream >> blockId;
  992. if (!CheckStreamStatus(mtp.stream)) {
  993. return writeMtpData();
  994. }
  995. if (!ReadSetting(blockId, mtp.stream, mtp.version, context)) {
  996. return writeMtpData();
  997. }
  998. }
  999. applyReadContext(std::move(context));
  1000. }
  1001. void Account::writeMtpConfig() {
  1002. Expects(_localKey != nullptr);
  1003. const auto serialized = _owner->mtp().config().serialize();
  1004. const auto size = Serialize::bytearraySize(serialized);
  1005. FileWriteDescriptor file(u"config"_q, _basePath);
  1006. EncryptedDescriptor data(size);
  1007. data.stream << serialized;
  1008. file.writeEncrypted(data, _localKey);
  1009. }
  1010. std::unique_ptr<MTP::Config> Account::readMtpConfig() {
  1011. Expects(_localKey != nullptr);
  1012. FileReadDescriptor file;
  1013. if (!ReadEncryptedFile(file, "config", _basePath, _localKey)) {
  1014. return nullptr;
  1015. }
  1016. LOG(("App Info: reading encrypted mtp config..."));
  1017. auto serialized = QByteArray();
  1018. file.stream >> serialized;
  1019. if (!CheckStreamStatus(file.stream)) {
  1020. return nullptr;
  1021. }
  1022. return MTP::Config::FromSerialized(serialized);
  1023. }
  1024. template <typename Callback>
  1025. void EnumerateDrafts(
  1026. const Data::HistoryDrafts &map,
  1027. bool supportMode,
  1028. const base::flat_map<Data::DraftKey, MessageDraftSource> &sources,
  1029. Callback &&callback) {
  1030. for (const auto &[key, draft] : map) {
  1031. if (key.isCloud() || sources.contains(key)) {
  1032. continue;
  1033. } else if (key.isLocal()
  1034. && (!supportMode || key.topicRootId())) {
  1035. const auto i = map.find(
  1036. Data::DraftKey::Cloud(key.topicRootId()));
  1037. const auto cloud = (i != end(map)) ? i->second.get() : nullptr;
  1038. if (Data::DraftsAreEqual(draft.get(), cloud)) {
  1039. continue;
  1040. }
  1041. }
  1042. callback(
  1043. key,
  1044. draft->reply,
  1045. draft->textWithTags,
  1046. draft->webpage,
  1047. draft->cursor);
  1048. }
  1049. for (const auto &[key, source] : sources) {
  1050. const auto draft = source.draft();
  1051. const auto cursor = source.cursor();
  1052. if (draft.reply.messageId
  1053. || !draft.textWithTags.text.isEmpty()
  1054. || cursor != MessageCursor()) {
  1055. callback(
  1056. key,
  1057. draft.reply,
  1058. draft.textWithTags,
  1059. draft.webpage,
  1060. cursor);
  1061. }
  1062. }
  1063. }
  1064. void Account::registerDraftSource(
  1065. not_null<History*> history,
  1066. Data::DraftKey key,
  1067. MessageDraftSource source) {
  1068. Expects(source.draft != nullptr);
  1069. Expects(source.cursor != nullptr);
  1070. _draftSources[history][key] = std::move(source);
  1071. }
  1072. void Account::unregisterDraftSource(
  1073. not_null<History*> history,
  1074. Data::DraftKey key) {
  1075. const auto i = _draftSources.find(history);
  1076. if (i != _draftSources.end()) {
  1077. i->second.remove(key);
  1078. if (i->second.empty()) {
  1079. _draftSources.erase(i);
  1080. }
  1081. }
  1082. }
  1083. void Account::writeDrafts(not_null<History*> history) {
  1084. const auto peerId = history->peer->id;
  1085. const auto &map = history->draftsMap();
  1086. const auto supportMode = history->session().supportMode();
  1087. const auto sourcesIt = _draftSources.find(history);
  1088. const auto &sources = (sourcesIt != _draftSources.end())
  1089. ? sourcesIt->second
  1090. : EmptyMessageDraftSources();
  1091. auto count = 0;
  1092. EnumerateDrafts(
  1093. map,
  1094. supportMode,
  1095. sources,
  1096. [&](auto&&...) { ++count; });
  1097. if (!count) {
  1098. auto i = _draftsMap.find(peerId);
  1099. if (i != _draftsMap.cend()) {
  1100. ClearKey(i->second, _basePath);
  1101. _draftsMap.erase(i);
  1102. writeMapDelayed();
  1103. }
  1104. _draftsNotReadMap.remove(peerId);
  1105. return;
  1106. }
  1107. auto i = _draftsMap.find(peerId);
  1108. if (i == _draftsMap.cend()) {
  1109. i = _draftsMap.emplace(peerId, GenerateKey(_basePath)).first;
  1110. writeMapQueued();
  1111. }
  1112. auto size = int(sizeof(quint64) * 2 + sizeof(quint32));
  1113. const auto sizeCallback = [&](
  1114. auto&&, // key
  1115. const FullReplyTo &reply,
  1116. const TextWithTags &text,
  1117. const Data::WebPageDraft &webpage,
  1118. auto&&) { // cursor
  1119. size += sizeof(qint64) // key
  1120. + Serialize::stringSize(text.text)
  1121. + TextUtilities::SerializeTagsSize(text.tags)
  1122. + sizeof(qint64) + sizeof(qint64) // messageId
  1123. + Serialize::stringSize(webpage.url)
  1124. + sizeof(qint32) // webpage.forceLargeMedia
  1125. + sizeof(qint32) // webpage.forceSmallMedia
  1126. + sizeof(qint32) // webpage.invert
  1127. + sizeof(qint32) // webpage.manual
  1128. + sizeof(qint32); // webpage.removed
  1129. };
  1130. EnumerateDrafts(
  1131. map,
  1132. supportMode,
  1133. sources,
  1134. sizeCallback);
  1135. EncryptedDescriptor data(size);
  1136. data.stream
  1137. << quint64(kRichDraftsTag)
  1138. << SerializePeerId(peerId)
  1139. << quint32(count);
  1140. const auto writeCallback = [&](
  1141. const Data::DraftKey &key,
  1142. const FullReplyTo &reply,
  1143. const TextWithTags &text,
  1144. const Data::WebPageDraft &webpage,
  1145. auto&&) { // cursor
  1146. data.stream
  1147. << key.serialize()
  1148. << text.text
  1149. << TextUtilities::SerializeTags(text.tags)
  1150. << qint64(reply.messageId.peer.value)
  1151. << qint64(reply.messageId.msg.bare)
  1152. << webpage.url
  1153. << qint32(webpage.forceLargeMedia ? 1 : 0)
  1154. << qint32(webpage.forceSmallMedia ? 1 : 0)
  1155. << qint32(webpage.invert ? 1 : 0)
  1156. << qint32(webpage.manual ? 1 : 0)
  1157. << qint32(webpage.removed ? 1 : 0);
  1158. };
  1159. EnumerateDrafts(
  1160. map,
  1161. supportMode,
  1162. sources,
  1163. writeCallback);
  1164. FileWriteDescriptor file(i->second, _basePath);
  1165. file.writeEncrypted(data, _localKey);
  1166. _draftsNotReadMap.remove(peerId);
  1167. }
  1168. void Account::writeDraftCursors(not_null<History*> history) {
  1169. const auto peerId = history->peer->id;
  1170. const auto &map = history->draftsMap();
  1171. const auto supportMode = history->session().supportMode();
  1172. const auto sourcesIt = _draftSources.find(history);
  1173. const auto &sources = (sourcesIt != _draftSources.end())
  1174. ? sourcesIt->second
  1175. : EmptyMessageDraftSources();
  1176. auto count = 0;
  1177. EnumerateDrafts(
  1178. map,
  1179. supportMode,
  1180. sources,
  1181. [&](auto&&...) { ++count; });
  1182. if (!count) {
  1183. clearDraftCursors(peerId);
  1184. return;
  1185. }
  1186. auto i = _draftCursorsMap.find(peerId);
  1187. if (i == _draftCursorsMap.cend()) {
  1188. i = _draftCursorsMap.emplace(peerId, GenerateKey(_basePath)).first;
  1189. writeMapQueued();
  1190. }
  1191. auto size = int(sizeof(quint64) * 2
  1192. + sizeof(quint32)
  1193. + (sizeof(qint64) + sizeof(qint32) * 3) * count);
  1194. EncryptedDescriptor data(size);
  1195. data.stream
  1196. << quint64(kMultiDraftCursorsTag)
  1197. << SerializePeerId(peerId)
  1198. << quint32(count);
  1199. const auto writeCallback = [&](
  1200. const Data::DraftKey &key,
  1201. auto&&, // reply
  1202. auto&&, // text
  1203. auto&&, // webpage
  1204. const MessageCursor &cursor) { // cursor
  1205. data.stream
  1206. << key.serialize()
  1207. << qint32(cursor.position)
  1208. << qint32(cursor.anchor)
  1209. << qint32(cursor.scroll);
  1210. };
  1211. EnumerateDrafts(
  1212. map,
  1213. supportMode,
  1214. sources,
  1215. writeCallback);
  1216. FileWriteDescriptor file(i->second, _basePath);
  1217. file.writeEncrypted(data, _localKey);
  1218. }
  1219. void Account::clearDraftCursors(PeerId peerId) {
  1220. const auto i = _draftCursorsMap.find(peerId);
  1221. if (i != _draftCursorsMap.cend()) {
  1222. ClearKey(i->second, _basePath);
  1223. _draftCursorsMap.erase(i);
  1224. writeMapDelayed();
  1225. }
  1226. }
  1227. void Account::readDraftCursors(PeerId peerId, Data::HistoryDrafts &map) {
  1228. const auto j = _draftCursorsMap.find(peerId);
  1229. if (j == _draftCursorsMap.cend()) {
  1230. return;
  1231. }
  1232. FileReadDescriptor draft;
  1233. if (!ReadEncryptedFile(draft, j->second, _basePath, _localKey)) {
  1234. clearDraftCursors(peerId);
  1235. return;
  1236. }
  1237. quint64 tag = 0;
  1238. draft.stream >> tag;
  1239. if (tag != kMultiDraftCursorsTag
  1240. && tag != kMultiDraftCursorsTagOld
  1241. && tag != kMultiDraftTagOld) {
  1242. readDraftCursorsLegacy(peerId, draft, tag, map);
  1243. return;
  1244. }
  1245. quint64 draftPeerSerialized = 0;
  1246. quint32 count = 0;
  1247. draft.stream >> draftPeerSerialized >> count;
  1248. const auto draftPeer = DeserializePeerId(draftPeerSerialized);
  1249. if (!count || count > 1000 || draftPeer != peerId) {
  1250. clearDraftCursors(peerId);
  1251. return;
  1252. }
  1253. const auto keysWritten = (tag == kMultiDraftCursorsTag);
  1254. const auto keysOld = (tag == kMultiDraftCursorsTagOld);
  1255. for (auto i = 0; i != count; ++i) {
  1256. qint64 keyValue = 0;
  1257. qint32 keyValueOld = 0;
  1258. if (keysWritten) {
  1259. draft.stream >> keyValue;
  1260. } else if (keysOld) {
  1261. draft.stream >> keyValueOld;
  1262. }
  1263. const auto key = keysWritten
  1264. ? Data::DraftKey::FromSerialized(keyValue)
  1265. : keysOld
  1266. ? Data::DraftKey::FromSerializedOld(keyValueOld)
  1267. : Data::DraftKey::Local(0);
  1268. qint32 position = 0, anchor = 0, scroll = Ui::kQFixedMax;
  1269. draft.stream >> position >> anchor >> scroll;
  1270. if (const auto i = map.find(key); i != end(map)) {
  1271. i->second->cursor = MessageCursor(position, anchor, scroll);
  1272. }
  1273. }
  1274. }
  1275. void Account::readDraftCursorsLegacy(
  1276. PeerId peerId,
  1277. details::FileReadDescriptor &draft,
  1278. quint64 draftPeerSerialized,
  1279. Data::HistoryDrafts &map) {
  1280. qint32 localPosition = 0, localAnchor = 0, localScroll = Ui::kQFixedMax;
  1281. qint32 editPosition = 0, editAnchor = 0, editScroll = Ui::kQFixedMax;
  1282. draft.stream >> localPosition >> localAnchor >> localScroll;
  1283. if (!draft.stream.atEnd()) {
  1284. draft.stream >> editPosition >> editAnchor >> editScroll;
  1285. }
  1286. const auto draftPeer = DeserializePeerId(draftPeerSerialized);
  1287. if (draftPeer != peerId) {
  1288. clearDraftCursors(peerId);
  1289. return;
  1290. }
  1291. if (const auto i = map.find(Data::DraftKey::Local({})); i != end(map)) {
  1292. i->second->cursor = MessageCursor(
  1293. localPosition,
  1294. localAnchor,
  1295. localScroll);
  1296. }
  1297. if (const auto i = map.find(Data::DraftKey::LocalEdit({}))
  1298. ; i != end(map)) {
  1299. i->second->cursor = MessageCursor(
  1300. editPosition,
  1301. editAnchor,
  1302. editScroll);
  1303. }
  1304. }
  1305. void Account::readDraftsWithCursors(not_null<History*> history) {
  1306. const auto guard = gsl::finally([&] {
  1307. if (const auto migrated = history->migrateFrom()) {
  1308. readDraftsWithCursors(migrated);
  1309. migrated->clearLocalEditDraft({});
  1310. history->takeLocalDraft(migrated);
  1311. }
  1312. });
  1313. PeerId peerId = history->peer->id;
  1314. if (!_draftsNotReadMap.remove(peerId)) {
  1315. clearDraftCursors(peerId);
  1316. return;
  1317. }
  1318. const auto j = _draftsMap.find(peerId);
  1319. if (j == _draftsMap.cend()) {
  1320. clearDraftCursors(peerId);
  1321. return;
  1322. }
  1323. FileReadDescriptor draft;
  1324. if (!ReadEncryptedFile(draft, j->second, _basePath, _localKey)) {
  1325. ClearKey(j->second, _basePath);
  1326. _draftsMap.erase(j);
  1327. clearDraftCursors(peerId);
  1328. return;
  1329. }
  1330. quint64 tag = 0;
  1331. draft.stream >> tag;
  1332. if (tag != kRichDraftsTag
  1333. && tag != kMultiDraftTag
  1334. && tag != kMultiDraftTagOld) {
  1335. readDraftsWithCursorsLegacy(history, draft, tag);
  1336. return;
  1337. }
  1338. quint32 count = 0;
  1339. quint64 draftPeerSerialized = 0;
  1340. draft.stream >> draftPeerSerialized >> count;
  1341. const auto draftPeer = DeserializePeerId(draftPeerSerialized);
  1342. if (!count || count > 1000 || draftPeer != peerId) {
  1343. ClearKey(j->second, _basePath);
  1344. _draftsMap.erase(j);
  1345. clearDraftCursors(peerId);
  1346. return;
  1347. }
  1348. auto map = Data::HistoryDrafts();
  1349. const auto keysOld = (tag == kMultiDraftTagOld);
  1350. const auto rich = (tag == kRichDraftsTag);
  1351. for (auto i = 0; i != count; ++i) {
  1352. TextWithTags text;
  1353. QByteArray textTagsSerialized;
  1354. qint64 keyValue = 0;
  1355. qint64 messageIdPeer = 0, messageIdMsg = 0;
  1356. qint32 keyValueOld = 0;
  1357. QString webpageUrl;
  1358. qint32 webpageForceLargeMedia = 0;
  1359. qint32 webpageForceSmallMedia = 0;
  1360. qint32 webpageInvert = 0;
  1361. qint32 webpageManual = 0;
  1362. qint32 webpageRemoved = 0;
  1363. if (keysOld) {
  1364. draft.stream >> keyValueOld;
  1365. } else {
  1366. draft.stream >> keyValue;
  1367. }
  1368. if (!rich) {
  1369. qint32 uncheckedPreviewState = 0;
  1370. draft.stream
  1371. >> text.text
  1372. >> textTagsSerialized
  1373. >> messageIdMsg
  1374. >> uncheckedPreviewState;
  1375. enum class PreviewState : char {
  1376. Allowed,
  1377. Cancelled,
  1378. EmptyOnEdit,
  1379. };
  1380. if (uncheckedPreviewState == int(PreviewState::Cancelled)) {
  1381. webpageRemoved = 1;
  1382. }
  1383. messageIdPeer = peerId.value;
  1384. } else {
  1385. draft.stream
  1386. >> text.text
  1387. >> textTagsSerialized
  1388. >> messageIdPeer
  1389. >> messageIdMsg
  1390. >> webpageUrl
  1391. >> webpageForceLargeMedia
  1392. >> webpageForceSmallMedia
  1393. >> webpageInvert
  1394. >> webpageManual
  1395. >> webpageRemoved;
  1396. }
  1397. text.tags = TextUtilities::DeserializeTags(
  1398. textTagsSerialized,
  1399. text.text.size());
  1400. const auto key = keysOld
  1401. ? Data::DraftKey::FromSerializedOld(keyValueOld)
  1402. : Data::DraftKey::FromSerialized(keyValue);
  1403. if (key && !key.isCloud()) {
  1404. map.emplace(key, std::make_unique<Data::Draft>(
  1405. text,
  1406. FullReplyTo{
  1407. .messageId = FullMsgId(
  1408. PeerId(messageIdPeer),
  1409. MsgId(messageIdMsg)),
  1410. .topicRootId = key.topicRootId(),
  1411. },
  1412. MessageCursor(),
  1413. Data::WebPageDraft{
  1414. .url = webpageUrl,
  1415. .forceLargeMedia = (webpageForceLargeMedia == 1),
  1416. .forceSmallMedia = (webpageForceSmallMedia == 1),
  1417. .invert = (webpageInvert == 1),
  1418. .manual = (webpageManual == 1),
  1419. .removed = (webpageRemoved == 1),
  1420. }));
  1421. }
  1422. }
  1423. if (draft.stream.status() != QDataStream::Ok) {
  1424. ClearKey(j->second, _basePath);
  1425. _draftsMap.erase(j);
  1426. clearDraftCursors(peerId);
  1427. return;
  1428. }
  1429. readDraftCursors(peerId, map);
  1430. history->setDraftsMap(std::move(map));
  1431. }
  1432. void Account::readDraftsWithCursorsLegacy(
  1433. not_null<History*> history,
  1434. details::FileReadDescriptor &draft,
  1435. quint64 draftPeerSerialized) {
  1436. TextWithTags msgData, editData;
  1437. QByteArray msgTagsSerialized, editTagsSerialized;
  1438. qint32 msgReplyTo = 0, msgPreviewCancelled = 0, editMsgId = 0, editPreviewCancelled = 0;
  1439. draft.stream >> msgData.text;
  1440. if (draft.version >= 9048) {
  1441. draft.stream >> msgTagsSerialized;
  1442. }
  1443. if (draft.version >= 7021) {
  1444. draft.stream >> msgReplyTo;
  1445. if (draft.version >= 8001) {
  1446. draft.stream >> msgPreviewCancelled;
  1447. if (!draft.stream.atEnd()) {
  1448. draft.stream >> editData.text;
  1449. if (draft.version >= 9048) {
  1450. draft.stream >> editTagsSerialized;
  1451. }
  1452. draft.stream >> editMsgId >> editPreviewCancelled;
  1453. }
  1454. }
  1455. }
  1456. const auto peerId = history->peer->id;
  1457. const auto draftPeer = DeserializePeerId(draftPeerSerialized);
  1458. if (draftPeer != peerId) {
  1459. const auto j = _draftsMap.find(peerId);
  1460. if (j != _draftsMap.cend()) {
  1461. ClearKey(j->second, _basePath);
  1462. _draftsMap.erase(j);
  1463. }
  1464. clearDraftCursors(peerId);
  1465. return;
  1466. }
  1467. msgData.tags = TextUtilities::DeserializeTags(
  1468. msgTagsSerialized,
  1469. msgData.text.size());
  1470. editData.tags = TextUtilities::DeserializeTags(
  1471. editTagsSerialized,
  1472. editData.text.size());
  1473. const auto topicRootId = MsgId();
  1474. auto map = base::flat_map<Data::DraftKey, std::unique_ptr<Data::Draft>>();
  1475. if (!msgData.text.isEmpty() || msgReplyTo) {
  1476. map.emplace(
  1477. Data::DraftKey::Local(topicRootId),
  1478. std::make_unique<Data::Draft>(
  1479. msgData,
  1480. FullReplyTo{ FullMsgId(peerId, MsgId(msgReplyTo)) },
  1481. MessageCursor(),
  1482. Data::WebPageDraft{
  1483. .removed = (msgPreviewCancelled == 1),
  1484. }));
  1485. }
  1486. if (editMsgId) {
  1487. map.emplace(
  1488. Data::DraftKey::LocalEdit(topicRootId),
  1489. std::make_unique<Data::Draft>(
  1490. editData,
  1491. FullReplyTo{ FullMsgId(peerId, editMsgId) },
  1492. MessageCursor(),
  1493. Data::WebPageDraft{
  1494. .removed = (editPreviewCancelled == 1),
  1495. }));
  1496. }
  1497. readDraftCursors(peerId, map);
  1498. history->setDraftsMap(std::move(map));
  1499. }
  1500. bool Account::hasDraftCursors(PeerId peer) {
  1501. return _draftCursorsMap.contains(peer);
  1502. }
  1503. bool Account::hasDraft(PeerId peer) {
  1504. return _draftsMap.contains(peer);
  1505. }
  1506. void Account::writeFileLocation(MediaKey location, const Core::FileLocation &local) {
  1507. if (local.fname.isEmpty()) {
  1508. return;
  1509. }
  1510. if (!local.inMediaCache()) {
  1511. const auto aliasIt = _fileLocationAliases.constFind(location);
  1512. if (aliasIt != _fileLocationAliases.cend()) {
  1513. location = aliasIt.value();
  1514. }
  1515. const auto i = _fileLocationPairs.find(local.fname);
  1516. if (i != _fileLocationPairs.cend()) {
  1517. if (i.value().second == local) {
  1518. if (i.value().first != location) {
  1519. _fileLocationAliases.insert(location, i.value().first);
  1520. writeLocationsQueued();
  1521. }
  1522. return;
  1523. }
  1524. if (i.value().first != location) {
  1525. for (auto j = _fileLocations.find(i.value().first), e = _fileLocations.end(); (j != e) && (j.key() == i.value().first); ++j) {
  1526. if (j.value() == i.value().second) {
  1527. _fileLocations.erase(j);
  1528. break;
  1529. }
  1530. }
  1531. _fileLocationPairs.erase(i);
  1532. }
  1533. }
  1534. _fileLocationPairs.insert(local.fname, { location, local });
  1535. } else {
  1536. for (auto i = _fileLocations.find(location); (i != _fileLocations.end()) && (i.key() == location);) {
  1537. if (i.value().inMediaCache() || i.value().check()) {
  1538. return;
  1539. }
  1540. i = _fileLocations.erase(i);
  1541. }
  1542. }
  1543. _fileLocations.insert(location, local);
  1544. writeLocationsQueued();
  1545. }
  1546. void Account::removeFileLocation(MediaKey location) {
  1547. auto i = _fileLocations.find(location);
  1548. if (i == _fileLocations.end()) {
  1549. return;
  1550. }
  1551. while (i != _fileLocations.end() && (i.key() == location)) {
  1552. i = _fileLocations.erase(i);
  1553. }
  1554. writeLocationsQueued();
  1555. }
  1556. Core::FileLocation Account::readFileLocation(MediaKey location) {
  1557. const auto aliasIt = _fileLocationAliases.constFind(location);
  1558. if (aliasIt != _fileLocationAliases.cend()) {
  1559. location = aliasIt.value();
  1560. }
  1561. for (auto i = _fileLocations.find(location); (i != _fileLocations.end()) && (i.key() == location);) {
  1562. if (!i.value().inMediaCache() && !i.value().check()) {
  1563. _fileLocationPairs.remove(i.value().fname);
  1564. i = _fileLocations.erase(i);
  1565. writeLocationsDelayed();
  1566. continue;
  1567. }
  1568. return i.value();
  1569. }
  1570. return Core::FileLocation();
  1571. }
  1572. EncryptionKey Account::cacheKey() const {
  1573. Expects(_localKey != nullptr);
  1574. return EncryptionKey(bytes::make_vector(_localKey->data()));
  1575. }
  1576. EncryptionKey Account::cacheBigFileKey() const {
  1577. return cacheKey();
  1578. }
  1579. QString Account::cachePath() const {
  1580. Expects(!_databasePath.isEmpty());
  1581. return _databasePath + "cache";
  1582. }
  1583. Cache::Database::Settings Account::cacheSettings() const {
  1584. auto result = Cache::Database::Settings();
  1585. result.clearOnWrongKey = true;
  1586. result.totalSizeLimit = _cacheTotalSizeLimit;
  1587. result.totalTimeLimit = _cacheTotalTimeLimit;
  1588. result.maxDataSize = kMaxFileInMemory;
  1589. return result;
  1590. }
  1591. void Account::updateCacheSettings(
  1592. Cache::Database::SettingsUpdate &update,
  1593. Cache::Database::SettingsUpdate &updateBig) {
  1594. Expects(update.totalSizeLimit > Database::Settings().maxDataSize);
  1595. Expects(update.totalTimeLimit >= 0);
  1596. Expects(updateBig.totalSizeLimit > Database::Settings().maxDataSize);
  1597. Expects(updateBig.totalTimeLimit >= 0);
  1598. if (_cacheTotalSizeLimit == update.totalSizeLimit
  1599. && _cacheTotalTimeLimit == update.totalTimeLimit
  1600. && _cacheBigFileTotalSizeLimit == updateBig.totalSizeLimit
  1601. && _cacheBigFileTotalTimeLimit == updateBig.totalTimeLimit) {
  1602. return;
  1603. }
  1604. _cacheTotalSizeLimit = update.totalSizeLimit;
  1605. _cacheTotalTimeLimit = update.totalTimeLimit;
  1606. _cacheBigFileTotalSizeLimit = updateBig.totalSizeLimit;
  1607. _cacheBigFileTotalTimeLimit = updateBig.totalTimeLimit;
  1608. writeSessionSettings();
  1609. }
  1610. QString Account::cacheBigFilePath() const {
  1611. Expects(!_databasePath.isEmpty());
  1612. return _databasePath + "media_cache";
  1613. }
  1614. Cache::Database::Settings Account::cacheBigFileSettings() const {
  1615. auto result = Cache::Database::Settings();
  1616. result.clearOnWrongKey = true;
  1617. result.totalSizeLimit = _cacheBigFileTotalSizeLimit;
  1618. result.totalTimeLimit = _cacheBigFileTotalTimeLimit;
  1619. result.maxDataSize = kMaxFileInMemory;
  1620. return result;
  1621. }
  1622. void Account::writeStickerSet(
  1623. QDataStream &stream,
  1624. const Data::StickersSet &set) {
  1625. using SetFlag = Data::StickersSetFlag;
  1626. const auto writeInfo = [&](int count) {
  1627. stream
  1628. << quint64(set.id)
  1629. << quint64(set.accessHash)
  1630. << quint64(set.hash)
  1631. << set.title
  1632. << set.shortName
  1633. << qint32(count)
  1634. << qint32(set.flags)
  1635. << qint32(set.installDate)
  1636. << quint64(set.thumbnailDocumentId)
  1637. << qint32(set.thumbnailType());
  1638. Serialize::writeImageLocation(stream, set.thumbnailLocation());
  1639. };
  1640. if (set.flags & SetFlag::NotLoaded) {
  1641. writeInfo(-set.count);
  1642. return;
  1643. } else if (set.stickers.isEmpty()) {
  1644. return;
  1645. }
  1646. writeInfo(set.stickers.size());
  1647. for (const auto &sticker : set.stickers) {
  1648. Serialize::Document::writeToStream(stream, sticker);
  1649. }
  1650. stream << qint32(set.dates.size());
  1651. if (!set.dates.empty()) {
  1652. Assert(set.dates.size() == set.stickers.size());
  1653. for (const auto date : set.dates) {
  1654. stream << qint32(date);
  1655. }
  1656. }
  1657. stream << qint32(set.emoji.size());
  1658. for (auto j = set.emoji.cbegin(), e = set.emoji.cend(); j != e; ++j) {
  1659. stream << j->first->id() << qint32(j->second.size());
  1660. for (const auto sticker : j->second) {
  1661. stream << quint64(sticker->id);
  1662. }
  1663. }
  1664. }
  1665. // In generic method _writeStickerSets() we look through all the sets and call a
  1666. // callback on each set to see, if we write it, skip it or abort the whole write.
  1667. enum class StickerSetCheckResult {
  1668. Write,
  1669. Skip,
  1670. Abort,
  1671. };
  1672. // CheckSet is a functor on Data::StickersSet, which returns a StickerSetCheckResult.
  1673. template <typename CheckSet>
  1674. void Account::writeStickerSets(
  1675. FileKey &stickersKey,
  1676. CheckSet checkSet,
  1677. const Data::StickersSetsOrder &order) {
  1678. using SetFlag = Data::StickersSetFlag;
  1679. const auto &sets = _owner->session().data().stickers().sets();
  1680. if (sets.empty()) {
  1681. if (stickersKey) {
  1682. ClearKey(stickersKey, _basePath);
  1683. stickersKey = 0;
  1684. writeMapDelayed();
  1685. }
  1686. return;
  1687. }
  1688. // versionTag + version + count
  1689. quint32 size = sizeof(quint32) + sizeof(qint32) + sizeof(qint32);
  1690. int32 setsCount = 0;
  1691. for (const auto &[id, set] : sets) {
  1692. const auto raw = set.get();
  1693. auto result = checkSet(*raw);
  1694. if (result == StickerSetCheckResult::Abort) {
  1695. return;
  1696. } else if (result == StickerSetCheckResult::Skip) {
  1697. continue;
  1698. }
  1699. // id
  1700. // + accessHash
  1701. // + hash
  1702. // + title
  1703. // + shortName
  1704. // + stickersCount
  1705. // + flags
  1706. // + installDate
  1707. // + thumbnailDocumentId
  1708. // + thumbnailType
  1709. // + thumbnailLocation
  1710. size += sizeof(quint64) * 3
  1711. + Serialize::stringSize(raw->title)
  1712. + Serialize::stringSize(raw->shortName)
  1713. + sizeof(qint32) * 3
  1714. + sizeof(quint64)
  1715. + sizeof(qint32)
  1716. + Serialize::imageLocationSize(raw->thumbnailLocation());
  1717. if (raw->flags & SetFlag::NotLoaded) {
  1718. continue;
  1719. }
  1720. for (const auto sticker : std::as_const(raw->stickers)) {
  1721. size += Serialize::Document::sizeInStream(sticker);
  1722. }
  1723. size += sizeof(qint32); // datesCount
  1724. if (!raw->dates.empty()) {
  1725. Assert(raw->stickers.size() == raw->dates.size());
  1726. size += raw->dates.size() * sizeof(qint32);
  1727. }
  1728. size += sizeof(qint32); // emojiCount
  1729. for (auto j = raw->emoji.cbegin(), e = raw->emoji.cend(); j != e; ++j) {
  1730. size += Serialize::stringSize(j->first->id()) + sizeof(qint32) + (j->second.size() * sizeof(quint64));
  1731. }
  1732. ++setsCount;
  1733. }
  1734. if (!setsCount && order.isEmpty()) {
  1735. if (stickersKey) {
  1736. ClearKey(stickersKey, _basePath);
  1737. stickersKey = 0;
  1738. writeMapDelayed();
  1739. }
  1740. return;
  1741. }
  1742. size += sizeof(qint32) + (order.size() * sizeof(quint64));
  1743. if (!stickersKey) {
  1744. stickersKey = GenerateKey(_basePath);
  1745. writeMapQueued();
  1746. }
  1747. EncryptedDescriptor data(size);
  1748. data.stream
  1749. << quint32(kStickersVersionTag)
  1750. << qint32(kStickersSerializeVersion)
  1751. << qint32(setsCount);
  1752. for (const auto &[id, set] : sets) {
  1753. auto result = checkSet(*set);
  1754. if (result == StickerSetCheckResult::Abort) {
  1755. return;
  1756. } else if (result == StickerSetCheckResult::Skip) {
  1757. continue;
  1758. }
  1759. writeStickerSet(data.stream, *set);
  1760. }
  1761. data.stream << order;
  1762. FileWriteDescriptor file(stickersKey, _basePath);
  1763. file.writeEncrypted(data, _localKey);
  1764. }
  1765. void Account::readStickerSets(
  1766. FileKey &stickersKey,
  1767. Data::StickersSetsOrder *outOrder,
  1768. Data::StickersSetFlags readingFlags) {
  1769. using SetFlag = Data::StickersSetFlag;
  1770. FileReadDescriptor stickers;
  1771. if (!ReadEncryptedFile(stickers, stickersKey, _basePath, _localKey)) {
  1772. ClearKey(stickersKey, _basePath);
  1773. stickersKey = 0;
  1774. writeMapDelayed();
  1775. return;
  1776. }
  1777. const auto failed = [&] {
  1778. ClearKey(stickersKey, _basePath);
  1779. stickersKey = 0;
  1780. };
  1781. auto &sets = _owner->session().data().stickers().setsRef();
  1782. if (outOrder) outOrder->clear();
  1783. quint32 versionTag = 0;
  1784. qint32 version = 0;
  1785. stickers.stream >> versionTag >> version;
  1786. if (versionTag != kStickersVersionTag || version < 2) {
  1787. // Old data, without sticker set thumbnails.
  1788. return failed();
  1789. }
  1790. qint32 count = 0;
  1791. stickers.stream >> count;
  1792. if (!CheckStreamStatus(stickers.stream)
  1793. || (count < 0)
  1794. || (count > kMaxSavedStickerSetsCount)) {
  1795. return failed();
  1796. }
  1797. for (auto i = 0; i != count; ++i) {
  1798. quint64 setId = 0, setAccessHash = 0, setHash = 0;
  1799. quint64 setThumbnailDocumentId = 0;
  1800. QString setTitle, setShortName;
  1801. qint32 scnt = 0;
  1802. qint32 setInstallDate = 0;
  1803. Data::StickersSetFlags setFlags = 0;
  1804. qint32 setFlagsValue = 0;
  1805. qint32 setThumbnailType = qint32(StickerType::Webp);
  1806. ImageLocation setThumbnail;
  1807. stickers.stream
  1808. >> setId
  1809. >> setAccessHash
  1810. >> setHash
  1811. >> setTitle
  1812. >> setShortName
  1813. >> scnt
  1814. >> setFlagsValue
  1815. >> setInstallDate;
  1816. if (version > 2) {
  1817. stickers.stream >> setThumbnailDocumentId;
  1818. if (version > 3) {
  1819. stickers.stream >> setThumbnailType;
  1820. }
  1821. }
  1822. constexpr auto kLegacyFlagWebm = (1 << 8);
  1823. if ((version < 4) && (setFlagsValue & kLegacyFlagWebm)) {
  1824. setThumbnailType = qint32(StickerType::Webm);
  1825. }
  1826. const auto thumbnail = Serialize::readImageLocation(
  1827. stickers.version,
  1828. stickers.stream);
  1829. if (!thumbnail || !CheckStreamStatus(stickers.stream)) {
  1830. return failed();
  1831. } else if (thumbnail->valid() && thumbnail->isLegacy()) {
  1832. // No thumb_version information in legacy location.
  1833. return failed();
  1834. } else {
  1835. setThumbnail = *thumbnail;
  1836. }
  1837. setFlags = Data::StickersSetFlags::from_raw(setFlagsValue);
  1838. if (setId == Data::Stickers::DefaultSetId) {
  1839. setTitle = tr::lng_stickers_default_set(tr::now);
  1840. setFlags |= SetFlag::Official | SetFlag::Special;
  1841. } else if (setId == Data::Stickers::CustomSetId) {
  1842. setTitle = u"Custom stickers"_q;
  1843. setFlags |= SetFlag::Special;
  1844. } else if ((setId == Data::Stickers::CloudRecentSetId)
  1845. || (setId == Data::Stickers::CloudRecentAttachedSetId)) {
  1846. setTitle = tr::lng_recent_stickers(tr::now);
  1847. setFlags |= SetFlag::Special;
  1848. } else if (setId == Data::Stickers::FavedSetId) {
  1849. setTitle = Lang::Hard::FavedSetTitle();
  1850. setFlags |= SetFlag::Special;
  1851. } else if (!setId) {
  1852. continue;
  1853. }
  1854. auto it = sets.find(setId);
  1855. auto settingSet = (it == sets.cend());
  1856. if (settingSet) {
  1857. // We will set this flags from order lists when reading those stickers.
  1858. setFlags &= ~(SetFlag::Installed | SetFlag::Featured);
  1859. it = sets.emplace(setId, std::make_unique<Data::StickersSet>(
  1860. &_owner->session().data(),
  1861. setId,
  1862. setAccessHash,
  1863. setHash,
  1864. setTitle,
  1865. setShortName,
  1866. 0,
  1867. setFlags,
  1868. setInstallDate)).first;
  1869. it->second->thumbnailDocumentId = setThumbnailDocumentId;
  1870. }
  1871. const auto set = it->second.get();
  1872. const auto inputSet = set->identifier();
  1873. const auto fillStickers = set->stickers.isEmpty();
  1874. if (scnt < 0) { // disabled not loaded set
  1875. if (!set->count || fillStickers) {
  1876. set->count = -scnt;
  1877. }
  1878. continue;
  1879. }
  1880. if (fillStickers) {
  1881. set->stickers.reserve(scnt);
  1882. set->count = 0;
  1883. }
  1884. Serialize::Document::StickerSetInfo info(
  1885. setId,
  1886. setAccessHash,
  1887. setShortName);
  1888. base::flat_set<DocumentId> read;
  1889. for (int32 j = 0; j < scnt; ++j) {
  1890. auto document = Serialize::Document::readStickerFromStream(
  1891. &_owner->session(),
  1892. stickers.version,
  1893. stickers.stream, info);
  1894. if (!CheckStreamStatus(stickers.stream)) {
  1895. return failed();
  1896. } else if (!document
  1897. || !document->sticker()
  1898. || read.contains(document->id)) {
  1899. continue;
  1900. }
  1901. read.emplace(document->id);
  1902. if (fillStickers) {
  1903. set->stickers.push_back(document);
  1904. if (!(set->flags & SetFlag::Special)) {
  1905. if (!document->sticker()->set.id) {
  1906. document->sticker()->set = inputSet;
  1907. }
  1908. }
  1909. ++set->count;
  1910. }
  1911. }
  1912. qint32 datesCount = 0;
  1913. stickers.stream >> datesCount;
  1914. if (datesCount > 0) {
  1915. if (datesCount != scnt) {
  1916. return failed();
  1917. }
  1918. const auto fillDates
  1919. = ((set->id == Data::Stickers::CloudRecentSetId)
  1920. || (set->id == Data::Stickers::CloudRecentAttachedSetId))
  1921. && (set->stickers.size() == datesCount);
  1922. if (fillDates) {
  1923. set->dates.clear();
  1924. set->dates.reserve(datesCount);
  1925. }
  1926. for (auto i = 0; i != datesCount; ++i) {
  1927. qint32 date = 0;
  1928. stickers.stream >> date;
  1929. if (fillDates) {
  1930. set->dates.push_back(TimeId(date));
  1931. }
  1932. }
  1933. }
  1934. qint32 emojiCount = 0;
  1935. stickers.stream >> emojiCount;
  1936. if (!CheckStreamStatus(stickers.stream) || emojiCount < 0) {
  1937. return failed();
  1938. }
  1939. for (int32 j = 0; j < emojiCount; ++j) {
  1940. QString emojiString;
  1941. qint32 stickersCount;
  1942. stickers.stream >> emojiString >> stickersCount;
  1943. Data::StickersPack pack;
  1944. pack.reserve(stickersCount);
  1945. for (int32 k = 0; k < stickersCount; ++k) {
  1946. quint64 id;
  1947. stickers.stream >> id;
  1948. const auto doc = _owner->session().data().document(id);
  1949. if (!doc->sticker()) continue;
  1950. pack.push_back(doc);
  1951. }
  1952. if (fillStickers) {
  1953. if (auto emoji = Ui::Emoji::Find(emojiString)) {
  1954. emoji = emoji->original();
  1955. set->emoji[emoji] = std::move(pack);
  1956. }
  1957. }
  1958. }
  1959. if (settingSet) {
  1960. if (version < 4
  1961. && setThumbnailType == qint32(StickerType::Webp)
  1962. && !set->stickers.empty()
  1963. && set->stickers.front()->sticker()) {
  1964. const auto first = set->stickers.front();
  1965. setThumbnailType = qint32(first->sticker()->type);
  1966. }
  1967. const auto thumbType = [&] {
  1968. switch (setThumbnailType) {
  1969. case qint32(StickerType::Webp): return StickerType::Webp;
  1970. case qint32(StickerType::Tgs): return StickerType::Tgs;
  1971. case qint32(StickerType::Webm): return StickerType::Webm;
  1972. }
  1973. return StickerType::Webp;
  1974. }();
  1975. set->setThumbnail(
  1976. ImageWithLocation{ .location = setThumbnail }, thumbType);
  1977. }
  1978. }
  1979. // Read orders of installed and featured stickers.
  1980. if (outOrder) {
  1981. auto outOrderCount = quint32();
  1982. stickers.stream >> outOrderCount;
  1983. if (!CheckStreamStatus(stickers.stream) || outOrderCount > 1000) {
  1984. return failed();
  1985. }
  1986. outOrder->reserve(outOrderCount);
  1987. for (auto i = 0; i != outOrderCount; ++i) {
  1988. auto value = uint64();
  1989. stickers.stream >> value;
  1990. if (!CheckStreamStatus(stickers.stream)) {
  1991. outOrder->clear();
  1992. return failed();
  1993. }
  1994. outOrder->push_back(value);
  1995. }
  1996. }
  1997. if (!CheckStreamStatus(stickers.stream)) {
  1998. return failed();
  1999. }
  2000. // Set flags that we dropped above from the order.
  2001. if (readingFlags && outOrder) {
  2002. for (const auto setId : std::as_const(*outOrder)) {
  2003. auto it = sets.find(setId);
  2004. if (it != sets.cend()) {
  2005. const auto set = it->second.get();
  2006. set->flags |= readingFlags;
  2007. if ((readingFlags == SetFlag::Installed)
  2008. && !set->installDate) {
  2009. set->installDate = kDefaultStickerInstallDate;
  2010. }
  2011. }
  2012. }
  2013. }
  2014. }
  2015. void Account::writeInstalledStickers() {
  2016. using SetFlag = Data::StickersSetFlag;
  2017. writeStickerSets(_installedStickersKey, [](const Data::StickersSet &set) {
  2018. if (set.id == Data::Stickers::CloudRecentSetId
  2019. || set.id == Data::Stickers::FavedSetId
  2020. || set.id == Data::Stickers::CloudRecentAttachedSetId
  2021. || set.id == Data::Stickers::CollectibleSetId) {
  2022. // separate files for them
  2023. return StickerSetCheckResult::Skip;
  2024. } else if (set.flags & SetFlag::Special) {
  2025. if (set.stickers.isEmpty()) { // all other special are "installed"
  2026. return StickerSetCheckResult::Skip;
  2027. }
  2028. } else if (!(set.flags & SetFlag::Installed)
  2029. || (set.flags & SetFlag::Archived)
  2030. || (set.type() != Data::StickersType::Stickers)) {
  2031. return StickerSetCheckResult::Skip;
  2032. } else if (set.flags & SetFlag::NotLoaded) {
  2033. // waiting to receive
  2034. return StickerSetCheckResult::Abort;
  2035. } else if (set.stickers.isEmpty()) {
  2036. return StickerSetCheckResult::Skip;
  2037. }
  2038. return StickerSetCheckResult::Write;
  2039. }, _owner->session().data().stickers().setsOrder());
  2040. }
  2041. void Account::writeFeaturedStickers() {
  2042. using SetFlag = Data::StickersSetFlag;
  2043. writeStickerSets(_featuredStickersKey, [](const Data::StickersSet &set) {
  2044. if (set.id == Data::Stickers::CloudRecentSetId
  2045. || set.id == Data::Stickers::FavedSetId
  2046. || set.id == Data::Stickers::CloudRecentAttachedSetId
  2047. || set.id == Data::Stickers::CollectibleSetId) {
  2048. // separate files for them
  2049. return StickerSetCheckResult::Skip;
  2050. } else if ((set.flags & SetFlag::Special)
  2051. || !(set.flags & SetFlag::Featured)
  2052. || (set.type() != Data::StickersType::Stickers)) {
  2053. return StickerSetCheckResult::Skip;
  2054. } else if (set.flags & SetFlag::NotLoaded) { // waiting to receive
  2055. return StickerSetCheckResult::Abort;
  2056. } else if (set.stickers.isEmpty()) {
  2057. return StickerSetCheckResult::Skip;
  2058. }
  2059. return StickerSetCheckResult::Write;
  2060. }, _owner->session().data().stickers().featuredSetsOrder());
  2061. }
  2062. void Account::writeFeaturedCustomEmoji() {
  2063. using SetFlag = Data::StickersSetFlag;
  2064. writeStickerSets(_featuredCustomEmojiKey, [](const Data::StickersSet &set) {
  2065. if (!(set.flags & SetFlag::Featured)
  2066. || (set.type() != Data::StickersType::Emoji)) {
  2067. return StickerSetCheckResult::Skip;
  2068. } else if (set.flags & SetFlag::NotLoaded) { // waiting to receive
  2069. return StickerSetCheckResult::Abort;
  2070. } else if (set.stickers.isEmpty()) {
  2071. return StickerSetCheckResult::Skip;
  2072. }
  2073. return StickerSetCheckResult::Write;
  2074. }, _owner->session().data().stickers().featuredEmojiSetsOrder());
  2075. }
  2076. void Account::writeRecentStickers() {
  2077. writeStickerSets(_recentStickersKey, [](const Data::StickersSet &set) {
  2078. if (set.id != Data::Stickers::CloudRecentSetId
  2079. || set.stickers.isEmpty()) {
  2080. return StickerSetCheckResult::Skip;
  2081. }
  2082. return StickerSetCheckResult::Write;
  2083. }, Data::StickersSetsOrder());
  2084. }
  2085. void Account::writeFavedStickers() {
  2086. writeStickerSets(_favedStickersKey, [](const Data::StickersSet &set) {
  2087. if (set.id != Data::Stickers::FavedSetId || set.stickers.isEmpty()) {
  2088. return StickerSetCheckResult::Skip;
  2089. }
  2090. return StickerSetCheckResult::Write;
  2091. }, Data::StickersSetsOrder());
  2092. }
  2093. void Account::writeArchivedStickers() {
  2094. using SetFlag = Data::StickersSetFlag;
  2095. writeStickerSets(_archivedStickersKey, [](const Data::StickersSet &set) {
  2096. if (!(set.flags & SetFlag::Archived)
  2097. || (set.type() != Data::StickersType::Stickers)
  2098. || set.stickers.isEmpty()) {
  2099. return StickerSetCheckResult::Skip;
  2100. }
  2101. return StickerSetCheckResult::Write;
  2102. }, _owner->session().data().stickers().archivedSetsOrder());
  2103. }
  2104. void Account::writeArchivedMasks() {
  2105. using SetFlag = Data::StickersSetFlag;
  2106. writeStickerSets(_archivedStickersKey, [](const Data::StickersSet &set) {
  2107. if (!(set.flags & SetFlag::Archived)
  2108. || (set.type() != Data::StickersType::Masks)
  2109. || set.stickers.isEmpty()) {
  2110. return StickerSetCheckResult::Skip;
  2111. }
  2112. return StickerSetCheckResult::Write;
  2113. }, _owner->session().data().stickers().archivedMaskSetsOrder());
  2114. }
  2115. void Account::writeInstalledMasks() {
  2116. using SetFlag = Data::StickersSetFlag;
  2117. writeStickerSets(_installedMasksKey, [](const Data::StickersSet &set) {
  2118. if (!(set.flags & SetFlag::Installed)
  2119. || (set.flags & SetFlag::Archived)
  2120. || (set.type() != Data::StickersType::Masks)
  2121. || set.stickers.isEmpty()) {
  2122. return StickerSetCheckResult::Skip;
  2123. }
  2124. return StickerSetCheckResult::Write;
  2125. }, _owner->session().data().stickers().maskSetsOrder());
  2126. }
  2127. void Account::writeRecentMasks() {
  2128. writeStickerSets(_recentMasksKey, [](const Data::StickersSet &set) {
  2129. if (set.id != Data::Stickers::CloudRecentAttachedSetId
  2130. || set.stickers.isEmpty()) {
  2131. return StickerSetCheckResult::Skip;
  2132. }
  2133. return StickerSetCheckResult::Write;
  2134. }, Data::StickersSetsOrder());
  2135. }
  2136. void Account::writeInstalledCustomEmoji() {
  2137. using SetFlag = Data::StickersSetFlag;
  2138. writeStickerSets(_installedCustomEmojiKey, [](const Data::StickersSet &set) {
  2139. if (!(set.flags & SetFlag::Installed)
  2140. || (set.flags & SetFlag::Archived)
  2141. || (set.type() != Data::StickersType::Emoji)) {
  2142. return StickerSetCheckResult::Skip;
  2143. } else if (set.flags & SetFlag::NotLoaded) {
  2144. // waiting to receive
  2145. return StickerSetCheckResult::Abort;
  2146. } else if (set.stickers.isEmpty()) {
  2147. return StickerSetCheckResult::Skip;
  2148. }
  2149. return StickerSetCheckResult::Write;
  2150. }, _owner->session().data().stickers().emojiSetsOrder());
  2151. }
  2152. void Account::importOldRecentStickers() {
  2153. using SetFlag = Data::StickersSetFlag;
  2154. if (!_recentStickersKeyOld) {
  2155. return;
  2156. }
  2157. FileReadDescriptor stickers;
  2158. if (!ReadEncryptedFile(stickers, _recentStickersKeyOld, _basePath, _localKey)) {
  2159. ClearKey(_recentStickersKeyOld, _basePath);
  2160. _recentStickersKeyOld = 0;
  2161. writeMapDelayed();
  2162. return;
  2163. }
  2164. auto &sets = _owner->session().data().stickers().setsRef();
  2165. sets.clear();
  2166. auto &order = _owner->session().data().stickers().setsOrderRef();
  2167. order.clear();
  2168. auto &recent = cRefRecentStickers();
  2169. recent.clear();
  2170. const auto def = sets.emplace(
  2171. Data::Stickers::DefaultSetId,
  2172. std::make_unique<Data::StickersSet>(
  2173. &_owner->session().data(),
  2174. Data::Stickers::DefaultSetId,
  2175. uint64(0), // accessHash
  2176. uint64(0), // hash
  2177. tr::lng_stickers_default_set(tr::now),
  2178. QString(),
  2179. 0, // count
  2180. (SetFlag::Official | SetFlag::Installed | SetFlag::Special),
  2181. kDefaultStickerInstallDate)).first->second.get();
  2182. const auto custom = sets.emplace(
  2183. Data::Stickers::CustomSetId,
  2184. std::make_unique<Data::StickersSet>(
  2185. &_owner->session().data(),
  2186. Data::Stickers::CustomSetId,
  2187. uint64(0), // accessHash
  2188. uint64(0), // hash
  2189. u"Custom stickers"_q,
  2190. QString(),
  2191. 0, // count
  2192. (SetFlag::Installed | SetFlag::Special),
  2193. kDefaultStickerInstallDate)).first->second.get();
  2194. QMap<uint64, bool> read;
  2195. while (!stickers.stream.atEnd()) {
  2196. quint64 id, access;
  2197. QString name, mime, alt;
  2198. qint32 date, dc, size, width, height, type;
  2199. qint16 value;
  2200. stickers.stream >> id >> value >> access >> date >> name >> mime >> dc >> size >> width >> height >> type;
  2201. if (stickers.version >= 7021) {
  2202. stickers.stream >> alt;
  2203. }
  2204. if (!value || read.contains(id)) continue;
  2205. read.insert(id, true);
  2206. QVector<MTPDocumentAttribute> attributes;
  2207. if (!name.isEmpty()) attributes.push_back(MTP_documentAttributeFilename(MTP_string(name)));
  2208. if (type == AnimatedDocument) {
  2209. attributes.push_back(MTP_documentAttributeAnimated());
  2210. } else if (type == StickerDocument) {
  2211. attributes.push_back(MTP_documentAttributeSticker(MTP_flags(0), MTP_string(alt), MTP_inputStickerSetEmpty(), MTPMaskCoords()));
  2212. }
  2213. if (width > 0 && height > 0) {
  2214. attributes.push_back(MTP_documentAttributeImageSize(MTP_int(width), MTP_int(height)));
  2215. }
  2216. const auto doc = _owner->session().data().document(
  2217. id,
  2218. access,
  2219. QByteArray(),
  2220. date,
  2221. attributes,
  2222. mime,
  2223. InlineImageLocation(),
  2224. ImageWithLocation(), // thumbnail
  2225. ImageWithLocation(), // videoThumbnail
  2226. false, // isPremiumSticker
  2227. dc,
  2228. size);
  2229. if (!doc->sticker()) {
  2230. continue;
  2231. }
  2232. if (value > 0) {
  2233. def->stickers.push_back(doc);
  2234. ++def->count;
  2235. } else {
  2236. custom->stickers.push_back(doc);
  2237. ++custom->count;
  2238. }
  2239. if (qAbs(value) > 1
  2240. && (recent.size()
  2241. < _owner->session().serverConfig().stickersRecentLimit)) {
  2242. recent.push_back(qMakePair(doc, qAbs(value)));
  2243. }
  2244. }
  2245. if (def->stickers.isEmpty()) {
  2246. sets.remove(Data::Stickers::DefaultSetId);
  2247. } else {
  2248. order.push_front(Data::Stickers::DefaultSetId);
  2249. }
  2250. if (custom->stickers.isEmpty()) {
  2251. sets.remove(Data::Stickers::CustomSetId);
  2252. }
  2253. writeInstalledStickers();
  2254. writeSessionSettings();
  2255. ClearKey(_recentStickersKeyOld, _basePath);
  2256. _recentStickersKeyOld = 0;
  2257. writeMapDelayed();
  2258. }
  2259. void Account::readInstalledStickers() {
  2260. if (!_installedStickersKey) {
  2261. return importOldRecentStickers();
  2262. }
  2263. _owner->session().data().stickers().setsRef().clear();
  2264. readStickerSets(
  2265. _installedStickersKey,
  2266. &_owner->session().data().stickers().setsOrderRef(),
  2267. Data::StickersSetFlag::Installed);
  2268. }
  2269. void Account::readFeaturedStickers() {
  2270. readStickerSets(
  2271. _featuredStickersKey,
  2272. &_owner->session().data().stickers().featuredSetsOrderRef(),
  2273. Data::StickersSetFlag::Featured);
  2274. const auto &sets = _owner->session().data().stickers().sets();
  2275. const auto &order = _owner->session().data().stickers().featuredSetsOrder();
  2276. int unreadCount = 0;
  2277. for (const auto setId : order) {
  2278. auto it = sets.find(setId);
  2279. if (it != sets.cend()
  2280. && (it->second->flags & Data::StickersSetFlag::Unread)) {
  2281. ++unreadCount;
  2282. }
  2283. }
  2284. _owner->session().data().stickers().setFeaturedSetsUnreadCount(unreadCount);
  2285. }
  2286. void Account::readFeaturedCustomEmoji() {
  2287. readStickerSets(
  2288. _featuredCustomEmojiKey,
  2289. &_owner->session().data().stickers().featuredEmojiSetsOrderRef(),
  2290. Data::StickersSetFlag::Featured);
  2291. }
  2292. void Account::readRecentStickers() {
  2293. readStickerSets(_recentStickersKey);
  2294. }
  2295. void Account::readRecentMasks() {
  2296. readStickerSets(_recentMasksKey);
  2297. }
  2298. void Account::readFavedStickers() {
  2299. readStickerSets(_favedStickersKey);
  2300. }
  2301. void Account::readArchivedStickers() {
  2302. // TODO: refactor to support for multiple accounts.
  2303. static bool archivedStickersRead = false;
  2304. if (!archivedStickersRead) {
  2305. readStickerSets(
  2306. _archivedStickersKey,
  2307. &_owner->session().data().stickers().archivedSetsOrderRef());
  2308. archivedStickersRead = true;
  2309. }
  2310. }
  2311. void Account::readArchivedMasks() {
  2312. // TODO: refactor to support for multiple accounts.
  2313. static bool archivedMasksRead = false;
  2314. if (!archivedMasksRead) {
  2315. readStickerSets(
  2316. _archivedMasksKey,
  2317. &_owner->session().data().stickers().archivedMaskSetsOrderRef());
  2318. archivedMasksRead = true;
  2319. }
  2320. }
  2321. void Account::readInstalledMasks() {
  2322. readStickerSets(
  2323. _installedMasksKey,
  2324. &_owner->session().data().stickers().maskSetsOrderRef(),
  2325. Data::StickersSetFlag::Installed);
  2326. }
  2327. void Account::readInstalledCustomEmoji() {
  2328. readStickerSets(
  2329. _installedCustomEmojiKey,
  2330. &_owner->session().data().stickers().emojiSetsOrderRef(),
  2331. Data::StickersSetFlag::Installed);
  2332. }
  2333. void Account::writeSavedGifs() {
  2334. const auto &saved = _owner->session().data().stickers().savedGifs();
  2335. if (saved.isEmpty()) {
  2336. if (_savedGifsKey) {
  2337. ClearKey(_savedGifsKey, _basePath);
  2338. _savedGifsKey = 0;
  2339. writeMapDelayed();
  2340. }
  2341. } else {
  2342. quint32 size = sizeof(quint32); // count
  2343. for (const auto gif : saved) {
  2344. size += Serialize::Document::sizeInStream(gif);
  2345. }
  2346. if (!_savedGifsKey) {
  2347. _savedGifsKey = GenerateKey(_basePath);
  2348. writeMapQueued();
  2349. }
  2350. EncryptedDescriptor data(size);
  2351. data.stream << quint32(saved.size());
  2352. for (const auto gif : saved) {
  2353. Serialize::Document::writeToStream(data.stream, gif);
  2354. }
  2355. FileWriteDescriptor file(_savedGifsKey, _basePath);
  2356. file.writeEncrypted(data, _localKey);
  2357. }
  2358. }
  2359. void Account::readSavedGifs() {
  2360. if (!_savedGifsKey) return;
  2361. FileReadDescriptor gifs;
  2362. if (!ReadEncryptedFile(gifs, _savedGifsKey, _basePath, _localKey)) {
  2363. ClearKey(_savedGifsKey, _basePath);
  2364. _savedGifsKey = 0;
  2365. writeMapDelayed();
  2366. return;
  2367. }
  2368. auto &saved = _owner->session().data().stickers().savedGifsRef();
  2369. const auto failed = [&] {
  2370. ClearKey(_savedGifsKey, _basePath);
  2371. _savedGifsKey = 0;
  2372. saved.clear();
  2373. };
  2374. saved.clear();
  2375. quint32 cnt;
  2376. gifs.stream >> cnt;
  2377. saved.reserve(cnt);
  2378. OrderedSet<DocumentId> read;
  2379. for (uint32 i = 0; i < cnt; ++i) {
  2380. auto document = Serialize::Document::readFromStream(
  2381. &_owner->session(),
  2382. gifs.version,
  2383. gifs.stream);
  2384. if (!CheckStreamStatus(gifs.stream)) {
  2385. return failed();
  2386. } else if (!document || !document->isGifv()) {
  2387. continue;
  2388. }
  2389. if (read.contains(document->id)) continue;
  2390. read.insert(document->id);
  2391. saved.push_back(document);
  2392. }
  2393. }
  2394. void Account::writeRecentHashtagsAndBots() {
  2395. const auto &write = cRecentWriteHashtags();
  2396. const auto &search = cRecentSearchHashtags();
  2397. const auto &bots = cRecentInlineBots();
  2398. if (write.isEmpty() && search.isEmpty() && bots.isEmpty()) {
  2399. readRecentHashtagsAndBots();
  2400. }
  2401. if (write.isEmpty() && search.isEmpty() && bots.isEmpty()) {
  2402. if (_recentHashtagsAndBotsKey) {
  2403. ClearKey(_recentHashtagsAndBotsKey, _basePath);
  2404. _recentHashtagsAndBotsKey = 0;
  2405. writeMapDelayed();
  2406. }
  2407. return;
  2408. }
  2409. if (!_recentHashtagsAndBotsKey) {
  2410. _recentHashtagsAndBotsKey = GenerateKey(_basePath);
  2411. writeMapQueued();
  2412. }
  2413. quint32 size = sizeof(quint32) * 3, writeCnt = 0, searchCnt = 0, botsCnt = cRecentInlineBots().size();
  2414. for (auto i = write.cbegin(), e = write.cend(); i != e; ++i) {
  2415. if (!i->first.isEmpty()) {
  2416. size += Serialize::stringSize(i->first) + sizeof(quint16);
  2417. ++writeCnt;
  2418. }
  2419. }
  2420. for (auto i = search.cbegin(), e = search.cend(); i != e; ++i) {
  2421. if (!i->first.isEmpty()) {
  2422. size += Serialize::stringSize(i->first) + sizeof(quint16);
  2423. ++searchCnt;
  2424. }
  2425. }
  2426. for (auto i = bots.cbegin(), e = bots.cend(); i != e; ++i) {
  2427. size += Serialize::peerSize(*i);
  2428. }
  2429. EncryptedDescriptor data(size);
  2430. data.stream << quint32(writeCnt) << quint32(searchCnt);
  2431. for (auto i = write.cbegin(), e = write.cend(); i != e; ++i) {
  2432. if (!i->first.isEmpty()) data.stream << i->first << quint16(i->second);
  2433. }
  2434. for (auto i = search.cbegin(), e = search.cend(); i != e; ++i) {
  2435. if (!i->first.isEmpty()) data.stream << i->first << quint16(i->second);
  2436. }
  2437. data.stream << quint32(botsCnt);
  2438. for (auto i = bots.cbegin(), e = bots.cend(); i != e; ++i) {
  2439. Serialize::writePeer(data.stream, *i);
  2440. }
  2441. FileWriteDescriptor file(_recentHashtagsAndBotsKey, _basePath);
  2442. file.writeEncrypted(data, _localKey);
  2443. }
  2444. void Account::readRecentHashtagsAndBots() {
  2445. if (_recentHashtagsAndBotsWereRead) return;
  2446. _recentHashtagsAndBotsWereRead = true;
  2447. if (!_recentHashtagsAndBotsKey) return;
  2448. FileReadDescriptor hashtags;
  2449. if (!ReadEncryptedFile(hashtags, _recentHashtagsAndBotsKey, _basePath, _localKey)) {
  2450. ClearKey(_recentHashtagsAndBotsKey, _basePath);
  2451. _recentHashtagsAndBotsKey = 0;
  2452. writeMapDelayed();
  2453. return;
  2454. }
  2455. quint32 writeCount = 0, searchCount = 0, botsCount = 0;
  2456. hashtags.stream >> writeCount >> searchCount;
  2457. QString tag;
  2458. quint16 count;
  2459. RecentHashtagPack write, search;
  2460. RecentInlineBots bots;
  2461. if (writeCount) {
  2462. write.reserve(writeCount);
  2463. for (uint32 i = 0; i < writeCount; ++i) {
  2464. hashtags.stream >> tag >> count;
  2465. write.push_back(qMakePair(tag.trimmed(), count));
  2466. }
  2467. }
  2468. if (searchCount) {
  2469. search.reserve(searchCount);
  2470. for (uint32 i = 0; i < searchCount; ++i) {
  2471. hashtags.stream >> tag >> count;
  2472. search.push_back(qMakePair(tag.trimmed(), count));
  2473. }
  2474. }
  2475. cSetRecentWriteHashtags(write);
  2476. cSetRecentSearchHashtags(search);
  2477. if (!hashtags.stream.atEnd()) {
  2478. hashtags.stream >> botsCount;
  2479. if (botsCount) {
  2480. bots.reserve(botsCount);
  2481. for (auto i = 0; i < botsCount; ++i) {
  2482. const auto peer = Serialize::readPeer(
  2483. &_owner->session(),
  2484. hashtags.version,
  2485. hashtags.stream);
  2486. if (!peer) {
  2487. return; // Broken data.
  2488. } else if (peer->isUser()
  2489. && peer->asUser()->isBot()
  2490. && !peer->asUser()->botInfo->inlinePlaceholder.isEmpty()
  2491. && !peer->asUser()->username().isEmpty()) {
  2492. bots.push_back(peer->asUser());
  2493. }
  2494. }
  2495. }
  2496. cSetRecentInlineBots(bots);
  2497. }
  2498. }
  2499. std::optional<RecentHashtagPack> Account::saveRecentHashtags(
  2500. Fn<RecentHashtagPack()> getPack,
  2501. const QString &text) {
  2502. auto found = false;
  2503. auto m = QRegularExpressionMatch();
  2504. auto recent = getPack();
  2505. for (auto i = 0, next = 0
  2506. ; (m = TextUtilities::RegExpHashtag(false).match(text, i)).hasMatch()
  2507. ; i = next) {
  2508. i = m.capturedStart();
  2509. next = m.capturedEnd();
  2510. if (m.hasMatch()) {
  2511. if (!m.capturedView(1).isEmpty()) {
  2512. ++i;
  2513. }
  2514. if (!m.capturedView(2).isEmpty()) {
  2515. --next;
  2516. }
  2517. }
  2518. const auto tag = text.mid(i + 1, next - i - 1);
  2519. if (TextUtilities::RegExpHashtagExclude().match(tag).hasMatch()) {
  2520. continue;
  2521. }
  2522. if (!found
  2523. && cRecentWriteHashtags().isEmpty()
  2524. && cRecentSearchHashtags().isEmpty()) {
  2525. readRecentHashtagsAndBots();
  2526. recent = getPack();
  2527. }
  2528. found = true;
  2529. Local::incrementRecentHashtag(recent, tag);
  2530. }
  2531. return found ? base::make_optional(recent) : std::nullopt;
  2532. }
  2533. void Account::saveRecentSentHashtags(const QString &text) {
  2534. const auto result = saveRecentHashtags(
  2535. [] { return cRecentWriteHashtags(); },
  2536. text);
  2537. if (result) {
  2538. cSetRecentWriteHashtags(*result);
  2539. writeRecentHashtagsAndBots();
  2540. }
  2541. }
  2542. void Account::saveRecentSearchHashtags(const QString &text) {
  2543. const auto result = saveRecentHashtags(
  2544. [] { return cRecentSearchHashtags(); },
  2545. text);
  2546. if (result) {
  2547. cSetRecentSearchHashtags(*result);
  2548. writeRecentHashtagsAndBots();
  2549. }
  2550. }
  2551. void Account::writeExportSettings(const Export::Settings &settings) {
  2552. const auto check = Export::Settings();
  2553. if (settings.types == check.types
  2554. && settings.fullChats == check.fullChats
  2555. && settings.media.types == check.media.types
  2556. && settings.media.sizeLimit == check.media.sizeLimit
  2557. && settings.path == check.path
  2558. && settings.format == check.format
  2559. && settings.availableAt == check.availableAt
  2560. && !settings.onlySinglePeer()) {
  2561. if (_exportSettingsKey) {
  2562. ClearKey(_exportSettingsKey, _basePath);
  2563. _exportSettingsKey = 0;
  2564. writeMapDelayed();
  2565. }
  2566. return;
  2567. }
  2568. if (!_exportSettingsKey) {
  2569. _exportSettingsKey = GenerateKey(_basePath);
  2570. writeMapQueued();
  2571. }
  2572. quint32 size = sizeof(quint32) * 6
  2573. + Serialize::stringSize(settings.path)
  2574. + sizeof(qint32) * 2 + sizeof(quint64);
  2575. EncryptedDescriptor data(size);
  2576. data.stream
  2577. << quint32(settings.types)
  2578. << quint32(settings.fullChats)
  2579. << quint32(settings.media.types)
  2580. << quint32(settings.media.sizeLimit)
  2581. << quint32(settings.format)
  2582. << settings.path
  2583. << quint32(settings.availableAt);
  2584. settings.singlePeer.match([&](const MTPDinputPeerUser & user) {
  2585. data.stream
  2586. << kSinglePeerTypeUser
  2587. << quint64(user.vuser_id().v)
  2588. << quint64(user.vaccess_hash().v);
  2589. }, [&](const MTPDinputPeerChat & chat) {
  2590. data.stream << kSinglePeerTypeChat << quint64(chat.vchat_id().v);
  2591. }, [&](const MTPDinputPeerChannel & channel) {
  2592. data.stream
  2593. << kSinglePeerTypeChannel
  2594. << quint64(channel.vchannel_id().v)
  2595. << quint64(channel.vaccess_hash().v);
  2596. }, [&](const MTPDinputPeerSelf &) {
  2597. data.stream << kSinglePeerTypeSelf;
  2598. }, [&](const MTPDinputPeerEmpty &) {
  2599. data.stream << kSinglePeerTypeEmpty;
  2600. }, [&](const MTPDinputPeerUserFromMessage &) {
  2601. Unexpected("From message peer in single peer export settings.");
  2602. }, [&](const MTPDinputPeerChannelFromMessage &) {
  2603. Unexpected("From message peer in single peer export settings.");
  2604. });
  2605. data.stream << qint32(settings.singlePeerFrom);
  2606. data.stream << qint32(settings.singlePeerTill);
  2607. FileWriteDescriptor file(_exportSettingsKey, _basePath);
  2608. file.writeEncrypted(data, _localKey);
  2609. }
  2610. Export::Settings Account::readExportSettings() {
  2611. FileReadDescriptor file;
  2612. if (!ReadEncryptedFile(file, _exportSettingsKey, _basePath, _localKey)) {
  2613. ClearKey(_exportSettingsKey, _basePath);
  2614. _exportSettingsKey = 0;
  2615. writeMapDelayed();
  2616. return Export::Settings();
  2617. }
  2618. quint32 types = 0, fullChats = 0;
  2619. quint32 mediaTypes = 0, mediaSizeLimit = 0;
  2620. quint32 format = 0, availableAt = 0;
  2621. QString path;
  2622. qint32 singlePeerType = 0, singlePeerBareIdOld = 0;
  2623. quint64 singlePeerBareId = 0;
  2624. quint64 singlePeerAccessHash = 0;
  2625. qint32 singlePeerFrom = 0, singlePeerTill = 0;
  2626. file.stream
  2627. >> types
  2628. >> fullChats
  2629. >> mediaTypes
  2630. >> mediaSizeLimit
  2631. >> format
  2632. >> path
  2633. >> availableAt;
  2634. if (!file.stream.atEnd()) {
  2635. file.stream >> singlePeerType;
  2636. switch (singlePeerType) {
  2637. case kSinglePeerTypeUserOld:
  2638. case kSinglePeerTypeChannelOld: {
  2639. file.stream >> singlePeerBareIdOld >> singlePeerAccessHash;
  2640. } break;
  2641. case kSinglePeerTypeChatOld: file.stream >> singlePeerBareIdOld; break;
  2642. case kSinglePeerTypeUser:
  2643. case kSinglePeerTypeChannel: {
  2644. file.stream >> singlePeerBareId >> singlePeerAccessHash;
  2645. } break;
  2646. case kSinglePeerTypeChat: file.stream >> singlePeerBareId; break;
  2647. case kSinglePeerTypeSelf:
  2648. case kSinglePeerTypeEmpty: break;
  2649. default: return Export::Settings();
  2650. }
  2651. }
  2652. if (!file.stream.atEnd()) {
  2653. file.stream >> singlePeerFrom >> singlePeerTill;
  2654. }
  2655. auto result = Export::Settings();
  2656. result.types = Export::Settings::Types::from_raw(types);
  2657. result.fullChats = Export::Settings::Types::from_raw(fullChats);
  2658. result.media.types = Export::MediaSettings::Types::from_raw(mediaTypes);
  2659. result.media.sizeLimit = mediaSizeLimit;
  2660. result.format = Export::Output::Format(format);
  2661. result.path = path;
  2662. result.availableAt = availableAt;
  2663. result.singlePeer = [&] {
  2664. switch (singlePeerType) {
  2665. case kSinglePeerTypeUserOld:
  2666. return MTP_inputPeerUser(
  2667. MTP_long(singlePeerBareIdOld),
  2668. MTP_long(singlePeerAccessHash));
  2669. case kSinglePeerTypeChatOld:
  2670. return MTP_inputPeerChat(MTP_long(singlePeerBareIdOld));
  2671. case kSinglePeerTypeChannelOld:
  2672. return MTP_inputPeerChannel(
  2673. MTP_long(singlePeerBareIdOld),
  2674. MTP_long(singlePeerAccessHash));
  2675. case kSinglePeerTypeUser:
  2676. return MTP_inputPeerUser(
  2677. MTP_long(singlePeerBareId),
  2678. MTP_long(singlePeerAccessHash));
  2679. case kSinglePeerTypeChat:
  2680. return MTP_inputPeerChat(MTP_long(singlePeerBareId));
  2681. case kSinglePeerTypeChannel:
  2682. return MTP_inputPeerChannel(
  2683. MTP_long(singlePeerBareId),
  2684. MTP_long(singlePeerAccessHash));
  2685. case kSinglePeerTypeSelf:
  2686. return MTP_inputPeerSelf();
  2687. case kSinglePeerTypeEmpty:
  2688. return MTP_inputPeerEmpty();
  2689. }
  2690. Unexpected("Type in export data single peer.");
  2691. }();
  2692. result.singlePeerFrom = singlePeerFrom;
  2693. result.singlePeerTill = singlePeerTill;
  2694. return (file.stream.status() == QDataStream::Ok && result.validate())
  2695. ? result
  2696. : Export::Settings();
  2697. }
  2698. void Account::setMediaLastPlaybackPosition(DocumentId id, crl::time time) {
  2699. auto &map = _mediaLastPlaybackPosition;
  2700. const auto i = ranges::find(
  2701. map,
  2702. id,
  2703. &std::pair<DocumentId, crl::time>::first);
  2704. if (i != map.end()) {
  2705. if (time > 0) {
  2706. if (i->second == time) {
  2707. return;
  2708. }
  2709. i->second = time;
  2710. std::rotate(i, i + 1, map.end());
  2711. } else {
  2712. map.erase(i);
  2713. }
  2714. } else if (time > 0) {
  2715. if (map.size() >= kMaxSavedPlaybackPositions) {
  2716. map.erase(map.begin());
  2717. }
  2718. map.emplace_back(id, time);
  2719. }
  2720. writeMediaLastPlaybackPositions();
  2721. }
  2722. crl::time Account::mediaLastPlaybackPosition(DocumentId id) const {
  2723. const_cast<Account*>(this)->readMediaLastPlaybackPositions();
  2724. const auto i = ranges::find(
  2725. _mediaLastPlaybackPosition,
  2726. id,
  2727. &std::pair<DocumentId, crl::time>::first);
  2728. return (i != _mediaLastPlaybackPosition.end()) ? i->second : 0;
  2729. }
  2730. void Account::writeMediaLastPlaybackPositions() {
  2731. if (_mediaLastPlaybackPosition.empty()) {
  2732. if (_mediaLastPlaybackPositionsKey) {
  2733. ClearKey(_mediaLastPlaybackPositionsKey, _basePath);
  2734. _mediaLastPlaybackPositionsKey = 0;
  2735. writeMapDelayed();
  2736. }
  2737. return;
  2738. }
  2739. if (!_mediaLastPlaybackPositionsKey) {
  2740. _mediaLastPlaybackPositionsKey = GenerateKey(_basePath);
  2741. writeMapQueued();
  2742. }
  2743. quint32 size = sizeof(quint32)
  2744. + _mediaLastPlaybackPosition.size() * sizeof(quint64) * 2;
  2745. EncryptedDescriptor data(size);
  2746. data.stream << quint32(_mediaLastPlaybackPosition.size());
  2747. for (const auto &[id, time] : _mediaLastPlaybackPosition) {
  2748. data.stream << quint64(id) << qint64(time);
  2749. }
  2750. FileWriteDescriptor file(_mediaLastPlaybackPositionsKey, _basePath);
  2751. file.writeEncrypted(data, _localKey);
  2752. }
  2753. void Account::readMediaLastPlaybackPositions() {
  2754. if (_mediaLastPlaybackPositionsRead) {
  2755. return;
  2756. }
  2757. _mediaLastPlaybackPositionsRead = true;
  2758. if (!_mediaLastPlaybackPositionsKey) {
  2759. return;
  2760. }
  2761. FileReadDescriptor file;
  2762. if (!ReadEncryptedFile(
  2763. file,
  2764. _mediaLastPlaybackPositionsKey,
  2765. _basePath,
  2766. _localKey)) {
  2767. ClearKey(_mediaLastPlaybackPositionsKey, _basePath);
  2768. _mediaLastPlaybackPositionsKey = 0;
  2769. writeMapDelayed();
  2770. return;
  2771. }
  2772. quint32 size = 0;
  2773. file.stream >> size;
  2774. for (auto i = 0; i < size; ++i) {
  2775. quint64 id = 0;
  2776. qint64 time = 0;
  2777. file.stream >> id >> time;
  2778. _mediaLastPlaybackPosition.emplace_back(DocumentId(id), time);
  2779. }
  2780. }
  2781. void Account::writeSearchSuggestionsDelayed() {
  2782. Expects(_owner->sessionExists());
  2783. if (!_writeSearchSuggestionsTimer.isActive()) {
  2784. _writeSearchSuggestionsTimer.callOnce(kWriteSearchSuggestionsDelay);
  2785. }
  2786. }
  2787. void Account::writeSearchSuggestionsIfNeeded() {
  2788. if (_writeSearchSuggestionsTimer.isActive()) {
  2789. _writeSearchSuggestionsTimer.cancel();
  2790. writeSearchSuggestions();
  2791. }
  2792. }
  2793. void Account::writeSearchSuggestions() {
  2794. Expects(_owner->sessionExists());
  2795. const auto top = _owner->session().topPeers().serialize();
  2796. const auto recent = _owner->session().recentPeers().serialize();
  2797. if (top.isEmpty() && recent.isEmpty()) {
  2798. if (_searchSuggestionsKey) {
  2799. ClearKey(_searchSuggestionsKey, _basePath);
  2800. _searchSuggestionsKey = 0;
  2801. writeMapDelayed();
  2802. }
  2803. return;
  2804. }
  2805. if (!_searchSuggestionsKey) {
  2806. _searchSuggestionsKey = GenerateKey(_basePath);
  2807. writeMapQueued();
  2808. }
  2809. quint32 size = Serialize::bytearraySize(top)
  2810. + Serialize::bytearraySize(recent);
  2811. EncryptedDescriptor data(size);
  2812. data.stream << top << recent;
  2813. FileWriteDescriptor file(_searchSuggestionsKey, _basePath);
  2814. file.writeEncrypted(data, _localKey);
  2815. }
  2816. void Account::readSearchSuggestions() {
  2817. if (_searchSuggestionsRead) {
  2818. return;
  2819. }
  2820. _searchSuggestionsRead = true;
  2821. if (!_searchSuggestionsKey) {
  2822. DEBUG_LOG(("Suggestions: No key."));
  2823. return;
  2824. }
  2825. FileReadDescriptor suggestions;
  2826. if (!ReadEncryptedFile(suggestions, _searchSuggestionsKey, _basePath, _localKey)) {
  2827. DEBUG_LOG(("Suggestions: Could not read file."));
  2828. ClearKey(_searchSuggestionsKey, _basePath);
  2829. _searchSuggestionsKey = 0;
  2830. writeMapDelayed();
  2831. return;
  2832. }
  2833. auto top = QByteArray();
  2834. auto recent = QByteArray();
  2835. suggestions.stream >> top >> recent;
  2836. if (CheckStreamStatus(suggestions.stream)) {
  2837. _owner->session().topPeers().applyLocal(top);
  2838. _owner->session().recentPeers().applyLocal(recent);
  2839. } else {
  2840. DEBUG_LOG(("Suggestions: Could not read content."));
  2841. }
  2842. }
  2843. void Account::writeSelf() {
  2844. writeMapDelayed();
  2845. }
  2846. void Account::readSelf(
  2847. not_null<Main::Session*> session,
  2848. const QByteArray &serialized,
  2849. int32 streamVersion) {
  2850. QDataStream stream(serialized);
  2851. const auto user = session->user();
  2852. const auto wasLoadedStatus = user->loadedStatus();
  2853. user->setLoadedStatus(PeerData::LoadedStatus::Not);
  2854. const auto self = Serialize::readPeer(
  2855. session,
  2856. streamVersion,
  2857. stream);
  2858. if (!self || !self->isSelf() || self != user) {
  2859. user->setLoadedStatus(wasLoadedStatus);
  2860. return;
  2861. }
  2862. QString about;
  2863. stream >> about;
  2864. if (CheckStreamStatus(stream)) {
  2865. self->asUser()->setAbout(about);
  2866. }
  2867. }
  2868. void Account::writeTrustedPeers() {
  2869. if (_trustedPeers.empty() && _trustedPayPerMessage.empty()) {
  2870. if (_trustedPeersKey) {
  2871. ClearKey(_trustedPeersKey, _basePath);
  2872. _trustedPeersKey = 0;
  2873. writeMapDelayed();
  2874. }
  2875. return;
  2876. }
  2877. if (!_trustedPeersKey) {
  2878. _trustedPeersKey = GenerateKey(_basePath);
  2879. writeMapQueued();
  2880. }
  2881. quint32 size = sizeof(qint32)
  2882. + _trustedPeers.size() * sizeof(quint64)
  2883. + sizeof(qint32)
  2884. + _trustedPayPerMessage.size() * (sizeof(quint64) + sizeof(qint32));
  2885. EncryptedDescriptor data(size);
  2886. data.stream << qint32(_trustedPeers.size());
  2887. for (const auto &[peerId, mask] : _trustedPeers) {
  2888. // value: 8 bit mask, 56 bit peer_id.
  2889. auto value = SerializePeerId(peerId);
  2890. Assert((value >> 56) == 0);
  2891. value |= (quint64(mask) << 56);
  2892. data.stream << value;
  2893. }
  2894. data.stream << qint32(_trustedPayPerMessage.size());
  2895. for (const auto &[peerId, stars] : _trustedPayPerMessage) {
  2896. data.stream << SerializePeerId(peerId) << qint32(stars);
  2897. }
  2898. FileWriteDescriptor file(_trustedPeersKey, _basePath);
  2899. file.writeEncrypted(data, _localKey);
  2900. }
  2901. void Account::readTrustedPeers() {
  2902. if (_trustedPeersRead) {
  2903. return;
  2904. }
  2905. _trustedPeersRead = true;
  2906. if (!_trustedPeersKey) {
  2907. return;
  2908. }
  2909. FileReadDescriptor trusted;
  2910. if (!ReadEncryptedFile(trusted, _trustedPeersKey, _basePath, _localKey)) {
  2911. ClearKey(_trustedPeersKey, _basePath);
  2912. _trustedPeersKey = 0;
  2913. writeMapDelayed();
  2914. return;
  2915. }
  2916. qint32 trustedCount = 0;
  2917. trusted.stream >> trustedCount;
  2918. for (int i = 0; i < trustedCount; ++i) {
  2919. auto value = quint64();
  2920. trusted.stream >> value;
  2921. const auto mask = base::flags<PeerTrustFlag>::from_raw(
  2922. uchar(value >> 56));
  2923. const auto peerIdSerialized = value & ~(0xFFULL << 56);
  2924. const auto peerId = DeserializePeerId(peerIdSerialized);
  2925. _trustedPeers.emplace(peerId, mask);
  2926. }
  2927. if (trusted.stream.atEnd()) {
  2928. return;
  2929. }
  2930. qint32 payPerMessageCount = 0;
  2931. trusted.stream >> payPerMessageCount;
  2932. const auto owner = _owner->sessionExists()
  2933. ? &_owner->session().data()
  2934. : nullptr;
  2935. for (int i = 0; i < payPerMessageCount; ++i) {
  2936. auto value = quint64();
  2937. auto stars = qint32();
  2938. trusted.stream >> value >> stars;
  2939. const auto peerId = DeserializePeerId(value);
  2940. const auto peer = owner ? owner->peerLoaded(peerId) : nullptr;
  2941. const auto now = peer ? peer->starsPerMessage() : stars;
  2942. if (now > 0 && now <= stars) {
  2943. _trustedPayPerMessage.emplace(peerId, stars);
  2944. }
  2945. }
  2946. if (_trustedPayPerMessage.size() != payPerMessageCount) {
  2947. writeTrustedPeers();
  2948. }
  2949. }
  2950. void Account::markPeerTrustedOpenGame(PeerId peerId) {
  2951. if (isPeerTrustedOpenGame(peerId)) {
  2952. return;
  2953. }
  2954. const auto i = _trustedPeers.find(peerId);
  2955. if (i == end(_trustedPeers)) {
  2956. _trustedPeers.emplace(peerId, PeerTrustFlag());
  2957. } else {
  2958. i->second &= ~PeerTrustFlag::NoOpenGame;
  2959. }
  2960. writeTrustedPeers();
  2961. }
  2962. bool Account::isPeerTrustedOpenGame(PeerId peerId) {
  2963. readTrustedPeers();
  2964. const auto i = _trustedPeers.find(peerId);
  2965. return (i != end(_trustedPeers))
  2966. && ((i->second & PeerTrustFlag::NoOpenGame) == 0);
  2967. }
  2968. void Account::markPeerTrustedPayment(PeerId peerId) {
  2969. if (isPeerTrustedPayment(peerId)) {
  2970. return;
  2971. }
  2972. const auto i = _trustedPeers.find(peerId);
  2973. if (i == end(_trustedPeers)) {
  2974. _trustedPeers.emplace(
  2975. peerId,
  2976. PeerTrustFlag::NoOpenGame | PeerTrustFlag::Payment);
  2977. } else {
  2978. i->second |= PeerTrustFlag::Payment;
  2979. }
  2980. writeTrustedPeers();
  2981. }
  2982. bool Account::isPeerTrustedPayment(PeerId peerId) {
  2983. readTrustedPeers();
  2984. const auto i = _trustedPeers.find(peerId);
  2985. return (i != end(_trustedPeers))
  2986. && ((i->second & PeerTrustFlag::Payment) != 0);
  2987. }
  2988. void Account::markPeerTrustedOpenWebView(PeerId peerId) {
  2989. if (isPeerTrustedOpenWebView(peerId)) {
  2990. return;
  2991. }
  2992. const auto i = _trustedPeers.find(peerId);
  2993. if (i == end(_trustedPeers)) {
  2994. _trustedPeers.emplace(
  2995. peerId,
  2996. PeerTrustFlag::NoOpenGame | PeerTrustFlag::OpenWebView);
  2997. } else {
  2998. i->second |= PeerTrustFlag::OpenWebView;
  2999. }
  3000. writeTrustedPeers();
  3001. }
  3002. bool Account::isPeerTrustedOpenWebView(PeerId peerId) {
  3003. readTrustedPeers();
  3004. const auto i = _trustedPeers.find(peerId);
  3005. return (i != end(_trustedPeers))
  3006. && ((i->second & PeerTrustFlag::OpenWebView) != 0);
  3007. }
  3008. void Account::markPeerTrustedPayForMessage(
  3009. PeerId peerId,
  3010. int starsPerMessage) {
  3011. if (isPeerTrustedPayForMessage(peerId, starsPerMessage)) {
  3012. return;
  3013. }
  3014. const auto i = _trustedPayPerMessage.find(peerId);
  3015. if (i == end(_trustedPayPerMessage)) {
  3016. _trustedPayPerMessage.emplace(peerId, starsPerMessage);
  3017. } else {
  3018. i->second = starsPerMessage;
  3019. }
  3020. writeTrustedPeers();
  3021. }
  3022. bool Account::isPeerTrustedPayForMessage(
  3023. PeerId peerId,
  3024. int starsPerMessage) {
  3025. if (starsPerMessage <= 0) {
  3026. return true;
  3027. }
  3028. readTrustedPeers();
  3029. const auto i = _trustedPayPerMessage.find(peerId);
  3030. return (i != end(_trustedPayPerMessage))
  3031. && (i->second >= starsPerMessage);
  3032. }
  3033. bool Account::peerTrustedPayForMessageRead() const {
  3034. return _trustedPeersRead;
  3035. }
  3036. bool Account::hasPeerTrustedPayForMessageEntry(PeerId peerId) const {
  3037. return _trustedPayPerMessage.contains(peerId);
  3038. }
  3039. void Account::clearPeerTrustedPayForMessage(PeerId peerId) {
  3040. const auto i = _trustedPayPerMessage.find(peerId);
  3041. if (i != end(_trustedPayPerMessage)) {
  3042. _trustedPayPerMessage.erase(i);
  3043. writeTrustedPeers();
  3044. }
  3045. }
  3046. void Account::enforceModernStorageIdBots() {
  3047. if (_webviewStorageIdBots.token.isEmpty()) {
  3048. _webviewStorageIdBots.token = QByteArray::fromStdString(
  3049. Webview::GenerateStorageToken());
  3050. writeMapDelayed();
  3051. }
  3052. }
  3053. Webview::StorageId Account::resolveStorageIdBots() {
  3054. if (!_webviewStorageIdBots) {
  3055. auto &token = _webviewStorageIdBots.token;
  3056. const auto legacy = Webview::LegacyStorageIdToken();
  3057. if (token.isEmpty()) {
  3058. auto legacyTaken = false;
  3059. const auto &list = _owner->domain().accounts();
  3060. for (const auto &[index, account] : list) {
  3061. if (account.get() != _owner.get()) {
  3062. const auto &id = account->local()._webviewStorageIdBots;
  3063. if (id.token == legacy) {
  3064. legacyTaken = true;
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. token = legacyTaken
  3070. ? QByteArray::fromStdString(Webview::GenerateStorageToken())
  3071. : legacy;
  3072. writeMapDelayed();
  3073. }
  3074. _webviewStorageIdBots.path = (token == legacy)
  3075. ? (BaseGlobalPath() + u"webview"_q)
  3076. : (_databasePath + u"wvbots"_q);
  3077. }
  3078. return _webviewStorageIdBots;
  3079. }
  3080. Webview::StorageId Account::resolveStorageIdOther() {
  3081. if (!_webviewStorageIdOther) {
  3082. if (_webviewStorageIdOther.token.isEmpty()) {
  3083. _webviewStorageIdOther.token = QByteArray::fromStdString(
  3084. Webview::GenerateStorageToken());
  3085. writeMapDelayed();
  3086. }
  3087. _webviewStorageIdOther.path = _databasePath + u"wvother"_q;
  3088. }
  3089. return _webviewStorageIdOther;
  3090. }
  3091. QImage Account::readRoundPlaceholder() {
  3092. if (!_roundPlaceholder.isNull()) {
  3093. return _roundPlaceholder;
  3094. } else if (!_roundPlaceholderKey) {
  3095. return QImage();
  3096. }
  3097. FileReadDescriptor placeholder;
  3098. if (!ReadEncryptedFile(
  3099. placeholder,
  3100. _roundPlaceholderKey,
  3101. _basePath,
  3102. _localKey)) {
  3103. ClearKey(_roundPlaceholderKey, _basePath);
  3104. _roundPlaceholderKey = 0;
  3105. writeMapDelayed();
  3106. return QImage();
  3107. }
  3108. auto bytes = QByteArray();
  3109. placeholder.stream >> bytes;
  3110. _roundPlaceholder = Images::Read({ .content = bytes }).image;
  3111. return _roundPlaceholder;
  3112. }
  3113. void Account::writeRoundPlaceholder(const QImage &placeholder) {
  3114. if (placeholder.isNull()) {
  3115. return;
  3116. }
  3117. _roundPlaceholder = placeholder;
  3118. auto bytes = QByteArray();
  3119. auto buffer = QBuffer(&bytes);
  3120. placeholder.save(&buffer, "JPG", 87);
  3121. quint32 size = Serialize::bytearraySize(bytes);
  3122. if (!_roundPlaceholderKey) {
  3123. _roundPlaceholderKey = GenerateKey(_basePath);
  3124. writeMapQueued();
  3125. }
  3126. EncryptedDescriptor data(size);
  3127. data.stream << bytes;
  3128. FileWriteDescriptor file(_roundPlaceholderKey, _basePath);
  3129. file.writeEncrypted(data, _localKey);
  3130. }
  3131. QByteArray Account::readInlineBotsDownloads() {
  3132. if (_inlineBotsDownloadsRead) {
  3133. return QByteArray();
  3134. }
  3135. _inlineBotsDownloadsRead = true;
  3136. if (!_inlineBotsDownloadsKey) {
  3137. return QByteArray();
  3138. }
  3139. FileReadDescriptor inlineBotsDownloads;
  3140. if (!ReadEncryptedFile(
  3141. inlineBotsDownloads,
  3142. _inlineBotsDownloadsKey,
  3143. _basePath,
  3144. _localKey)) {
  3145. ClearKey(_inlineBotsDownloadsKey, _basePath);
  3146. _inlineBotsDownloadsKey = 0;
  3147. writeMapDelayed();
  3148. return QByteArray();
  3149. }
  3150. auto bytes = QByteArray();
  3151. inlineBotsDownloads.stream >> bytes;
  3152. return bytes;
  3153. }
  3154. void Account::writeInlineBotsDownloads(const QByteArray &bytes) {
  3155. if (!_inlineBotsDownloadsKey) {
  3156. _inlineBotsDownloadsKey = GenerateKey(_basePath);
  3157. writeMapQueued();
  3158. }
  3159. quint32 size = Serialize::bytearraySize(bytes);
  3160. EncryptedDescriptor data(size);
  3161. data.stream << bytes;
  3162. FileWriteDescriptor file(_inlineBotsDownloadsKey, _basePath);
  3163. file.writeEncrypted(data, _localKey);
  3164. }
  3165. bool Account::encrypt(
  3166. const void *src,
  3167. void *dst,
  3168. uint32 len,
  3169. const void *key128) const {
  3170. if (!_localKey) {
  3171. return false;
  3172. }
  3173. MTP::aesEncryptLocal(src, dst, len, _localKey, key128);
  3174. return true;
  3175. }
  3176. bool Account::decrypt(
  3177. const void *src,
  3178. void *dst,
  3179. uint32 len,
  3180. const void *key128) const {
  3181. if (!_localKey) {
  3182. return false;
  3183. }
  3184. MTP::aesDecryptLocal(src, dst, len, _localKey, key128);
  3185. return true;
  3186. }
  3187. Webview::StorageId TonSiteStorageId() {
  3188. auto result = Webview::StorageId{
  3189. .path = BaseGlobalPath() + u"webview-tonsite"_q,
  3190. .token = Core::App().settings().tonsiteStorageToken(),
  3191. };
  3192. if (result.token.isEmpty()) {
  3193. result.token = QByteArray::fromStdString(
  3194. Webview::GenerateStorageToken());
  3195. Core::App().settings().setTonsiteStorageToken(result.token);
  3196. Core::App().saveSettingsDelayed();
  3197. }
  3198. return result;
  3199. }
  3200. } // namespace Storage