apiwrap.cpp 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800
  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 "apiwrap.h"
  8. #include "core/wallet_replacer.h"
  9. #include "api/api_authorizations.h"
  10. #include "api/api_attached_stickers.h"
  11. #include "api/api_blocked_peers.h"
  12. #include "api/api_chat_links.h"
  13. #include "api/api_chat_participants.h"
  14. #include "api/api_cloud_password.h"
  15. #include "api/api_hash.h"
  16. #include "api/api_invite_links.h"
  17. #include "api/api_media.h"
  18. #include "api/api_peer_colors.h"
  19. #include "api/api_peer_photo.h"
  20. #include "api/api_polls.h"
  21. #include "api/api_sending.h"
  22. #include "api/api_text_entities.h"
  23. #include "api/api_self_destruct.h"
  24. #include "api/api_sensitive_content.h"
  25. #include "api/api_global_privacy.h"
  26. #include "api/api_updates.h"
  27. #include "api/api_user_privacy.h"
  28. #include "api/api_views.h"
  29. #include "api/api_confirm_phone.h"
  30. #include "api/api_unread_things.h"
  31. #include "api/api_ringtones.h"
  32. #include "api/api_transcribes.h"
  33. #include "api/api_premium.h"
  34. #include "api/api_user_names.h"
  35. #include "api/api_websites.h"
  36. #include "data/business/data_shortcut_messages.h"
  37. #include "data/components/scheduled_messages.h"
  38. #include "data/notify/data_notify_settings.h"
  39. #include "data/data_changes.h"
  40. #include "data/data_web_page.h"
  41. #include "data/data_folder.h"
  42. #include "data/data_forum_topic.h"
  43. #include "data/data_forum.h"
  44. #include "data/data_saved_sublist.h"
  45. #include "data/data_search_controller.h"
  46. #include "data/data_session.h"
  47. #include "data/data_channel.h"
  48. #include "data/data_chat.h"
  49. #include "data/data_user.h"
  50. #include "data/data_chat_filters.h"
  51. #include "data/data_histories.h"
  52. #include "data/data_history_messages.h"
  53. #include "core/core_cloud_password.h"
  54. #include "core/application.h"
  55. #include "base/unixtime.h"
  56. #include "base/random.h"
  57. #include "base/call_delayed.h"
  58. #include "lang/lang_keys.h"
  59. #include "mainwidget.h"
  60. #include "boxes/add_contact_box.h"
  61. #include "mtproto/mtproto_config.h"
  62. #include "history/history.h"
  63. #include "history/history_item_components.h"
  64. #include "history/history_item_helpers.h"
  65. #include "main/main_session.h"
  66. #include "main/main_session_settings.h"
  67. #include "main/main_account.h"
  68. #include "ui/boxes/confirm_box.h"
  69. #include "boxes/sticker_set_box.h"
  70. #include "boxes/premium_limits_box.h"
  71. #include "window/notifications_manager.h"
  72. #include "window/window_controller.h"
  73. #include "window/window_lock_widgets.h"
  74. #include "window/window_session_controller.h"
  75. #include "inline_bots/inline_bot_result.h"
  76. #include "chat_helpers/message_field.h"
  77. #include "ui/item_text_options.h"
  78. #include "ui/text/text_utilities.h"
  79. #include "ui/chat/attach/attach_prepare.h"
  80. #include "ui/toast/toast.h"
  81. #include "support/support_helper.h"
  82. #include "settings/settings_premium.h"
  83. #include "storage/localimageloader.h"
  84. #include "storage/download_manager_mtproto.h"
  85. #include "storage/file_upload.h"
  86. #include "storage/storage_account.h"
  87. namespace {
  88. // Save draft to the cloud with 1 sec extra delay.
  89. constexpr auto kSaveCloudDraftTimeout = 1000;
  90. constexpr auto kTopPromotionInterval = TimeId(60 * 60);
  91. constexpr auto kTopPromotionMinDelay = TimeId(10);
  92. constexpr auto kSmallDelayMs = 5;
  93. constexpr auto kReadFeaturedSetsTimeout = crl::time(1000);
  94. constexpr auto kFileLoaderQueueStopTimeout = crl::time(5000);
  95. constexpr auto kStickersByEmojiInvalidateTimeout = crl::time(6 * 1000);
  96. constexpr auto kNotifySettingSaveTimeout = crl::time(1000);
  97. constexpr auto kDialogsFirstLoad = 20;
  98. constexpr auto kDialogsPerPage = 500;
  99. constexpr auto kStatsSessionKillTimeout = 10 * crl::time(1000);
  100. using PhotoFileLocationId = Data::PhotoFileLocationId;
  101. using DocumentFileLocationId = Data::DocumentFileLocationId;
  102. using UpdatedFileReferences = Data::UpdatedFileReferences;
  103. [[nodiscard]] TimeId UnixtimeFromMsgId(mtpMsgId msgId) {
  104. return TimeId(msgId >> 32);
  105. }
  106. [[nodiscard]] std::shared_ptr<ChatHelpers::Show> ShowForPeer(
  107. not_null<PeerData*> peer) {
  108. if (const auto window = Core::App().windowFor(peer)) {
  109. if (const auto controller = window->sessionController()) {
  110. if (&controller->session() == &peer->session()) {
  111. return controller->uiShow();
  112. }
  113. }
  114. }
  115. return nullptr;
  116. }
  117. void ShowChannelsLimitBox(not_null<PeerData*> peer) {
  118. if (const auto window = Core::App().windowFor(peer)) {
  119. window->invokeForSessionController(
  120. &peer->session().account(),
  121. peer,
  122. [&](not_null<Window::SessionController*> controller) {
  123. controller->show(Box(ChannelsLimitBox, &peer->session()));
  124. });
  125. }
  126. }
  127. [[nodiscard]] FileLoadTo FileLoadTaskOptions(const Api::SendAction &action) {
  128. const auto peer = action.history->peer;
  129. return FileLoadTo(
  130. peer->id,
  131. action.options,
  132. action.replyTo,
  133. action.replaceMediaOf);
  134. }
  135. [[nodiscard]] QString FormatVideoTimestamp(TimeId seconds) {
  136. const auto minutes = seconds / 60;
  137. const auto hours = minutes / 60;
  138. return hours
  139. ? u"%1h%2m%3s"_q.arg(hours).arg(minutes % 60).arg(seconds % 60)
  140. : minutes
  141. ? u"%1m%2s"_q.arg(minutes).arg(seconds % 60)
  142. : QString::number(seconds);
  143. }
  144. } // namespace
  145. ApiWrap::ApiWrap(not_null<Main::Session*> session)
  146. : MTP::Sender(&session->account().mtp())
  147. , _session(session)
  148. , _messageDataResolveDelayed([=] { resolveMessageDatas(); })
  149. , _webPagesTimer([=] { resolveWebPages(); })
  150. , _draftsSaveTimer([=] { saveDraftsToCloud(); })
  151. , _featuredSetsReadTimer([=] { readFeaturedSets(); })
  152. , _dialogsLoadState(std::make_unique<DialogsLoadState>())
  153. , _fileLoader(std::make_unique<TaskQueue>(kFileLoaderQueueStopTimeout))
  154. , _topPromotionTimer([=] { refreshTopPromotion(); })
  155. , _updateNotifyTimer([=] { sendNotifySettingsUpdates(); })
  156. , _statsSessionKillTimer([=] { checkStatsSessions(); })
  157. , _authorizations(std::make_unique<Api::Authorizations>(this))
  158. , _attachedStickers(std::make_unique<Api::AttachedStickers>(this))
  159. , _blockedPeers(std::make_unique<Api::BlockedPeers>(this))
  160. , _cloudPassword(std::make_unique<Api::CloudPassword>(this))
  161. , _selfDestruct(std::make_unique<Api::SelfDestruct>(this))
  162. , _sensitiveContent(std::make_unique<Api::SensitiveContent>(this))
  163. , _globalPrivacy(std::make_unique<Api::GlobalPrivacy>(this))
  164. , _userPrivacy(std::make_unique<Api::UserPrivacy>(this))
  165. , _inviteLinks(std::make_unique<Api::InviteLinks>(this))
  166. , _chatLinks(std::make_unique<Api::ChatLinks>(this))
  167. , _views(std::make_unique<Api::ViewsManager>(this))
  168. , _confirmPhone(std::make_unique<Api::ConfirmPhone>(this))
  169. , _peerPhoto(std::make_unique<Api::PeerPhoto>(this))
  170. , _polls(std::make_unique<Api::Polls>(this))
  171. , _chatParticipants(std::make_unique<Api::ChatParticipants>(this))
  172. , _unreadThings(std::make_unique<Api::UnreadThings>(this))
  173. , _ringtones(std::make_unique<Api::Ringtones>(this))
  174. , _transcribes(std::make_unique<Api::Transcribes>(this))
  175. , _premium(std::make_unique<Api::Premium>(this))
  176. , _usernames(std::make_unique<Api::Usernames>(this))
  177. , _websites(std::make_unique<Api::Websites>(this))
  178. , _peerColors(std::make_unique<Api::PeerColors>(this)) {
  179. crl::on_main(session, [=] {
  180. // You can't use _session->lifetime() in the constructor,
  181. // only queued, because it is not constructed yet.
  182. _session->data().chatsFilters().changed(
  183. ) | rpl::filter([=] {
  184. return _session->data().chatsFilters().archiveNeeded();
  185. }) | rpl::start_with_next([=] {
  186. requestMoreDialogsIfNeeded();
  187. }, _session->lifetime());
  188. setupSupportMode();
  189. Core::App().settings().proxy().connectionTypeValue(
  190. ) | rpl::start_with_next([=] {
  191. refreshTopPromotion();
  192. }, _session->lifetime());
  193. });
  194. }
  195. ApiWrap::~ApiWrap() = default;
  196. Main::Session &ApiWrap::session() const {
  197. return *_session;
  198. }
  199. Storage::Account &ApiWrap::local() const {
  200. return _session->local();
  201. }
  202. Api::Updates &ApiWrap::updates() const {
  203. return _session->updates();
  204. }
  205. void ApiWrap::setupSupportMode() {
  206. if (!_session->supportMode()) {
  207. return;
  208. }
  209. _session->settings().supportChatsTimeSliceValue(
  210. ) | rpl::start_with_next([=](int seconds) {
  211. _dialogsLoadTill = seconds ? std::max(base::unixtime::now() - seconds, 0) : 0;
  212. refreshDialogsLoadBlocked();
  213. }, _session->lifetime());
  214. }
  215. void ApiWrap::requestChangelog(
  216. const QString &sinceVersion,
  217. Fn<void(const MTPUpdates &result)> callback) {
  218. //request(MTPhelp_GetAppChangelog(
  219. // MTP_string(sinceVersion)
  220. //)).done(
  221. // callback
  222. //).send();
  223. }
  224. void ApiWrap::refreshTopPromotion() {
  225. const auto now = base::unixtime::now();
  226. const auto next = (_topPromotionNextRequestTime != 0)
  227. ? _topPromotionNextRequestTime
  228. : now;
  229. if (_topPromotionRequestId) {
  230. getTopPromotionDelayed(now, next);
  231. return;
  232. }
  233. const auto key = [&]() -> std::pair<QString, uint32> {
  234. if (!Core::App().settings().proxy().isEnabled()) {
  235. return {};
  236. }
  237. const auto &proxy = Core::App().settings().proxy().selected();
  238. if (proxy.type != MTP::ProxyData::Type::Mtproto) {
  239. return {};
  240. }
  241. return { proxy.host, proxy.port };
  242. }();
  243. if (_topPromotionKey == key && now < next) {
  244. getTopPromotionDelayed(now, next);
  245. return;
  246. }
  247. _topPromotionKey = key;
  248. _topPromotionRequestId = request(MTPhelp_GetPromoData(
  249. )).done([=](const MTPhelp_PromoData &result) {
  250. _topPromotionRequestId = 0;
  251. topPromotionDone(result);
  252. }).fail([=] {
  253. _topPromotionRequestId = 0;
  254. const auto now = base::unixtime::now();
  255. const auto next = _topPromotionNextRequestTime = now
  256. + kTopPromotionInterval;
  257. if (!_topPromotionTimer.isActive()) {
  258. getTopPromotionDelayed(now, next);
  259. }
  260. }).send();
  261. }
  262. void ApiWrap::getTopPromotionDelayed(TimeId now, TimeId next) {
  263. _topPromotionTimer.callOnce(std::min(
  264. std::max(next - now, kTopPromotionMinDelay),
  265. kTopPromotionInterval) * crl::time(1000));
  266. };
  267. void ApiWrap::topPromotionDone(const MTPhelp_PromoData &proxy) {
  268. _topPromotionNextRequestTime = proxy.match([&](const auto &data) {
  269. return data.vexpires().v;
  270. });
  271. getTopPromotionDelayed(
  272. base::unixtime::now(),
  273. _topPromotionNextRequestTime);
  274. proxy.match([&](const MTPDhelp_promoDataEmpty &data) {
  275. _session->data().setTopPromoted(nullptr, QString(), QString());
  276. }, [&](const MTPDhelp_promoData &data) {
  277. _session->data().processChats(data.vchats());
  278. _session->data().processUsers(data.vusers());
  279. const auto peerId = peerFromMTP(data.vpeer());
  280. const auto history = _session->data().history(peerId);
  281. _session->data().setTopPromoted(
  282. history,
  283. data.vpsa_type().value_or_empty(),
  284. data.vpsa_message().value_or_empty());
  285. });
  286. }
  287. void ApiWrap::requestDeepLinkInfo(
  288. const QString &path,
  289. Fn<void(TextWithEntities message, bool updateRequired)> callback) {
  290. request(_deepLinkInfoRequestId).cancel();
  291. _deepLinkInfoRequestId = request(MTPhelp_GetDeepLinkInfo(
  292. MTP_string(path)
  293. )).done([=](const MTPhelp_DeepLinkInfo &result) {
  294. _deepLinkInfoRequestId = 0;
  295. if (result.type() == mtpc_help_deepLinkInfo) {
  296. const auto &data = result.c_help_deepLinkInfo();
  297. callback(TextWithEntities{
  298. qs(data.vmessage()),
  299. Api::EntitiesFromMTP(
  300. _session,
  301. data.ventities().value_or_empty())
  302. }, data.is_update_app());
  303. }
  304. }).fail([=] {
  305. _deepLinkInfoRequestId = 0;
  306. }).send();
  307. }
  308. void ApiWrap::requestTermsUpdate() {
  309. if (_termsUpdateRequestId) {
  310. return;
  311. }
  312. const auto now = crl::now();
  313. if (_termsUpdateSendAt && now < _termsUpdateSendAt) {
  314. base::call_delayed(_termsUpdateSendAt - now, _session, [=] {
  315. requestTermsUpdate();
  316. });
  317. return;
  318. }
  319. constexpr auto kTermsUpdateTimeoutMin = 10 * crl::time(1000);
  320. constexpr auto kTermsUpdateTimeoutMax = 86400 * crl::time(1000);
  321. _termsUpdateRequestId = request(MTPhelp_GetTermsOfServiceUpdate(
  322. )).done([=](const MTPhelp_TermsOfServiceUpdate &result) {
  323. _termsUpdateRequestId = 0;
  324. const auto requestNext = [&](auto &&data) {
  325. const auto timeout = (data.vexpires().v - base::unixtime::now());
  326. _termsUpdateSendAt = crl::now() + std::clamp(
  327. timeout * crl::time(1000),
  328. kTermsUpdateTimeoutMin,
  329. kTermsUpdateTimeoutMax);
  330. requestTermsUpdate();
  331. };
  332. switch (result.type()) {
  333. case mtpc_help_termsOfServiceUpdateEmpty: {
  334. const auto &data = result.c_help_termsOfServiceUpdateEmpty();
  335. requestNext(data);
  336. } break;
  337. case mtpc_help_termsOfServiceUpdate: {
  338. const auto &data = result.c_help_termsOfServiceUpdate();
  339. const auto &terms = data.vterms_of_service();
  340. const auto &fields = terms.c_help_termsOfService();
  341. session().lockByTerms(
  342. Window::TermsLock::FromMTP(_session, fields));
  343. requestNext(data);
  344. } break;
  345. default: Unexpected("Type in requestTermsUpdate().");
  346. }
  347. }).fail([=] {
  348. _termsUpdateRequestId = 0;
  349. _termsUpdateSendAt = crl::now() + kTermsUpdateTimeoutMin;
  350. requestTermsUpdate();
  351. }).send();
  352. }
  353. void ApiWrap::acceptTerms(bytes::const_span id) {
  354. request(MTPhelp_AcceptTermsOfService(
  355. MTP_dataJSON(MTP_bytes(id))
  356. )).done([=] {
  357. requestTermsUpdate();
  358. }).send();
  359. }
  360. void ApiWrap::checkChatInvite(
  361. const QString &hash,
  362. FnMut<void(const MTPChatInvite &)> done,
  363. Fn<void(const MTP::Error &)> fail) {
  364. request(base::take(_checkInviteRequestId)).cancel();
  365. _checkInviteRequestId = request(MTPmessages_CheckChatInvite(
  366. MTP_string(hash)
  367. )).done(std::move(done)).fail(std::move(fail)).send();
  368. }
  369. void ApiWrap::checkFilterInvite(
  370. const QString &slug,
  371. FnMut<void(const MTPchatlists_ChatlistInvite &)> done,
  372. Fn<void(const MTP::Error &)> fail) {
  373. request(base::take(_checkFilterInviteRequestId)).cancel();
  374. _checkFilterInviteRequestId = request(
  375. MTPchatlists_CheckChatlistInvite(MTP_string(slug))
  376. ).done(std::move(done)).fail(std::move(fail)).send();
  377. }
  378. void ApiWrap::savePinnedOrder(Data::Folder *folder) {
  379. const auto &order = _session->data().pinnedChatsOrder(folder);
  380. const auto input = [](Dialogs::Key key) {
  381. if (const auto history = key.history()) {
  382. return MTP_inputDialogPeer(history->peer->input);
  383. } else if (const auto folder = key.folder()) {
  384. return MTP_inputDialogPeerFolder(MTP_int(folder->id()));
  385. }
  386. Unexpected("Key type in pinnedDialogsOrder().");
  387. };
  388. auto peers = QVector<MTPInputDialogPeer>();
  389. peers.reserve(order.size());
  390. ranges::transform(
  391. order,
  392. ranges::back_inserter(peers),
  393. input);
  394. request(MTPmessages_ReorderPinnedDialogs(
  395. MTP_flags(MTPmessages_ReorderPinnedDialogs::Flag::f_force),
  396. MTP_int(folder ? folder->id() : 0),
  397. MTP_vector(peers)
  398. )).send();
  399. }
  400. void ApiWrap::savePinnedOrder(not_null<Data::Forum*> forum) {
  401. const auto &order = _session->data().pinnedChatsOrder(forum);
  402. const auto input = [](Dialogs::Key key) {
  403. if (const auto topic = key.topic()) {
  404. return MTP_int(topic->rootId().bare);
  405. }
  406. Unexpected("Key type in pinnedDialogsOrder().");
  407. };
  408. auto topics = QVector<MTPint>();
  409. topics.reserve(order.size());
  410. ranges::transform(
  411. order,
  412. ranges::back_inserter(topics),
  413. input);
  414. request(MTPchannels_ReorderPinnedForumTopics(
  415. MTP_flags(MTPchannels_ReorderPinnedForumTopics::Flag::f_force),
  416. forum->channel()->inputChannel,
  417. MTP_vector(topics)
  418. )).done([=](const MTPUpdates &result) {
  419. applyUpdates(result);
  420. }).send();
  421. }
  422. void ApiWrap::savePinnedOrder(not_null<Data::SavedMessages*> saved) {
  423. const auto &order = _session->data().pinnedChatsOrder(saved);
  424. const auto input = [](Dialogs::Key key) {
  425. if (const auto sublist = key.sublist()) {
  426. return MTP_inputDialogPeer(sublist->peer()->input);
  427. }
  428. Unexpected("Key type in pinnedDialogsOrder().");
  429. };
  430. auto peers = QVector<MTPInputDialogPeer>();
  431. peers.reserve(order.size());
  432. ranges::transform(
  433. order,
  434. ranges::back_inserter(peers),
  435. input);
  436. request(MTPmessages_ReorderPinnedSavedDialogs(
  437. MTP_flags(MTPmessages_ReorderPinnedSavedDialogs::Flag::f_force),
  438. MTP_vector(peers)
  439. )).send();
  440. }
  441. void ApiWrap::toggleHistoryArchived(
  442. not_null<History*> history,
  443. bool archived,
  444. Fn<void()> callback) {
  445. if (const auto already = _historyArchivedRequests.take(history)) {
  446. request(already->first).cancel();
  447. }
  448. const auto isPinned = history->isPinnedDialog(0);
  449. const auto archiveId = Data::Folder::kId;
  450. const auto requestId = request(MTPfolders_EditPeerFolders(
  451. MTP_vector<MTPInputFolderPeer>(
  452. 1,
  453. MTP_inputFolderPeer(
  454. history->peer->input,
  455. MTP_int(archived ? archiveId : 0)))
  456. )).done([=](const MTPUpdates &result) {
  457. applyUpdates(result);
  458. if (archived) {
  459. history->setFolder(_session->data().folder(archiveId));
  460. } else {
  461. history->clearFolder();
  462. }
  463. if (const auto data = _historyArchivedRequests.take(history)) {
  464. data->second();
  465. }
  466. if (isPinned) {
  467. _session->data().notifyPinnedDialogsOrderUpdated();
  468. }
  469. }).fail([=] {
  470. _historyArchivedRequests.remove(history);
  471. }).send();
  472. _historyArchivedRequests.emplace(history, requestId, callback);
  473. }
  474. void ApiWrap::sendMessageFail(
  475. const MTP::Error &error,
  476. not_null<PeerData*> peer,
  477. uint64 randomId,
  478. FullMsgId itemId) {
  479. sendMessageFail(error.type(), peer, randomId, itemId);
  480. }
  481. void ApiWrap::sendMessageFail(
  482. const QString &error,
  483. not_null<PeerData*> peer,
  484. uint64 randomId,
  485. FullMsgId itemId) {
  486. const auto show = ShowForPeer(peer);
  487. const auto paidStarsPrefix = u"ALLOW_PAYMENT_REQUIRED_"_q;
  488. if (show && error == u"PEER_FLOOD"_q) {
  489. show->showBox(
  490. Ui::MakeInformBox(
  491. PeerFloodErrorText(&session(), PeerFloodType::Send)),
  492. Ui::LayerOption::CloseOther);
  493. } else if (show && error == u"USER_BANNED_IN_CHANNEL"_q) {
  494. const auto link = Ui::Text::Link(
  495. tr::lng_cant_more_info(tr::now),
  496. session().createInternalLinkFull(u"spambot"_q));
  497. show->showBox(
  498. Ui::MakeInformBox(
  499. tr::lng_error_public_groups_denied(
  500. tr::now,
  501. lt_more_info,
  502. link,
  503. Ui::Text::WithEntities)),
  504. Ui::LayerOption::CloseOther);
  505. } else if (error.startsWith(u"SLOWMODE_WAIT_"_q)) {
  506. const auto chop = u"SLOWMODE_WAIT_"_q.size();
  507. const auto left = base::StringViewMid(error, chop).toInt();
  508. if (const auto channel = peer->asChannel()) {
  509. const auto seconds = channel->slowmodeSeconds();
  510. if (seconds >= left) {
  511. channel->growSlowmodeLastMessage(
  512. base::unixtime::now() - (left - seconds));
  513. } else {
  514. requestFullPeer(peer);
  515. }
  516. }
  517. } else if (error == u"SCHEDULE_STATUS_PRIVATE"_q) {
  518. auto &scheduled = _session->scheduledMessages();
  519. Assert(peer->isUser());
  520. if (const auto item = scheduled.lookupItem(peer->id, itemId.msg)) {
  521. scheduled.removeSending(item);
  522. if (show) {
  523. show->showBox(
  524. Ui::MakeInformBox(tr::lng_cant_do_this()),
  525. Ui::LayerOption::CloseOther);
  526. }
  527. }
  528. } else if (show && error == u"CHAT_FORWARDS_RESTRICTED"_q) {
  529. show->showToast(peer->isBroadcast()
  530. ? tr::lng_error_noforwards_channel(tr::now)
  531. : tr::lng_error_noforwards_group(tr::now), kJoinErrorDuration);
  532. } else if (error == u"PREMIUM_ACCOUNT_REQUIRED"_q) {
  533. Settings::ShowPremium(&session(), "premium_stickers");
  534. } else if (error == u"SCHEDULE_TOO_MUCH"_q) {
  535. auto &scheduled = _session->scheduledMessages();
  536. if (const auto item = scheduled.lookupItem(peer->id, itemId.msg)) {
  537. scheduled.removeSending(item);
  538. }
  539. if (show) {
  540. show->showToast(tr::lng_error_schedule_limit(tr::now));
  541. }
  542. } else if (error.startsWith(paidStarsPrefix)) {
  543. if (show) {
  544. show->showToast(
  545. u"Payment requirements changed. Please, try again."_q);
  546. }
  547. if (const auto stars = error.mid(paidStarsPrefix.size()).toInt()) {
  548. if (const auto user = peer->asUser()) {
  549. user->setStarsPerMessage(stars);
  550. } else if (const auto channel = peer->asChannel()) {
  551. channel->setStarsPerMessage(stars);
  552. }
  553. }
  554. peer->updateFull();
  555. }
  556. if (const auto item = _session->data().message(itemId)) {
  557. Assert(randomId != 0);
  558. _session->data().unregisterMessageRandomId(randomId);
  559. item->sendFailed();
  560. if (error == u"TOPIC_CLOSED"_q) {
  561. if (const auto topic = item->topic()) {
  562. topic->setClosed(true);
  563. }
  564. }
  565. }
  566. }
  567. void ApiWrap::requestMessageData(
  568. PeerData *peer,
  569. MsgId msgId,
  570. Fn<void()> done) {
  571. auto &requests = (peer && peer->isChannel())
  572. ? _channelMessageDataRequests[peer->asChannel()][msgId]
  573. : _messageDataRequests[msgId];
  574. if (done) {
  575. requests.callbacks.push_back(std::move(done));
  576. }
  577. if (!requests.requestId) {
  578. _messageDataResolveDelayed.call();
  579. }
  580. }
  581. QVector<MTPInputMessage> ApiWrap::collectMessageIds(
  582. const MessageDataRequests &requests) {
  583. auto result = QVector<MTPInputMessage>();
  584. result.reserve(requests.size());
  585. for (const auto &[msgId, request] : requests) {
  586. if (request.requestId > 0) {
  587. continue;
  588. }
  589. result.push_back(MTP_inputMessageID(MTP_int(msgId)));
  590. }
  591. return result;
  592. }
  593. auto ApiWrap::messageDataRequests(ChannelData *channel, bool onlyExisting)
  594. -> MessageDataRequests* {
  595. if (!channel) {
  596. return &_messageDataRequests;
  597. }
  598. const auto i = _channelMessageDataRequests.find(channel);
  599. if (i != end(_channelMessageDataRequests)) {
  600. return &i->second;
  601. } else if (onlyExisting) {
  602. return nullptr;
  603. }
  604. return &_channelMessageDataRequests.emplace(
  605. channel,
  606. MessageDataRequests()
  607. ).first->second;
  608. }
  609. void ApiWrap::resolveMessageDatas() {
  610. if (_messageDataRequests.empty() && _channelMessageDataRequests.empty()) {
  611. return;
  612. }
  613. const auto ids = collectMessageIds(_messageDataRequests);
  614. if (!ids.isEmpty()) {
  615. const auto requestId = request(MTPmessages_GetMessages(
  616. MTP_vector<MTPInputMessage>(ids)
  617. )).done([=](
  618. const MTPmessages_Messages &result,
  619. mtpRequestId requestId) {
  620. _session->data().processExistingMessages(nullptr, result);
  621. finalizeMessageDataRequest(nullptr, requestId);
  622. }).fail([=](const MTP::Error &error, mtpRequestId requestId) {
  623. finalizeMessageDataRequest(nullptr, requestId);
  624. }).afterDelay(kSmallDelayMs).send();
  625. for (auto &[msgId, request] : _messageDataRequests) {
  626. if (request.requestId > 0) {
  627. continue;
  628. }
  629. request.requestId = requestId;
  630. }
  631. }
  632. for (auto j = _channelMessageDataRequests.begin(); j != _channelMessageDataRequests.cend();) {
  633. if (j->second.empty()) {
  634. j = _channelMessageDataRequests.erase(j);
  635. continue;
  636. }
  637. const auto ids = collectMessageIds(j->second);
  638. if (!ids.isEmpty()) {
  639. const auto channel = j->first;
  640. const auto requestId = request(MTPchannels_GetMessages(
  641. channel->inputChannel,
  642. MTP_vector<MTPInputMessage>(ids)
  643. )).done([=](
  644. const MTPmessages_Messages &result,
  645. mtpRequestId requestId) {
  646. _session->data().processExistingMessages(channel, result);
  647. finalizeMessageDataRequest(channel, requestId);
  648. }).fail([=](const MTP::Error &error, mtpRequestId requestId) {
  649. finalizeMessageDataRequest(channel, requestId);
  650. }).afterDelay(kSmallDelayMs).send();
  651. for (auto &[msgId, request] : j->second) {
  652. if (request.requestId > 0) {
  653. continue;
  654. }
  655. request.requestId = requestId;
  656. }
  657. }
  658. ++j;
  659. }
  660. }
  661. void ApiWrap::finalizeMessageDataRequest(
  662. ChannelData *channel,
  663. mtpRequestId requestId) {
  664. auto requests = messageDataRequests(channel, true);
  665. if (!requests) {
  666. return;
  667. }
  668. auto callbacks = std::vector<Fn<void()>>();
  669. for (auto i = requests->begin(); i != requests->cend();) {
  670. if (i->second.requestId == requestId) {
  671. auto &list = i->second.callbacks;
  672. if (callbacks.empty()) {
  673. callbacks = std::move(list);
  674. } else {
  675. callbacks.insert(
  676. end(callbacks),
  677. std::make_move_iterator(begin(list)),
  678. std::make_move_iterator(end(list)));
  679. }
  680. i = requests->erase(i);
  681. } else {
  682. ++i;
  683. }
  684. }
  685. if (channel && requests->empty()) {
  686. _channelMessageDataRequests.remove(channel);
  687. }
  688. for (const auto &callback : callbacks) {
  689. callback();
  690. }
  691. }
  692. QString ApiWrap::exportDirectMessageLink(
  693. not_null<HistoryItem*> item,
  694. bool inRepliesContext,
  695. bool forceNonPublicLink,
  696. std::optional<TimeId> videoTimestamp) {
  697. Expects(item->history()->peer->isChannel());
  698. const auto itemId = item->fullId();
  699. const auto channel = item->history()->peer->asChannel();
  700. const auto fallback = [&] {
  701. auto linkChannel = channel;
  702. auto linkItemId = item->id;
  703. auto linkCommentId = MsgId();
  704. auto linkThreadId = MsgId();
  705. auto linkThreadIsTopic = false;
  706. if (inRepliesContext) {
  707. linkThreadIsTopic = item->history()->isForum();
  708. const auto rootId = linkThreadIsTopic
  709. ? item->topicRootId()
  710. : item->replyToTop();
  711. if (rootId) {
  712. const auto root = item->history()->owner().message(
  713. channel->id,
  714. rootId);
  715. const auto sender = root
  716. ? root->discussionPostOriginalSender()
  717. : nullptr;
  718. if (sender && sender->hasUsername() && !forceNonPublicLink) {
  719. // Comment to a public channel.
  720. const auto forwarded = root->Get<HistoryMessageForwarded>();
  721. linkItemId = forwarded->savedFromMsgId;
  722. if (linkItemId) {
  723. linkChannel = sender;
  724. linkCommentId = item->id;
  725. } else {
  726. linkItemId = item->id;
  727. }
  728. } else {
  729. // Reply in a thread, maybe comment in a private channel.
  730. linkThreadId = rootId;
  731. }
  732. }
  733. }
  734. const auto base = (linkChannel->hasUsername() && !forceNonPublicLink)
  735. ? linkChannel->username()
  736. : "c/" + QString::number(peerToChannel(linkChannel->id).bare);
  737. const auto post = QString::number(linkItemId.bare);
  738. const auto query = base
  739. + '/'
  740. + (linkCommentId
  741. ? (post + "?comment=" + QString::number(linkCommentId.bare))
  742. : (linkThreadId && !linkThreadIsTopic)
  743. ? (post + "?thread=" + QString::number(linkThreadId.bare))
  744. : linkThreadId
  745. ? (QString::number(linkThreadId.bare) + '/' + post)
  746. : post);
  747. return session().createInternalLinkFull(query);
  748. };
  749. if (forceNonPublicLink) {
  750. return fallback();
  751. }
  752. const auto i = _unlikelyMessageLinks.find(itemId);
  753. const auto current = (i != end(_unlikelyMessageLinks))
  754. ? i->second
  755. : fallback();
  756. request(MTPchannels_ExportMessageLink(
  757. MTP_flags(inRepliesContext
  758. ? MTPchannels_ExportMessageLink::Flag::f_thread
  759. : MTPchannels_ExportMessageLink::Flag(0)),
  760. channel->inputChannel,
  761. MTP_int(item->id)
  762. )).done([=](const MTPExportedMessageLink &result) {
  763. const auto link = qs(result.data().vlink());
  764. if (current != link) {
  765. _unlikelyMessageLinks.emplace_or_assign(itemId, link);
  766. }
  767. }).send();
  768. const auto addTimestamp = channel->hasUsername()
  769. && !inRepliesContext
  770. && videoTimestamp.has_value();
  771. const auto addedSeparator = (current.indexOf('?') >= 0) ? '&' : '?';
  772. const auto addedTimestamp = addTimestamp
  773. ? (addedSeparator + u"t="_q + FormatVideoTimestamp(*videoTimestamp))
  774. : QString();
  775. return current + addedTimestamp;
  776. }
  777. QString ApiWrap::exportDirectStoryLink(not_null<Data::Story*> story) {
  778. const auto storyId = story->fullId();
  779. const auto peer = story->peer();
  780. const auto fallback = [&] {
  781. const auto base = peer->username();
  782. const auto story = QString::number(storyId.story);
  783. const auto query = base + "/s/" + story;
  784. return session().createInternalLinkFull(query);
  785. };
  786. const auto i = _unlikelyStoryLinks.find(storyId);
  787. const auto current = (i != end(_unlikelyStoryLinks))
  788. ? i->second
  789. : fallback();
  790. request(MTPstories_ExportStoryLink(
  791. peer->input,
  792. MTP_int(story->id())
  793. )).done([=](const MTPExportedStoryLink &result) {
  794. const auto link = qs(result.data().vlink());
  795. if (current != link) {
  796. _unlikelyStoryLinks.emplace_or_assign(storyId, link);
  797. }
  798. }).send();
  799. return current;
  800. }
  801. void ApiWrap::requestContacts() {
  802. if (_session->data().contactsLoaded().current() || _contactsRequestId) {
  803. return;
  804. }
  805. _contactsRequestId = request(MTPcontacts_GetContacts(
  806. MTP_long(0) // hash
  807. )).done([=](const MTPcontacts_Contacts &result) {
  808. _contactsRequestId = 0;
  809. if (result.type() == mtpc_contacts_contactsNotModified) {
  810. return;
  811. }
  812. Assert(result.type() == mtpc_contacts_contacts);
  813. const auto &d = result.c_contacts_contacts();
  814. _session->data().processUsers(d.vusers());
  815. for (const auto &contact : d.vcontacts().v) {
  816. if (contact.type() != mtpc_contact) continue;
  817. const auto userId = UserId(contact.c_contact().vuser_id());
  818. if (userId == _session->userId()) {
  819. _session->user()->setIsContact(true);
  820. }
  821. }
  822. _session->data().contactsLoaded() = true;
  823. }).fail([=] {
  824. _contactsRequestId = 0;
  825. }).send();
  826. }
  827. void ApiWrap::requestDialogs(Data::Folder *folder) {
  828. if (folder && !_foldersLoadState.contains(folder)) {
  829. _foldersLoadState.emplace(folder, DialogsLoadState());
  830. }
  831. requestMoreDialogs(folder);
  832. }
  833. void ApiWrap::requestMoreDialogs(Data::Folder *folder) {
  834. const auto state = dialogsLoadState(folder);
  835. if (!state) {
  836. return;
  837. } else if (state->requestId) {
  838. return;
  839. } else if (_dialogsLoadBlockedByDate.current()) {
  840. return;
  841. }
  842. const auto firstLoad = !state->offsetDate;
  843. const auto loadCount = firstLoad ? kDialogsFirstLoad : kDialogsPerPage;
  844. const auto flags = MTPmessages_GetDialogs::Flag::f_exclude_pinned
  845. | MTPmessages_GetDialogs::Flag::f_folder_id;
  846. const auto hash = uint64(0);
  847. state->requestId = request(MTPmessages_GetDialogs(
  848. MTP_flags(flags),
  849. MTP_int(folder ? folder->id() : 0),
  850. MTP_int(state->offsetDate),
  851. MTP_int(state->offsetId),
  852. (state->offsetPeer
  853. ? state->offsetPeer->input
  854. : MTP_inputPeerEmpty()),
  855. MTP_int(loadCount),
  856. MTP_long(hash)
  857. )).done([=](const MTPmessages_Dialogs &result) {
  858. const auto state = dialogsLoadState(folder);
  859. const auto count = result.match([](
  860. const MTPDmessages_dialogsNotModified &) {
  861. LOG(("API Error: not-modified received for requested dialogs."));
  862. return 0;
  863. }, [&](const MTPDmessages_dialogs &data) {
  864. if (state) {
  865. state->listReceived = true;
  866. dialogsLoadFinish(folder); // may kill 'state'.
  867. }
  868. return int(data.vdialogs().v.size());
  869. }, [&](const MTPDmessages_dialogsSlice &data) {
  870. updateDialogsOffset(
  871. folder,
  872. data.vdialogs().v,
  873. data.vmessages().v);
  874. return data.vcount().v;
  875. });
  876. result.match([](const MTPDmessages_dialogsNotModified & data) {
  877. LOG(("API Error: not-modified received for requested dialogs."));
  878. }, [&](const auto &data) {
  879. _session->data().processUsers(data.vusers());
  880. _session->data().processChats(data.vchats());
  881. _session->data().applyDialogs(
  882. folder,
  883. data.vmessages().v,
  884. data.vdialogs().v,
  885. count);
  886. });
  887. if (!folder
  888. && (!_dialogsLoadState || !_dialogsLoadState->listReceived)) {
  889. refreshDialogsLoadBlocked();
  890. }
  891. requestMoreDialogsIfNeeded();
  892. _session->data().chatsListChanged(folder);
  893. }).fail([=] {
  894. dialogsLoadState(folder)->requestId = 0;
  895. }).send();
  896. if (!state->pinnedReceived) {
  897. requestPinnedDialogs(folder);
  898. }
  899. if (!folder) {
  900. refreshDialogsLoadBlocked();
  901. }
  902. }
  903. void ApiWrap::refreshDialogsLoadBlocked() {
  904. _dialogsLoadMayBlockByDate = _dialogsLoadState
  905. && !_dialogsLoadState->listReceived
  906. && (_dialogsLoadTill > 0);
  907. _dialogsLoadBlockedByDate = _dialogsLoadState
  908. && !_dialogsLoadState->listReceived
  909. && !_dialogsLoadState->requestId
  910. && (_dialogsLoadTill > 0)
  911. && (_dialogsLoadState->offsetDate > 0)
  912. && (_dialogsLoadState->offsetDate <= _dialogsLoadTill);
  913. }
  914. void ApiWrap::requestMoreDialogsIfNeeded() {
  915. const auto dialogsReady = !_dialogsLoadState
  916. || _dialogsLoadState->listReceived;
  917. if (_session->data().chatsFilters().loadNextExceptions(dialogsReady)) {
  918. return;
  919. } else if (_dialogsLoadState && !_dialogsLoadState->listReceived) {
  920. if (_dialogsLoadState->requestId) {
  921. return;
  922. }
  923. requestDialogs(nullptr);
  924. } else if (const auto folder = _session->data().folderLoaded(
  925. Data::Folder::kId)) {
  926. if (_session->data().chatsFilters().archiveNeeded()) {
  927. requestMoreDialogs(folder);
  928. }
  929. }
  930. requestContacts();
  931. _session->data().shortcutMessages().preloadShortcuts();
  932. }
  933. void ApiWrap::updateDialogsOffset(
  934. Data::Folder *folder,
  935. const QVector<MTPDialog> &dialogs,
  936. const QVector<MTPMessage> &messages) {
  937. auto lastDate = TimeId(0);
  938. auto lastPeer = PeerId(0);
  939. auto lastMsgId = MsgId(0);
  940. for (const auto &dialog : ranges::views::reverse(dialogs)) {
  941. dialog.match([&](const auto &dialog) {
  942. const auto peer = peerFromMTP(dialog.vpeer());
  943. const auto messageId = dialog.vtop_message().v;
  944. if (!peer || !messageId) {
  945. return;
  946. }
  947. if (!lastPeer) {
  948. lastPeer = peer;
  949. }
  950. if (!lastMsgId) {
  951. lastMsgId = messageId;
  952. }
  953. for (const auto &message : ranges::views::reverse(messages)) {
  954. if (IdFromMessage(message) == messageId
  955. && PeerFromMessage(message) == peer) {
  956. if (const auto date = DateFromMessage(message)) {
  957. lastDate = date;
  958. }
  959. return;
  960. }
  961. }
  962. });
  963. if (lastDate) {
  964. break;
  965. }
  966. }
  967. if (const auto state = dialogsLoadState(folder)) {
  968. if (lastDate) {
  969. state->offsetDate = lastDate;
  970. state->offsetId = lastMsgId;
  971. state->offsetPeer = _session->data().peer(lastPeer);
  972. state->requestId = 0;
  973. } else {
  974. state->listReceived = true;
  975. dialogsLoadFinish(folder);
  976. }
  977. }
  978. }
  979. auto ApiWrap::dialogsLoadState(Data::Folder *folder) -> DialogsLoadState* {
  980. if (!folder) {
  981. return _dialogsLoadState.get();
  982. }
  983. const auto i = _foldersLoadState.find(folder);
  984. return (i != end(_foldersLoadState)) ? &i->second : nullptr;
  985. }
  986. void ApiWrap::dialogsLoadFinish(Data::Folder *folder) {
  987. const auto notify = [&] {
  988. Core::App().postponeCall(crl::guard(_session, [=] {
  989. _session->data().chatsListDone(folder);
  990. }));
  991. };
  992. const auto state = dialogsLoadState(folder);
  993. if (!state || !state->listReceived || !state->pinnedReceived) {
  994. return;
  995. }
  996. if (folder) {
  997. _foldersLoadState.remove(folder);
  998. notify();
  999. } else {
  1000. _dialogsLoadState = nullptr;
  1001. notify();
  1002. }
  1003. }
  1004. void ApiWrap::requestPinnedDialogs(Data::Folder *folder) {
  1005. const auto state = dialogsLoadState(folder);
  1006. if (!state || state->pinnedReceived || state->pinnedRequestId) {
  1007. return;
  1008. }
  1009. const auto finalize = [=] {
  1010. if (const auto state = dialogsLoadState(folder)) {
  1011. state->pinnedRequestId = 0;
  1012. state->pinnedReceived = true;
  1013. dialogsLoadFinish(folder);
  1014. }
  1015. };
  1016. state->pinnedRequestId = request(MTPmessages_GetPinnedDialogs(
  1017. MTP_int(folder ? folder->id() : 0)
  1018. )).done([=](const MTPmessages_PeerDialogs &result) {
  1019. finalize();
  1020. result.match([&](const MTPDmessages_peerDialogs &data) {
  1021. _session->data().processUsers(data.vusers());
  1022. _session->data().processChats(data.vchats());
  1023. _session->data().clearPinnedChats(folder);
  1024. _session->data().applyDialogs(
  1025. folder,
  1026. data.vmessages().v,
  1027. data.vdialogs().v);
  1028. _session->data().chatsListChanged(folder);
  1029. _session->data().notifyPinnedDialogsOrderUpdated();
  1030. });
  1031. }).fail([=] {
  1032. finalize();
  1033. }).send();
  1034. }
  1035. void ApiWrap::requestMoreBlockedByDateDialogs() {
  1036. if (!_dialogsLoadState) {
  1037. return;
  1038. }
  1039. const auto max = _session->settings().supportChatsTimeSlice();
  1040. _dialogsLoadTill = _dialogsLoadState->offsetDate
  1041. ? (_dialogsLoadState->offsetDate - max)
  1042. : (base::unixtime::now() - max);
  1043. refreshDialogsLoadBlocked();
  1044. requestDialogs();
  1045. }
  1046. rpl::producer<bool> ApiWrap::dialogsLoadMayBlockByDate() const {
  1047. return _dialogsLoadMayBlockByDate.value();
  1048. }
  1049. rpl::producer<bool> ApiWrap::dialogsLoadBlockedByDate() const {
  1050. return _dialogsLoadBlockedByDate.value();
  1051. }
  1052. void ApiWrap::requestWallPaper(
  1053. const QString &slug,
  1054. Fn<void(const Data::WallPaper &)> done,
  1055. Fn<void()> fail) {
  1056. if (_wallPaperSlug != slug) {
  1057. _wallPaperSlug = slug;
  1058. if (_wallPaperRequestId) {
  1059. request(base::take(_wallPaperRequestId)).cancel();
  1060. }
  1061. }
  1062. _wallPaperDone = std::move(done);
  1063. _wallPaperFail = std::move(fail);
  1064. if (_wallPaperRequestId) {
  1065. return;
  1066. }
  1067. _wallPaperRequestId = request(MTPaccount_GetWallPaper(
  1068. MTP_inputWallPaperSlug(MTP_string(slug))
  1069. )).done([=](const MTPWallPaper &result) {
  1070. _wallPaperRequestId = 0;
  1071. _wallPaperSlug = QString();
  1072. if (const auto paper = Data::WallPaper::Create(_session, result)) {
  1073. if (const auto done = base::take(_wallPaperDone)) {
  1074. done(*paper);
  1075. }
  1076. } else if (const auto fail = base::take(_wallPaperFail)) {
  1077. fail();
  1078. }
  1079. }).fail([=](const MTP::Error &error) {
  1080. _wallPaperRequestId = 0;
  1081. _wallPaperSlug = QString();
  1082. if (const auto fail = base::take(_wallPaperFail)) {
  1083. fail();
  1084. }
  1085. }).send();
  1086. }
  1087. void ApiWrap::requestFullPeer(not_null<PeerData*> peer) {
  1088. if (_fullPeerRequests.contains(peer)) {
  1089. return;
  1090. }
  1091. const auto requestId = [&] {
  1092. const auto failHandler = [=](const MTP::Error &error) {
  1093. _fullPeerRequests.remove(peer);
  1094. migrateFail(peer, error.type());
  1095. };
  1096. if (const auto user = peer->asUser()) {
  1097. if (_session->supportMode()) {
  1098. _session->supportHelper().refreshInfo(user);
  1099. }
  1100. return request(MTPusers_GetFullUser(
  1101. user->inputUser
  1102. )).done([=](const MTPusers_UserFull &result) {
  1103. result.match([&](const MTPDusers_userFull &data) {
  1104. _session->data().processUsers(data.vusers());
  1105. _session->data().processChats(data.vchats());
  1106. });
  1107. gotUserFull(user, result);
  1108. }).fail(failHandler).send();
  1109. } else if (const auto chat = peer->asChat()) {
  1110. return request(MTPmessages_GetFullChat(
  1111. chat->inputChat
  1112. )).done([=](const MTPmessages_ChatFull &result) {
  1113. gotChatFull(peer, result);
  1114. }).fail(failHandler).send();
  1115. } else if (const auto channel = peer->asChannel()) {
  1116. return request(MTPchannels_GetFullChannel(
  1117. channel->inputChannel
  1118. )).done([=](const MTPmessages_ChatFull &result) {
  1119. gotChatFull(peer, result);
  1120. migrateDone(channel, channel);
  1121. }).fail(failHandler).send();
  1122. }
  1123. Unexpected("Peer type in requestFullPeer.");
  1124. }();
  1125. _fullPeerRequests.emplace(peer, requestId);
  1126. }
  1127. void ApiWrap::processFullPeer(
  1128. not_null<PeerData*> peer,
  1129. const MTPmessages_ChatFull &result) {
  1130. gotChatFull(peer, result);
  1131. }
  1132. void ApiWrap::gotChatFull(
  1133. not_null<PeerData*> peer,
  1134. const MTPmessages_ChatFull &result) {
  1135. const auto &d = result.c_messages_chatFull();
  1136. _session->data().applyMaximumChatVersions(d.vchats());
  1137. _session->data().processUsers(d.vusers());
  1138. _session->data().processChats(d.vchats());
  1139. d.vfull_chat().match([&](const MTPDchatFull &data) {
  1140. if (const auto chat = peer->asChat()) {
  1141. Data::ApplyChatUpdate(chat, data);
  1142. } else {
  1143. LOG(("MTP Error: bad type in gotChatFull for channel: %1"
  1144. ).arg(d.vfull_chat().type()));
  1145. }
  1146. }, [&](const MTPDchannelFull &data) {
  1147. if (const auto channel = peer->asChannel()) {
  1148. Data::ApplyChannelUpdate(channel, data);
  1149. } else {
  1150. LOG(("MTP Error: bad type in gotChatFull for chat: %1"
  1151. ).arg(d.vfull_chat().type()));
  1152. }
  1153. });
  1154. _fullPeerRequests.remove(peer);
  1155. _session->changes().peerUpdated(
  1156. peer,
  1157. Data::PeerUpdate::Flag::FullInfo);
  1158. }
  1159. void ApiWrap::gotUserFull(
  1160. not_null<UserData*> user,
  1161. const MTPusers_UserFull &result) {
  1162. result.match([&](const MTPDusers_userFull &data) {
  1163. data.vfull_user().match([&](const MTPDuserFull &fields) {
  1164. if (user == _session->user() && !_session->validateSelf(fields.vid().v)) {
  1165. constexpr auto kRequestUserAgainTimeout = crl::time(10000);
  1166. base::call_delayed(kRequestUserAgainTimeout, _session, [=] {
  1167. requestFullPeer(user);
  1168. });
  1169. return;
  1170. }
  1171. Data::ApplyUserUpdate(user, fields);
  1172. });
  1173. });
  1174. _fullPeerRequests.remove(user);
  1175. _session->changes().peerUpdated(
  1176. user,
  1177. Data::PeerUpdate::Flag::FullInfo);
  1178. }
  1179. void ApiWrap::requestPeerSettings(not_null<PeerData*> peer) {
  1180. if (!_requestedPeerSettings.emplace(peer).second) {
  1181. return;
  1182. }
  1183. request(MTPmessages_GetPeerSettings(
  1184. peer->input
  1185. )).done([=](const MTPmessages_PeerSettings &result) {
  1186. result.match([&](const MTPDmessages_peerSettings &data) {
  1187. _session->data().processUsers(data.vusers());
  1188. _session->data().processChats(data.vchats());
  1189. peer->setBarSettings(data.vsettings());
  1190. _requestedPeerSettings.erase(peer);
  1191. });
  1192. }).fail([=] {
  1193. _requestedPeerSettings.erase(peer);
  1194. }).send();
  1195. }
  1196. void ApiWrap::migrateChat(
  1197. not_null<ChatData*> chat,
  1198. FnMut<void(not_null<ChannelData*>)> done,
  1199. Fn<void(const QString &)> fail) {
  1200. const auto callback = [&] {
  1201. return MigrateCallbacks{ std::move(done), std::move(fail) };
  1202. };
  1203. const auto i = _migrateCallbacks.find(chat);
  1204. if (i != _migrateCallbacks.end()) {
  1205. i->second.push_back(callback());
  1206. return;
  1207. }
  1208. _migrateCallbacks.emplace(chat).first->second.push_back(callback());
  1209. if (const auto channel = chat->migrateTo()) {
  1210. session().changes().peerUpdated(
  1211. chat,
  1212. Data::PeerUpdate::Flag::Migration);
  1213. crl::on_main([=] {
  1214. migrateDone(chat, channel);
  1215. });
  1216. } else if (chat->isDeactivated()) {
  1217. crl::on_main([=] {
  1218. migrateFail(
  1219. chat,
  1220. MTP::Error::Local(
  1221. "BAD_MIGRATION",
  1222. "Chat is already deactivated").type());
  1223. });
  1224. return;
  1225. } else if (!chat->amCreator()) {
  1226. crl::on_main([=] {
  1227. migrateFail(
  1228. chat,
  1229. MTP::Error::Local(
  1230. "BAD_MIGRATION",
  1231. "Current user is not the creator of that chat").type());
  1232. });
  1233. return;
  1234. }
  1235. request(MTPmessages_MigrateChat(
  1236. chat->inputChat
  1237. )).done([=](const MTPUpdates &result) {
  1238. applyUpdates(result);
  1239. session().changes().sendNotifications();
  1240. if (const auto channel = chat->migrateTo()) {
  1241. if (auto handlers = _migrateCallbacks.take(chat)) {
  1242. _migrateCallbacks.emplace(channel, std::move(*handlers));
  1243. }
  1244. requestFullPeer(channel);
  1245. } else {
  1246. migrateFail(
  1247. chat,
  1248. MTP::Error::Local("MIGRATION_FAIL", "No channel").type());
  1249. }
  1250. }).fail([=](const MTP::Error &error) {
  1251. migrateFail(chat, error.type());
  1252. }).send();
  1253. }
  1254. void ApiWrap::migrateDone(
  1255. not_null<PeerData*> peer,
  1256. not_null<ChannelData*> channel) {
  1257. session().changes().sendNotifications();
  1258. if (auto handlers = _migrateCallbacks.take(peer)) {
  1259. for (auto &handler : *handlers) {
  1260. if (handler.done) {
  1261. handler.done(channel);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. void ApiWrap::migrateFail(not_null<PeerData*> peer, const QString &error) {
  1267. if (error == u"CHANNELS_TOO_MUCH"_q) {
  1268. ShowChannelsLimitBox(peer);
  1269. }
  1270. if (auto handlers = _migrateCallbacks.take(peer)) {
  1271. for (auto &handler : *handlers) {
  1272. if (handler.fail) {
  1273. handler.fail(error);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. void ApiWrap::markContentsRead(
  1279. const base::flat_set<not_null<HistoryItem*>> &items) {
  1280. auto markedIds = QVector<MTPint>();
  1281. auto channelMarkedIds = base::flat_map<
  1282. not_null<ChannelData*>,
  1283. QVector<MTPint>>();
  1284. markedIds.reserve(items.size());
  1285. for (const auto &item : items) {
  1286. if (!item->markContentsRead(true) || !item->isRegular()) {
  1287. continue;
  1288. }
  1289. if (const auto channel = item->history()->peer->asChannel()) {
  1290. channelMarkedIds[channel].push_back(MTP_int(item->id));
  1291. } else {
  1292. markedIds.push_back(MTP_int(item->id));
  1293. }
  1294. }
  1295. if (!markedIds.isEmpty()) {
  1296. request(MTPmessages_ReadMessageContents(
  1297. MTP_vector<MTPint>(markedIds)
  1298. )).done([=](const MTPmessages_AffectedMessages &result) {
  1299. applyAffectedMessages(result);
  1300. }).send();
  1301. }
  1302. for (const auto &channelIds : channelMarkedIds) {
  1303. request(MTPchannels_ReadMessageContents(
  1304. channelIds.first->inputChannel,
  1305. MTP_vector<MTPint>(channelIds.second)
  1306. )).send();
  1307. }
  1308. }
  1309. void ApiWrap::markContentsRead(not_null<HistoryItem*> item) {
  1310. if (!item->markContentsRead(true) || !item->isRegular()) {
  1311. return;
  1312. }
  1313. const auto ids = MTP_vector<MTPint>(1, MTP_int(item->id));
  1314. if (const auto channel = item->history()->peer->asChannel()) {
  1315. request(MTPchannels_ReadMessageContents(
  1316. channel->inputChannel,
  1317. ids
  1318. )).send();
  1319. } else {
  1320. request(MTPmessages_ReadMessageContents(
  1321. ids
  1322. )).done([=](const MTPmessages_AffectedMessages &result) {
  1323. applyAffectedMessages(result);
  1324. }).send();
  1325. }
  1326. }
  1327. void ApiWrap::deleteAllFromParticipant(
  1328. not_null<ChannelData*> channel,
  1329. not_null<PeerData*> from) {
  1330. const auto history = _session->data().historyLoaded(channel);
  1331. const auto ids = history
  1332. ? history->collectMessagesFromParticipantToDelete(from)
  1333. : std::vector<MsgId>();
  1334. for (const auto &msgId : ids) {
  1335. if (const auto item = _session->data().message(channel->id, msgId)) {
  1336. item->destroy();
  1337. }
  1338. }
  1339. _session->data().sendHistoryChangeNotifications();
  1340. deleteAllFromParticipantSend(channel, from);
  1341. }
  1342. void ApiWrap::deleteAllFromParticipantSend(
  1343. not_null<ChannelData*> channel,
  1344. not_null<PeerData*> from) {
  1345. request(MTPchannels_DeleteParticipantHistory(
  1346. channel->inputChannel,
  1347. from->input
  1348. )).done([=](const MTPmessages_AffectedHistory &result) {
  1349. const auto offset = applyAffectedHistory(channel, result);
  1350. if (offset > 0) {
  1351. deleteAllFromParticipantSend(channel, from);
  1352. } else if (const auto history = _session->data().historyLoaded(channel)) {
  1353. history->requestChatListMessage();
  1354. }
  1355. }).send();
  1356. }
  1357. void ApiWrap::scheduleStickerSetRequest(uint64 setId, uint64 access) {
  1358. if (!_stickerSetRequests.contains(setId)) {
  1359. _stickerSetRequests.emplace(setId, StickerSetRequest{ access });
  1360. }
  1361. }
  1362. void ApiWrap::requestStickerSets() {
  1363. for (auto &[id, info] : _stickerSetRequests) {
  1364. if (info.id) {
  1365. continue;
  1366. }
  1367. info.id = request(MTPmessages_GetStickerSet(
  1368. MTP_inputStickerSetID(
  1369. MTP_long(id),
  1370. MTP_long(info.accessHash)),
  1371. MTP_int(0) // hash
  1372. )).done([=, setId = id](const MTPmessages_StickerSet &result) {
  1373. gotStickerSet(setId, result);
  1374. }).fail([=, setId = id] {
  1375. _stickerSetRequests.remove(setId);
  1376. }).afterDelay(kSmallDelayMs).send();
  1377. }
  1378. }
  1379. void ApiWrap::saveStickerSets(
  1380. const Data::StickersSetsOrder &localOrder,
  1381. const Data::StickersSetsOrder &localRemoved,
  1382. Data::StickersType type) {
  1383. auto &setDisenableRequests = (type == Data::StickersType::Emoji)
  1384. ? _customEmojiSetDisenableRequests
  1385. : (type == Data::StickersType::Masks)
  1386. ? _maskSetDisenableRequests
  1387. : _stickerSetDisenableRequests;
  1388. const auto reorderRequestId = [=]() -> mtpRequestId & {
  1389. return (type == Data::StickersType::Emoji)
  1390. ? _customEmojiReorderRequestId
  1391. : (type == Data::StickersType::Masks)
  1392. ? _masksReorderRequestId
  1393. : _stickersReorderRequestId;
  1394. };
  1395. for (auto requestId : base::take(setDisenableRequests)) {
  1396. request(requestId).cancel();
  1397. }
  1398. request(base::take(reorderRequestId())).cancel();
  1399. request(base::take(_stickersClearRecentRequestId)).cancel();
  1400. request(base::take(_stickersClearRecentAttachedRequestId)).cancel();
  1401. const auto stickersSaveOrder = [=] {
  1402. if (localOrder.size() < 2) {
  1403. return;
  1404. }
  1405. QVector<MTPlong> mtpOrder;
  1406. mtpOrder.reserve(localOrder.size());
  1407. for (const auto setId : std::as_const(localOrder)) {
  1408. mtpOrder.push_back(MTP_long(setId));
  1409. }
  1410. using Flag = MTPmessages_ReorderStickerSets::Flag;
  1411. const auto flags = (type == Data::StickersType::Emoji)
  1412. ? Flag::f_emojis
  1413. : (type == Data::StickersType::Masks)
  1414. ? Flag::f_masks
  1415. : Flag(0);
  1416. reorderRequestId() = request(MTPmessages_ReorderStickerSets(
  1417. MTP_flags(flags),
  1418. MTP_vector<MTPlong>(mtpOrder)
  1419. )).done([=] {
  1420. reorderRequestId() = 0;
  1421. }).fail([=] {
  1422. reorderRequestId() = 0;
  1423. if (type == Data::StickersType::Emoji) {
  1424. _session->data().stickers().setLastEmojiUpdate(0);
  1425. updateCustomEmoji();
  1426. } else if (type == Data::StickersType::Masks) {
  1427. _session->data().stickers().setLastMasksUpdate(0);
  1428. updateMasks();
  1429. } else {
  1430. _session->data().stickers().setLastUpdate(0);
  1431. updateStickers();
  1432. }
  1433. }).send();
  1434. };
  1435. const auto stickerSetDisenabled = [=](mtpRequestId requestId) {
  1436. auto &setDisenableRequests = (type == Data::StickersType::Emoji)
  1437. ? _customEmojiSetDisenableRequests
  1438. : (type == Data::StickersType::Masks)
  1439. ? _maskSetDisenableRequests
  1440. : _stickerSetDisenableRequests;
  1441. setDisenableRequests.remove(requestId);
  1442. if (setDisenableRequests.empty()) {
  1443. stickersSaveOrder();
  1444. }
  1445. };
  1446. auto writeInstalled = true,
  1447. writeRecent = false,
  1448. writeCloudRecent = false,
  1449. writeCloudRecentAttached = false,
  1450. writeFaved = false,
  1451. writeArchived = false;
  1452. auto &recent = _session->data().stickers().getRecentPack();
  1453. auto &sets = _session->data().stickers().setsRef();
  1454. auto &order = (type == Data::StickersType::Emoji)
  1455. ? _session->data().stickers().emojiSetsOrder()
  1456. : (type == Data::StickersType::Masks)
  1457. ? _session->data().stickers().maskSetsOrder()
  1458. : _session->data().stickers().setsOrder();
  1459. auto &orderRef = (type == Data::StickersType::Emoji)
  1460. ? _session->data().stickers().emojiSetsOrderRef()
  1461. : (type == Data::StickersType::Masks)
  1462. ? _session->data().stickers().maskSetsOrderRef()
  1463. : _session->data().stickers().setsOrderRef();
  1464. using Flag = Data::StickersSetFlag;
  1465. for (const auto removedSetId : localRemoved) {
  1466. if ((removedSetId == Data::Stickers::CloudRecentSetId)
  1467. || (removedSetId == Data::Stickers::CloudRecentAttachedSetId)) {
  1468. if (sets.remove(Data::Stickers::CloudRecentSetId) != 0) {
  1469. writeCloudRecent = true;
  1470. }
  1471. if (sets.remove(Data::Stickers::CloudRecentAttachedSetId) != 0) {
  1472. writeCloudRecentAttached = true;
  1473. }
  1474. if (sets.remove(Data::Stickers::CustomSetId)) {
  1475. writeInstalled = true;
  1476. }
  1477. if (!recent.isEmpty()) {
  1478. recent.clear();
  1479. writeRecent = true;
  1480. }
  1481. const auto isAttached
  1482. = (removedSetId == Data::Stickers::CloudRecentAttachedSetId);
  1483. const auto flags = isAttached
  1484. ? MTPmessages_ClearRecentStickers::Flag::f_attached
  1485. : MTPmessages_ClearRecentStickers::Flags(0);
  1486. auto &requestId = isAttached
  1487. ? _stickersClearRecentAttachedRequestId
  1488. : _stickersClearRecentRequestId;
  1489. const auto finish = [=] {
  1490. (isAttached
  1491. ? _stickersClearRecentAttachedRequestId
  1492. : _stickersClearRecentRequestId) = 0;
  1493. };
  1494. requestId = request(MTPmessages_ClearRecentStickers(
  1495. MTP_flags(flags)
  1496. )).done(finish).fail(finish).send();
  1497. continue;
  1498. }
  1499. auto it = sets.find(removedSetId);
  1500. if (it != sets.cend()) {
  1501. const auto set = it->second.get();
  1502. for (auto i = recent.begin(); i != recent.cend();) {
  1503. if (set->stickers.indexOf(i->first) >= 0) {
  1504. i = recent.erase(i);
  1505. writeRecent = true;
  1506. } else {
  1507. ++i;
  1508. }
  1509. }
  1510. const auto archived = !!(set->flags & Flag::Archived);
  1511. if (!archived) {
  1512. const auto featured = !!(set->flags & Flag::Featured);
  1513. const auto special = !!(set->flags & Flag::Special);
  1514. const auto emoji = !!(set->flags & Flag::Emoji);
  1515. const auto locked = (set->locked > 0);
  1516. const auto setId = set->mtpInput();
  1517. auto requestId = request(MTPmessages_UninstallStickerSet(
  1518. setId
  1519. )).done([=](const MTPBool &result, mtpRequestId requestId) {
  1520. stickerSetDisenabled(requestId);
  1521. }).fail([=](const MTP::Error &error, mtpRequestId requestId) {
  1522. stickerSetDisenabled(requestId);
  1523. }).afterDelay(kSmallDelayMs).send();
  1524. setDisenableRequests.insert(requestId);
  1525. const auto removeIndex = order.indexOf(set->id);
  1526. if (removeIndex >= 0) {
  1527. orderRef.removeAt(removeIndex);
  1528. }
  1529. if (!featured && !special && !emoji && !locked) {
  1530. sets.erase(it);
  1531. } else {
  1532. if (archived) {
  1533. writeArchived = true;
  1534. }
  1535. set->flags &= ~(Flag::Installed | Flag::Archived);
  1536. set->installDate = TimeId(0);
  1537. }
  1538. }
  1539. }
  1540. }
  1541. // Clear all installed flags, set only for sets from order.
  1542. for (auto &[id, set] : sets) {
  1543. const auto archived = !!(set->flags & Flag::Archived);
  1544. const auto thatType = !!(set->flags & Flag::Emoji)
  1545. ? Data::StickersType::Emoji
  1546. : !!(set->flags & Flag::Masks)
  1547. ? Data::StickersType::Masks
  1548. : Data::StickersType::Stickers;
  1549. if (!archived && (type == thatType)) {
  1550. set->flags &= ~Flag::Installed;
  1551. }
  1552. }
  1553. orderRef.clear();
  1554. for (const auto setId : std::as_const(localOrder)) {
  1555. auto it = sets.find(setId);
  1556. if (it == sets.cend()) {
  1557. continue;
  1558. }
  1559. const auto set = it->second.get();
  1560. const auto archived = !!(set->flags & Flag::Archived);
  1561. if (archived && !localRemoved.contains(set->id)) {
  1562. const auto mtpSetId = set->mtpInput();
  1563. const auto requestId = request(MTPmessages_InstallStickerSet(
  1564. mtpSetId,
  1565. MTP_boolFalse()
  1566. )).done([=](
  1567. const MTPmessages_StickerSetInstallResult &result,
  1568. mtpRequestId requestId) {
  1569. stickerSetDisenabled(requestId);
  1570. }).fail([=](
  1571. const MTP::Error &error,
  1572. mtpRequestId requestId) {
  1573. stickerSetDisenabled(requestId);
  1574. }).afterDelay(kSmallDelayMs).send();
  1575. setDisenableRequests.insert(requestId);
  1576. set->flags &= ~Flag::Archived;
  1577. writeArchived = true;
  1578. }
  1579. orderRef.push_back(setId);
  1580. set->flags |= Flag::Installed;
  1581. if (!set->installDate) {
  1582. set->installDate = base::unixtime::now();
  1583. }
  1584. }
  1585. for (auto it = sets.begin(); it != sets.cend();) {
  1586. const auto set = it->second.get();
  1587. if ((set->flags & Flag::Featured)
  1588. || (set->flags & Flag::Installed)
  1589. || (set->flags & Flag::Archived)
  1590. || (set->flags & Flag::Special)
  1591. || (set->flags & Flag::Emoji)
  1592. || (set->locked > 0)) {
  1593. ++it;
  1594. } else {
  1595. it = sets.erase(it);
  1596. }
  1597. }
  1598. auto &storage = local();
  1599. if (writeInstalled) {
  1600. if (type == Data::StickersType::Emoji) {
  1601. storage.writeInstalledCustomEmoji();
  1602. } else if (type == Data::StickersType::Masks) {
  1603. storage.writeInstalledMasks();
  1604. } else {
  1605. storage.writeInstalledStickers();
  1606. }
  1607. }
  1608. if (writeRecent) {
  1609. session().saveSettings();
  1610. }
  1611. if (writeArchived) {
  1612. if (type == Data::StickersType::Emoji) {
  1613. } else if (type == Data::StickersType::Masks) {
  1614. storage.writeArchivedMasks();
  1615. } else {
  1616. storage.writeArchivedStickers();
  1617. }
  1618. }
  1619. if (writeCloudRecent) {
  1620. storage.writeRecentStickers();
  1621. }
  1622. if (writeCloudRecentAttached) {
  1623. storage.writeRecentMasks();
  1624. }
  1625. if (writeFaved) {
  1626. storage.writeFavedStickers();
  1627. }
  1628. _session->data().stickers().notifyUpdated(type);
  1629. if (setDisenableRequests.empty()) {
  1630. stickersSaveOrder();
  1631. } else {
  1632. requestSendDelayed();
  1633. }
  1634. }
  1635. void ApiWrap::joinChannel(not_null<ChannelData*> channel) {
  1636. if (channel->amIn()) {
  1637. session().changes().peerUpdated(
  1638. channel,
  1639. Data::PeerUpdate::Flag::ChannelAmIn);
  1640. } else if (!_channelAmInRequests.contains(channel)) {
  1641. const auto requestId = request(MTPchannels_JoinChannel(
  1642. channel->inputChannel
  1643. )).done([=](const MTPUpdates &result) {
  1644. _channelAmInRequests.remove(channel);
  1645. applyUpdates(result);
  1646. }).fail([=](const MTP::Error &error) {
  1647. const auto &type = error.type();
  1648. const auto show = ShowForPeer(channel);
  1649. if (type == u"CHANNEL_PRIVATE"_q
  1650. && channel->invitePeekExpires()) {
  1651. channel->privateErrorReceived();
  1652. } else if (type == u"CHANNELS_TOO_MUCH"_q) {
  1653. ShowChannelsLimitBox(channel);
  1654. } else {
  1655. const auto text = [&] {
  1656. if (type == u"INVITE_REQUEST_SENT"_q) {
  1657. return channel->isMegagroup()
  1658. ? tr::lng_group_request_sent(tr::now)
  1659. : tr::lng_group_request_sent_channel(tr::now);
  1660. } else if (type == u"CHANNEL_PRIVATE"_q
  1661. || type == u"CHANNEL_PUBLIC_GROUP_NA"_q
  1662. || type == u"USER_BANNED_IN_CHANNEL"_q) {
  1663. return channel->isMegagroup()
  1664. ? tr::lng_group_not_accessible(tr::now)
  1665. : tr::lng_channel_not_accessible(tr::now);
  1666. } else if (type == u"USERS_TOO_MUCH"_q) {
  1667. return tr::lng_group_full(tr::now);
  1668. }
  1669. return QString();
  1670. }();
  1671. if (show && !text.isEmpty()) {
  1672. show->showToast(text, kJoinErrorDuration);
  1673. }
  1674. }
  1675. _channelAmInRequests.remove(channel);
  1676. }).send();
  1677. _channelAmInRequests.emplace(channel, requestId);
  1678. using Flag = ChannelDataFlag;
  1679. chatParticipants().loadSimilarPeers(channel);
  1680. channel->setFlags(channel->flags() | Flag::SimilarExpanded);
  1681. }
  1682. }
  1683. void ApiWrap::leaveChannel(not_null<ChannelData*> channel) {
  1684. if (!channel->amIn()) {
  1685. session().changes().peerUpdated(
  1686. channel,
  1687. Data::PeerUpdate::Flag::ChannelAmIn);
  1688. } else if (!_channelAmInRequests.contains(channel)) {
  1689. auto requestId = request(MTPchannels_LeaveChannel(
  1690. channel->inputChannel
  1691. )).done([=](const MTPUpdates &result) {
  1692. _channelAmInRequests.remove(channel);
  1693. applyUpdates(result);
  1694. }).fail([=] {
  1695. _channelAmInRequests.remove(channel);
  1696. }).send();
  1697. _channelAmInRequests.emplace(channel, requestId);
  1698. }
  1699. }
  1700. void ApiWrap::requestNotifySettings(const MTPInputNotifyPeer &peer) {
  1701. const auto bad = peer.match([](const MTPDinputNotifyUsers &) {
  1702. return false;
  1703. }, [](const MTPDinputNotifyChats &) {
  1704. return false;
  1705. }, [](const MTPDinputNotifyBroadcasts &) {
  1706. return false;
  1707. }, [&](const MTPDinputNotifyPeer &data) {
  1708. if (data.vpeer().type() == mtpc_inputPeerEmpty) {
  1709. LOG(("Api Error: Requesting settings for empty peer."));
  1710. return true;
  1711. }
  1712. return false;
  1713. }, [&](const MTPDinputNotifyForumTopic &data) {
  1714. if (data.vpeer().type() == mtpc_inputPeerEmpty) {
  1715. LOG(("Api Error: Requesting settings for empty peer topic."));
  1716. return true;
  1717. }
  1718. return false;
  1719. });
  1720. if (bad) {
  1721. return;
  1722. }
  1723. const auto peerFromInput = [&](const MTPInputPeer &inputPeer) {
  1724. return inputPeer.match([&](const MTPDinputPeerSelf &) {
  1725. return _session->userPeerId();
  1726. }, [](const MTPDinputPeerEmpty &) {
  1727. return PeerId(0);
  1728. }, [](const MTPDinputPeerChannel &data) {
  1729. return peerFromChannel(data.vchannel_id());
  1730. }, [](const MTPDinputPeerChat &data) {
  1731. return peerFromChat(data.vchat_id());
  1732. }, [](const MTPDinputPeerUser &data) {
  1733. return peerFromUser(data.vuser_id());
  1734. }, [](const auto &) -> PeerId {
  1735. Unexpected("Type in ApiRequest::requestNotifySettings peer.");
  1736. });
  1737. };
  1738. const auto key = peer.match([](const MTPDinputNotifyUsers &) {
  1739. return NotifySettingsKey{ peerFromUser(1) };
  1740. }, [](const MTPDinputNotifyChats &) {
  1741. return NotifySettingsKey{ peerFromChat(1) };
  1742. }, [](const MTPDinputNotifyBroadcasts &) {
  1743. return NotifySettingsKey{ peerFromChannel(1) };
  1744. }, [&](const MTPDinputNotifyPeer &data) {
  1745. return NotifySettingsKey{ peerFromInput(data.vpeer()) };
  1746. }, [&](const MTPDinputNotifyForumTopic &data) {
  1747. return NotifySettingsKey{
  1748. peerFromInput(data.vpeer()),
  1749. data.vtop_msg_id().v,
  1750. };
  1751. });
  1752. if (_notifySettingRequests.contains(key)) {
  1753. return;
  1754. }
  1755. const auto requestId = request(MTPaccount_GetNotifySettings(
  1756. peer
  1757. )).done([=](const MTPPeerNotifySettings &result) {
  1758. _session->data().notifySettings().apply(peer, result);
  1759. _notifySettingRequests.remove(key);
  1760. }).fail([=] {
  1761. _session->data().notifySettings().apply(
  1762. peer,
  1763. MTP_peerNotifySettings(
  1764. MTP_flags(0),
  1765. MTPBool(),
  1766. MTPBool(),
  1767. MTPint(),
  1768. MTPNotificationSound(),
  1769. MTPNotificationSound(),
  1770. MTPNotificationSound(),
  1771. MTPBool(),
  1772. MTPBool(),
  1773. MTPNotificationSound(),
  1774. MTPNotificationSound(),
  1775. MTPNotificationSound()));
  1776. _notifySettingRequests.erase(key);
  1777. }).send();
  1778. _notifySettingRequests.emplace(key, requestId);
  1779. }
  1780. void ApiWrap::updateNotifySettingsDelayed(
  1781. not_null<const Data::Thread*> thread) {
  1782. const auto topic = thread->asTopic();
  1783. if (!topic) {
  1784. return updateNotifySettingsDelayed(thread->peer());
  1785. }
  1786. if (_updateNotifyTopics.emplace(topic).second) {
  1787. topic->destroyed(
  1788. ) | rpl::start_with_next([=] {
  1789. _updateNotifyTopics.remove(topic);
  1790. }, _updateNotifyQueueLifetime);
  1791. _updateNotifyTimer.callOnce(kNotifySettingSaveTimeout);
  1792. }
  1793. }
  1794. void ApiWrap::updateNotifySettingsDelayed(not_null<const PeerData*> peer) {
  1795. if (_updateNotifyPeers.emplace(peer).second) {
  1796. _updateNotifyTimer.callOnce(kNotifySettingSaveTimeout);
  1797. }
  1798. }
  1799. void ApiWrap::updateNotifySettingsDelayed(Data::DefaultNotify type) {
  1800. if (_updateNotifyDefaults.emplace(type).second) {
  1801. _updateNotifyTimer.callOnce(kNotifySettingSaveTimeout);
  1802. }
  1803. }
  1804. void ApiWrap::sendNotifySettingsUpdates() {
  1805. _updateNotifyQueueLifetime.destroy();
  1806. for (const auto topic : base::take(_updateNotifyTopics)) {
  1807. request(MTPaccount_UpdateNotifySettings(
  1808. MTP_inputNotifyForumTopic(
  1809. topic->channel()->input,
  1810. MTP_int(topic->rootId())),
  1811. topic->notify().serialize()
  1812. )).afterDelay(kSmallDelayMs).send();
  1813. }
  1814. for (const auto peer : base::take(_updateNotifyPeers)) {
  1815. request(MTPaccount_UpdateNotifySettings(
  1816. MTP_inputNotifyPeer(peer->input),
  1817. peer->notify().serialize()
  1818. )).afterDelay(kSmallDelayMs).send();
  1819. }
  1820. const auto &settings = session().data().notifySettings();
  1821. for (const auto type : base::take(_updateNotifyDefaults)) {
  1822. request(MTPaccount_UpdateNotifySettings(
  1823. Data::DefaultNotifyToMTP(type),
  1824. settings.defaultSettings(type).serialize()
  1825. )).afterDelay(kSmallDelayMs).send();
  1826. }
  1827. session().mtp().sendAnything();
  1828. }
  1829. void ApiWrap::saveDraftToCloudDelayed(not_null<Data::Thread*> thread) {
  1830. _draftsSaveRequestIds.emplace(base::make_weak(thread), 0);
  1831. if (!_draftsSaveTimer.isActive()) {
  1832. _draftsSaveTimer.callOnce(kSaveCloudDraftTimeout);
  1833. }
  1834. }
  1835. void ApiWrap::updatePrivacyLastSeens() {
  1836. const auto now = base::unixtime::now();
  1837. if (!_session->premium()) {
  1838. _session->data().enumerateUsers([&](not_null<UserData*> user) {
  1839. if (user->isSelf()
  1840. || !user->isLoaded()
  1841. || user->lastseen().isHidden()) {
  1842. return;
  1843. }
  1844. const auto till = user->lastseen().onlineTill();
  1845. user->updateLastseen((till + 3 * 86400 >= now)
  1846. ? Data::LastseenStatus::Recently(true)
  1847. : (till + 7 * 86400 >= now)
  1848. ? Data::LastseenStatus::WithinWeek(true)
  1849. : (till + 30 * 86400 >= now)
  1850. ? Data::LastseenStatus::WithinMonth(true)
  1851. : Data::LastseenStatus::LongAgo(true));
  1852. session().changes().peerUpdated(
  1853. user,
  1854. Data::PeerUpdate::Flag::OnlineStatus);
  1855. session().data().maybeStopWatchForOffline(user);
  1856. });
  1857. }
  1858. if (_contactsStatusesRequestId) {
  1859. request(_contactsStatusesRequestId).cancel();
  1860. }
  1861. _contactsStatusesRequestId = request(MTPcontacts_GetStatuses(
  1862. )).done([=](const MTPVector<MTPContactStatus> &result) {
  1863. _contactsStatusesRequestId = 0;
  1864. for (const auto &status : result.v) {
  1865. const auto &data = status.data();
  1866. const auto userId = UserId(data.vuser_id());
  1867. if (const auto user = _session->data().userLoaded(userId)) {
  1868. const auto status = LastseenFromMTP(
  1869. data.vstatus(),
  1870. user->lastseen());
  1871. if (user->updateLastseen(status)) {
  1872. session().changes().peerUpdated(
  1873. user,
  1874. Data::PeerUpdate::Flag::OnlineStatus);
  1875. }
  1876. }
  1877. }
  1878. }).fail([this] {
  1879. _contactsStatusesRequestId = 0;
  1880. }).send();
  1881. }
  1882. void ApiWrap::clearHistory(not_null<PeerData*> peer, bool revoke) {
  1883. deleteHistory(peer, true, revoke);
  1884. }
  1885. void ApiWrap::deleteConversation(not_null<PeerData*> peer, bool revoke) {
  1886. if (const auto chat = peer->asChat()) {
  1887. request(MTPmessages_DeleteChatUser(
  1888. MTP_flags(0),
  1889. chat->inputChat,
  1890. _session->user()->inputUser
  1891. )).done([=](const MTPUpdates &result) {
  1892. applyUpdates(result);
  1893. deleteHistory(peer, false, revoke);
  1894. }).fail([=] {
  1895. deleteHistory(peer, false, revoke);
  1896. }).send();
  1897. } else {
  1898. deleteHistory(peer, false, revoke);
  1899. }
  1900. }
  1901. void ApiWrap::deleteHistory(
  1902. not_null<PeerData*> peer,
  1903. bool justClear,
  1904. bool revoke) {
  1905. auto deleteTillId = MsgId(0);
  1906. const auto history = _session->data().history(peer);
  1907. if (justClear) {
  1908. // In case of clear history we need to know the last server message.
  1909. while (history->lastMessageKnown()) {
  1910. const auto last = history->lastMessage();
  1911. if (!last) {
  1912. // History is empty.
  1913. return;
  1914. } else if (!last->isRegular()) {
  1915. // Destroy client-side message locally.
  1916. last->destroy();
  1917. } else {
  1918. break;
  1919. }
  1920. }
  1921. if (!history->lastMessageKnown()) {
  1922. history->owner().histories().requestDialogEntry(history, [=] {
  1923. Expects(history->lastMessageKnown());
  1924. deleteHistory(peer, justClear, revoke);
  1925. });
  1926. return;
  1927. }
  1928. deleteTillId = history->lastMessage()->id;
  1929. }
  1930. if (const auto channel = peer->asChannel()) {
  1931. if (!justClear && !revoke) {
  1932. channel->ptsSetWaitingForShortPoll(-1);
  1933. leaveChannel(channel);
  1934. } else {
  1935. if (const auto migrated = peer->migrateFrom()) {
  1936. deleteHistory(migrated, justClear, revoke);
  1937. }
  1938. if (deleteTillId || (!justClear && revoke)) {
  1939. history->owner().histories().deleteAllMessages(
  1940. history,
  1941. deleteTillId,
  1942. justClear,
  1943. revoke);
  1944. }
  1945. }
  1946. } else {
  1947. history->owner().histories().deleteAllMessages(
  1948. history,
  1949. deleteTillId,
  1950. justClear,
  1951. revoke);
  1952. }
  1953. if (!justClear) {
  1954. _session->data().deleteConversationLocally(peer);
  1955. } else if (history) {
  1956. history->clear(History::ClearType::ClearHistory);
  1957. }
  1958. }
  1959. void ApiWrap::applyUpdates(
  1960. const MTPUpdates &updates,
  1961. uint64 sentMessageRandomId) const {
  1962. this->updates().applyUpdates(updates, sentMessageRandomId);
  1963. }
  1964. int ApiWrap::applyAffectedHistory(
  1965. PeerData *peer,
  1966. const MTPmessages_AffectedHistory &result) const {
  1967. const auto &data = result.c_messages_affectedHistory();
  1968. if (const auto channel = peer ? peer->asChannel() : nullptr) {
  1969. channel->ptsUpdateAndApply(data.vpts().v, data.vpts_count().v);
  1970. } else {
  1971. updates().updateAndApply(data.vpts().v, data.vpts_count().v);
  1972. }
  1973. return data.voffset().v;
  1974. }
  1975. void ApiWrap::applyAffectedMessages(
  1976. not_null<PeerData*> peer,
  1977. const MTPmessages_AffectedMessages &result) {
  1978. const auto &data = result.c_messages_affectedMessages();
  1979. if (const auto channel = peer->asChannel()) {
  1980. channel->ptsUpdateAndApply(data.vpts().v, data.vpts_count().v);
  1981. } else {
  1982. applyAffectedMessages(result);
  1983. }
  1984. }
  1985. void ApiWrap::applyAffectedMessages(
  1986. const MTPmessages_AffectedMessages &result) const {
  1987. const auto &data = result.c_messages_affectedMessages();
  1988. updates().updateAndApply(data.vpts().v, data.vpts_count().v);
  1989. }
  1990. void ApiWrap::saveCurrentDraftToCloud() {
  1991. Core::App().materializeLocalDrafts();
  1992. for (const auto &controller : _session->windows()) {
  1993. if (const auto thread = controller->activeChatCurrent().thread()) {
  1994. const auto topic = thread->asTopic();
  1995. if (topic && topic->creating()) {
  1996. continue;
  1997. }
  1998. const auto history = thread->owningHistory();
  1999. _session->local().writeDrafts(history);
  2000. const auto topicRootId = thread->topicRootId();
  2001. const auto localDraft = history->localDraft(topicRootId);
  2002. const auto cloudDraft = history->cloudDraft(topicRootId);
  2003. if (!Data::DraftsAreEqual(localDraft, cloudDraft)
  2004. && !_session->supportMode()) {
  2005. saveDraftToCloudDelayed(thread);
  2006. }
  2007. }
  2008. }
  2009. }
  2010. void ApiWrap::saveDraftsToCloud() {
  2011. for (auto i = begin(_draftsSaveRequestIds); i != end(_draftsSaveRequestIds);) {
  2012. const auto weak = i->first;
  2013. const auto thread = weak.get();
  2014. if (!thread) {
  2015. i = _draftsSaveRequestIds.erase(i);
  2016. continue;
  2017. } else if (i->second) {
  2018. ++i;
  2019. continue; // sent already
  2020. }
  2021. const auto history = thread->owningHistory();
  2022. const auto topicRootId = thread->topicRootId();
  2023. auto cloudDraft = history->cloudDraft(topicRootId);
  2024. auto localDraft = history->localDraft(topicRootId);
  2025. if (cloudDraft && cloudDraft->saveRequestId) {
  2026. request(base::take(cloudDraft->saveRequestId)).cancel();
  2027. }
  2028. if (!_session->supportMode()) {
  2029. cloudDraft = history->createCloudDraft(topicRootId, localDraft);
  2030. } else if (!cloudDraft) {
  2031. cloudDraft = history->createCloudDraft(topicRootId, nullptr);
  2032. }
  2033. auto flags = MTPmessages_SaveDraft::Flags(0);
  2034. auto &textWithTags = cloudDraft->textWithTags;
  2035. if (cloudDraft->webpage.removed) {
  2036. flags |= MTPmessages_SaveDraft::Flag::f_no_webpage;
  2037. } else if (!cloudDraft->webpage.url.isEmpty()) {
  2038. flags |= MTPmessages_SaveDraft::Flag::f_media;
  2039. }
  2040. if (cloudDraft->reply.messageId || cloudDraft->reply.topicRootId) {
  2041. flags |= MTPmessages_SaveDraft::Flag::f_reply_to;
  2042. }
  2043. if (!textWithTags.tags.isEmpty()) {
  2044. flags |= MTPmessages_SaveDraft::Flag::f_entities;
  2045. }
  2046. auto entities = Api::EntitiesToMTP(
  2047. _session,
  2048. TextUtilities::ConvertTextTagsToEntities(textWithTags.tags),
  2049. Api::ConvertOption::SkipLocal);
  2050. history->startSavingCloudDraft(topicRootId);
  2051. cloudDraft->saveRequestId = request(MTPmessages_SaveDraft(
  2052. MTP_flags(flags),
  2053. ReplyToForMTP(history, cloudDraft->reply),
  2054. history->peer->input,
  2055. MTP_string(textWithTags.text),
  2056. entities,
  2057. Data::WebPageForMTP(
  2058. cloudDraft->webpage,
  2059. textWithTags.text.isEmpty()),
  2060. MTP_long(0) // effect
  2061. )).done([=](const MTPBool &result, const MTP::Response &response) {
  2062. const auto requestId = response.requestId;
  2063. history->finishSavingCloudDraft(
  2064. topicRootId,
  2065. UnixtimeFromMsgId(response.outerMsgId));
  2066. if (const auto cloudDraft = history->cloudDraft(topicRootId)) {
  2067. if (cloudDraft->saveRequestId == requestId) {
  2068. cloudDraft->saveRequestId = 0;
  2069. history->draftSavedToCloud(topicRootId);
  2070. }
  2071. }
  2072. const auto i = _draftsSaveRequestIds.find(weak);
  2073. if (i != _draftsSaveRequestIds.cend()
  2074. && i->second == requestId) {
  2075. _draftsSaveRequestIds.erase(i);
  2076. checkQuitPreventFinished();
  2077. }
  2078. }).fail([=](const MTP::Error &error, const MTP::Response &response) {
  2079. const auto requestId = response.requestId;
  2080. history->finishSavingCloudDraft(
  2081. topicRootId,
  2082. UnixtimeFromMsgId(response.outerMsgId));
  2083. if (const auto cloudDraft = history->cloudDraft(topicRootId)) {
  2084. if (cloudDraft->saveRequestId == requestId) {
  2085. history->clearCloudDraft(topicRootId);
  2086. }
  2087. }
  2088. const auto i = _draftsSaveRequestIds.find(weak);
  2089. if (i != _draftsSaveRequestIds.cend()
  2090. && i->second == requestId) {
  2091. _draftsSaveRequestIds.erase(i);
  2092. checkQuitPreventFinished();
  2093. }
  2094. }).send();
  2095. i->second = cloudDraft->saveRequestId;
  2096. ++i;
  2097. }
  2098. }
  2099. bool ApiWrap::isQuitPrevent() {
  2100. if (_draftsSaveRequestIds.empty()) {
  2101. return false;
  2102. }
  2103. LOG(("ApiWrap prevents quit, saving drafts..."));
  2104. saveDraftsToCloud();
  2105. return true;
  2106. }
  2107. void ApiWrap::checkQuitPreventFinished() {
  2108. if (_draftsSaveRequestIds.empty()) {
  2109. if (Core::Quitting()) {
  2110. LOG(("ApiWrap doesn't prevent quit any more."));
  2111. }
  2112. Core::App().quitPreventFinished();
  2113. }
  2114. }
  2115. void ApiWrap::registerModifyRequest(
  2116. const QString &key,
  2117. mtpRequestId requestId) {
  2118. const auto i = _modifyRequests.find(key);
  2119. if (i != end(_modifyRequests)) {
  2120. request(i->second).cancel();
  2121. i->second = requestId;
  2122. } else {
  2123. _modifyRequests.emplace(key, requestId);
  2124. }
  2125. }
  2126. void ApiWrap::clearModifyRequest(const QString &key) {
  2127. _modifyRequests.remove(key);
  2128. }
  2129. void ApiWrap::gotStickerSet(
  2130. uint64 setId,
  2131. const MTPmessages_StickerSet &result) {
  2132. _stickerSetRequests.remove(setId);
  2133. result.match([&](const MTPDmessages_stickerSet &data) {
  2134. _session->data().stickers().feedSetFull(data);
  2135. }, [](const MTPDmessages_stickerSetNotModified &) {
  2136. LOG(("API Error: Unexpected messages.stickerSetNotModified."));
  2137. });
  2138. }
  2139. void ApiWrap::requestWebPageDelayed(not_null<WebPageData*> page) {
  2140. if (page->failed || !page->pendingTill) {
  2141. return;
  2142. }
  2143. _webPagesPending.emplace(page, 0);
  2144. auto left = (page->pendingTill - base::unixtime::now()) * 1000;
  2145. if (!_webPagesTimer.isActive() || left <= _webPagesTimer.remainingTime()) {
  2146. _webPagesTimer.callOnce((left < 0 ? 0 : left) + 1);
  2147. }
  2148. }
  2149. void ApiWrap::clearWebPageRequest(not_null<WebPageData*> page) {
  2150. _webPagesPending.remove(page);
  2151. if (_webPagesPending.empty() && _webPagesTimer.isActive()) {
  2152. _webPagesTimer.cancel();
  2153. }
  2154. }
  2155. void ApiWrap::clearWebPageRequests() {
  2156. _webPagesPending.clear();
  2157. _webPagesTimer.cancel();
  2158. }
  2159. void ApiWrap::resolveWebPages() {
  2160. auto ids = QVector<MTPInputMessage>(); // temp_req_id = -1
  2161. using IndexAndMessageIds = QPair<int32, QVector<MTPInputMessage>>;
  2162. using MessageIdsByChannel = base::flat_map<ChannelData*, IndexAndMessageIds>;
  2163. MessageIdsByChannel idsByChannel; // temp_req_id = -index - 2
  2164. ids.reserve(_webPagesPending.size());
  2165. int32 t = base::unixtime::now(), m = INT_MAX;
  2166. for (auto &[page, requestId] : _webPagesPending) {
  2167. if (requestId > 0) {
  2168. continue;
  2169. }
  2170. if (page->pendingTill <= t) {
  2171. if (const auto item = _session->data().findWebPageItem(page)) {
  2172. if (const auto channel = item->history()->peer->asChannel()) {
  2173. auto channelMap = idsByChannel.find(channel);
  2174. if (channelMap == idsByChannel.cend()) {
  2175. channelMap = idsByChannel.emplace(
  2176. channel,
  2177. IndexAndMessageIds(
  2178. idsByChannel.size(),
  2179. QVector<MTPInputMessage>(
  2180. 1,
  2181. MTP_inputMessageID(MTP_int(item->id))))).first;
  2182. } else {
  2183. channelMap->second.second.push_back(
  2184. MTP_inputMessageID(MTP_int(item->id)));
  2185. }
  2186. requestId = -channelMap->second.first - 2;
  2187. } else {
  2188. ids.push_back(MTP_inputMessageID(MTP_int(item->id)));
  2189. requestId = -1;
  2190. }
  2191. }
  2192. } else {
  2193. m = std::min(m, page->pendingTill - t);
  2194. }
  2195. }
  2196. auto requestId = mtpRequestId(0);
  2197. if (!ids.isEmpty()) {
  2198. requestId = request(MTPmessages_GetMessages(
  2199. MTP_vector<MTPInputMessage>(ids)
  2200. )).done([=](
  2201. const MTPmessages_Messages &result,
  2202. mtpRequestId requestId) {
  2203. gotWebPages(nullptr, result, requestId);
  2204. }).afterDelay(kSmallDelayMs).send();
  2205. }
  2206. QVector<mtpRequestId> reqsByIndex(idsByChannel.size(), 0);
  2207. for (auto i = idsByChannel.cbegin(), e = idsByChannel.cend(); i != e; ++i) {
  2208. reqsByIndex[i->second.first] = request(MTPchannels_GetMessages(
  2209. i->first->inputChannel,
  2210. MTP_vector<MTPInputMessage>(i->second.second)
  2211. )).done([=, channel = i->first](
  2212. const MTPmessages_Messages &result,
  2213. mtpRequestId requestId) {
  2214. gotWebPages(channel, result, requestId);
  2215. }).afterDelay(kSmallDelayMs).send();
  2216. }
  2217. if (requestId || !reqsByIndex.isEmpty()) {
  2218. for (auto &[page, pendingRequestId] : _webPagesPending) {
  2219. if (pendingRequestId > 0) {
  2220. continue;
  2221. } else if (pendingRequestId < 0) {
  2222. if (pendingRequestId == -1) {
  2223. pendingRequestId = requestId;
  2224. } else {
  2225. pendingRequestId = reqsByIndex[-pendingRequestId - 2];
  2226. }
  2227. }
  2228. }
  2229. }
  2230. if (m < INT_MAX) {
  2231. _webPagesTimer.callOnce(std::min(m, 86400) * crl::time(1000));
  2232. }
  2233. }
  2234. template <typename Request>
  2235. void ApiWrap::requestFileReference(
  2236. Data::FileOrigin origin,
  2237. FileReferencesHandler &&handler,
  2238. Request &&data) {
  2239. const auto i = _fileReferenceHandlers.find(origin);
  2240. if (i != end(_fileReferenceHandlers)) {
  2241. i->second.push_back(std::move(handler));
  2242. return;
  2243. }
  2244. auto handlers = std::vector<FileReferencesHandler>();
  2245. handlers.push_back(std::move(handler));
  2246. _fileReferenceHandlers.emplace(origin, std::move(handlers));
  2247. request(std::move(data)).done([=](const auto &result) {
  2248. const auto parsed = Data::GetFileReferences(result);
  2249. for (const auto &p : parsed.data) {
  2250. // Unpack here the parsed pair by hand to workaround a GCC bug.
  2251. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87122
  2252. const auto &origin = p.first;
  2253. const auto &reference = p.second;
  2254. const auto documentId = std::get_if<DocumentFileLocationId>(
  2255. &origin);
  2256. if (documentId) {
  2257. _session->data().document(
  2258. documentId->id
  2259. )->refreshFileReference(reference);
  2260. }
  2261. const auto photoId = std::get_if<PhotoFileLocationId>(&origin);
  2262. if (photoId) {
  2263. _session->data().photo(
  2264. photoId->id
  2265. )->refreshFileReference(reference);
  2266. }
  2267. }
  2268. const auto i = _fileReferenceHandlers.find(origin);
  2269. Assert(i != end(_fileReferenceHandlers));
  2270. auto handlers = std::move(i->second);
  2271. _fileReferenceHandlers.erase(i);
  2272. for (auto &handler : handlers) {
  2273. handler(parsed);
  2274. }
  2275. }).fail([=] {
  2276. const auto i = _fileReferenceHandlers.find(origin);
  2277. Assert(i != end(_fileReferenceHandlers));
  2278. auto handlers = std::move(i->second);
  2279. _fileReferenceHandlers.erase(i);
  2280. for (auto &handler : handlers) {
  2281. handler(UpdatedFileReferences());
  2282. }
  2283. }).send();
  2284. }
  2285. void ApiWrap::refreshFileReference(
  2286. Data::FileOrigin origin,
  2287. not_null<Storage::DownloadMtprotoTask*> task,
  2288. int requestId,
  2289. const QByteArray &current) {
  2290. return refreshFileReference(origin, crl::guard(task, [=](
  2291. const UpdatedFileReferences &data) {
  2292. task->refreshFileReferenceFrom(data, requestId, current);
  2293. }));
  2294. }
  2295. void ApiWrap::refreshFileReference(
  2296. Data::FileOrigin origin,
  2297. FileReferencesHandler &&handler) {
  2298. const auto fail = [&] {
  2299. handler(UpdatedFileReferences());
  2300. };
  2301. const auto request = [&](
  2302. auto &&data,
  2303. Fn<void()> &&additional = nullptr) {
  2304. requestFileReference(
  2305. origin,
  2306. std::move(handler),
  2307. std::move(data));
  2308. if (additional) {
  2309. const auto i = _fileReferenceHandlers.find(origin);
  2310. Assert(i != end(_fileReferenceHandlers));
  2311. if (i->second.size() == 1) {
  2312. i->second.push_back([=](auto&&) {
  2313. additional();
  2314. });
  2315. }
  2316. }
  2317. };
  2318. v::match(origin.data, [&](Data::FileOriginMessage data) {
  2319. if (const auto item = _session->data().message(data)) {
  2320. const auto media = item->media();
  2321. const auto storyId = media ? media->storyId() : FullStoryId();
  2322. if (storyId) {
  2323. request(MTPstories_GetStoriesByID(
  2324. _session->data().peer(storyId.peer)->input,
  2325. MTP_vector<MTPint>(1, MTP_int(storyId.story))));
  2326. } else if (item->isScheduled()) {
  2327. const auto realId = _session->scheduledMessages().lookupId(
  2328. item);
  2329. request(MTPmessages_GetScheduledMessages(
  2330. item->history()->peer->input,
  2331. MTP_vector<MTPint>(1, MTP_int(realId))));
  2332. } else if (item->isBusinessShortcut()) {
  2333. const auto &shortcuts = _session->data().shortcutMessages();
  2334. const auto realId = shortcuts.lookupId(item);
  2335. request(MTPmessages_GetQuickReplyMessages(
  2336. MTP_flags(MTPmessages_GetQuickReplyMessages::Flag::f_id),
  2337. MTP_int(item->shortcutId()),
  2338. MTP_vector<MTPint>(1, MTP_int(realId)),
  2339. MTP_long(0)));
  2340. } else if (const auto channel = item->history()->peer->asChannel()) {
  2341. request(MTPchannels_GetMessages(
  2342. channel->inputChannel,
  2343. MTP_vector<MTPInputMessage>(
  2344. 1,
  2345. MTP_inputMessageID(MTP_int(item->id)))));
  2346. } else {
  2347. request(MTPmessages_GetMessages(
  2348. MTP_vector<MTPInputMessage>(
  2349. 1,
  2350. MTP_inputMessageID(MTP_int(item->id)))));
  2351. }
  2352. } else {
  2353. fail();
  2354. }
  2355. }, [&](Data::FileOriginUserPhoto data) {
  2356. if (const auto user = _session->data().user(data.userId)) {
  2357. request(MTPphotos_GetUserPhotos(
  2358. user->inputUser,
  2359. MTP_int(-1),
  2360. MTP_long(data.photoId),
  2361. MTP_int(1)));
  2362. } else {
  2363. fail();
  2364. }
  2365. }, [&](Data::FileOriginFullUser data) {
  2366. if (const auto user = _session->data().user(data.userId)) {
  2367. request(MTPusers_GetFullUser(user->inputUser));
  2368. } else {
  2369. fail();
  2370. }
  2371. }, [&](Data::FileOriginPeerPhoto data) {
  2372. fail();
  2373. }, [&](Data::FileOriginStickerSet data) {
  2374. const auto isRecentAttached
  2375. = (data.setId == Data::Stickers::CloudRecentAttachedSetId);
  2376. if (data.setId == Data::Stickers::CloudRecentSetId
  2377. || data.setId == Data::Stickers::RecentSetId
  2378. || isRecentAttached) {
  2379. auto done = [=] { crl::on_main(_session, [=] {
  2380. if (isRecentAttached) {
  2381. local().writeRecentMasks();
  2382. } else {
  2383. local().writeRecentStickers();
  2384. }
  2385. }); };
  2386. request(MTPmessages_GetRecentStickers(
  2387. MTP_flags(isRecentAttached
  2388. ? MTPmessages_GetRecentStickers::Flag::f_attached
  2389. : MTPmessages_GetRecentStickers::Flags(0)),
  2390. MTP_long(0)),
  2391. std::move(done));
  2392. } else if (data.setId == Data::Stickers::FavedSetId) {
  2393. request(MTPmessages_GetFavedStickers(MTP_long(0)),
  2394. [=] { crl::on_main(_session, [=] { local().writeFavedStickers(); }); });
  2395. } else {
  2396. request(MTPmessages_GetStickerSet(
  2397. MTP_inputStickerSetID(
  2398. MTP_long(data.setId),
  2399. MTP_long(data.accessHash)),
  2400. MTP_int(0)), // hash
  2401. [=] { crl::on_main(_session, [=] {
  2402. local().writeInstalledStickers();
  2403. local().writeRecentStickers();
  2404. local().writeFavedStickers();
  2405. }); });
  2406. }
  2407. }, [&](Data::FileOriginSavedGifs data) {
  2408. request(
  2409. MTPmessages_GetSavedGifs(MTP_long(0)),
  2410. [=] { crl::on_main(_session, [=] { local().writeSavedGifs(); }); });
  2411. }, [&](Data::FileOriginWallpaper data) {
  2412. const auto useSlug = data.ownerId
  2413. && (data.ownerId != session().userId())
  2414. && !data.slug.isEmpty();
  2415. request(MTPaccount_GetWallPaper(useSlug
  2416. ? MTP_inputWallPaperSlug(MTP_string(data.slug))
  2417. : MTP_inputWallPaper(
  2418. MTP_long(data.paperId),
  2419. MTP_long(data.accessHash))));
  2420. }, [&](Data::FileOriginTheme data) {
  2421. request(MTPaccount_GetTheme(
  2422. MTP_string(Data::CloudThemes::Format()),
  2423. MTP_inputTheme(
  2424. MTP_long(data.themeId),
  2425. MTP_long(data.accessHash))));
  2426. }, [&](Data::FileOriginRingtones data) {
  2427. request(MTPaccount_GetSavedRingtones(MTP_long(0)));
  2428. }, [&](Data::FileOriginPremiumPreviews data) {
  2429. request(MTPhelp_GetPremiumPromo());
  2430. }, [&](Data::FileOriginWebPage data) {
  2431. request(MTPmessages_GetWebPage(
  2432. MTP_string(data.url),
  2433. MTP_int(0)));
  2434. }, [&](Data::FileOriginStory data) {
  2435. request(MTPstories_GetStoriesByID(
  2436. _session->data().peer(data.peer)->input,
  2437. MTP_vector<MTPint>(1, MTP_int(data.story))));
  2438. }, [&](v::null_t) {
  2439. fail();
  2440. });
  2441. }
  2442. void ApiWrap::gotWebPages(ChannelData *channel, const MTPmessages_Messages &result, mtpRequestId req) {
  2443. WebPageData::ApplyChanges(_session, channel, result);
  2444. for (auto i = _webPagesPending.begin(); i != _webPagesPending.cend();) {
  2445. if (i->second == req) {
  2446. if (i->first->pendingTill > 0) {
  2447. i->first->pendingTill = 0;
  2448. i->first->failed = 1;
  2449. _session->data().notifyWebPageUpdateDelayed(i->first);
  2450. }
  2451. i = _webPagesPending.erase(i);
  2452. } else {
  2453. ++i;
  2454. }
  2455. }
  2456. _session->data().sendWebPageGamePollNotifications();
  2457. }
  2458. void ApiWrap::updateStickers() {
  2459. const auto now = crl::now();
  2460. requestStickers(now);
  2461. requestRecentStickers(now, false);
  2462. requestFavedStickers(now);
  2463. requestFeaturedStickers(now);
  2464. }
  2465. void ApiWrap::updateSavedGifs() {
  2466. const auto now = crl::now();
  2467. requestSavedGifs(now);
  2468. }
  2469. void ApiWrap::updateMasks() {
  2470. const auto now = crl::now();
  2471. requestMasks(now);
  2472. requestRecentStickers(now, true);
  2473. }
  2474. void ApiWrap::updateCustomEmoji() {
  2475. const auto now = crl::now();
  2476. requestCustomEmoji(now);
  2477. requestFeaturedEmoji(now);
  2478. }
  2479. void ApiWrap::requestSpecialStickersForce(
  2480. bool faved,
  2481. bool recent,
  2482. bool attached) {
  2483. if (faved) {
  2484. requestFavedStickers(std::nullopt);
  2485. } else if (recent || attached) {
  2486. requestRecentStickers(std::nullopt, attached);
  2487. }
  2488. }
  2489. void ApiWrap::setGroupStickerSet(
  2490. not_null<ChannelData*> megagroup,
  2491. const StickerSetIdentifier &set) {
  2492. Expects(megagroup->mgInfo != nullptr);
  2493. megagroup->mgInfo->stickerSet = set;
  2494. request(MTPchannels_SetStickers(
  2495. megagroup->inputChannel,
  2496. Data::InputStickerSet(set)
  2497. )).send();
  2498. _session->data().stickers().notifyUpdated(Data::StickersType::Stickers);
  2499. }
  2500. void ApiWrap::setGroupEmojiSet(
  2501. not_null<ChannelData*> megagroup,
  2502. const StickerSetIdentifier &set) {
  2503. Expects(megagroup->mgInfo != nullptr);
  2504. megagroup->mgInfo->emojiSet = set;
  2505. request(MTPchannels_SetEmojiStickers(
  2506. megagroup->inputChannel,
  2507. Data::InputStickerSet(set)
  2508. )).send();
  2509. _session->changes().peerUpdated(
  2510. megagroup,
  2511. Data::PeerUpdate::Flag::EmojiSet);
  2512. _session->data().stickers().notifyUpdated(Data::StickersType::Emoji);
  2513. }
  2514. std::vector<not_null<DocumentData*>> *ApiWrap::stickersByEmoji(
  2515. const QString &key) {
  2516. const auto it = _stickersByEmoji.find(key);
  2517. const auto sendRequest = [&] {
  2518. if (it == _stickersByEmoji.end()) {
  2519. return true;
  2520. }
  2521. const auto received = it->second.received;
  2522. const auto now = crl::now();
  2523. return (received > 0)
  2524. && (received + kStickersByEmojiInvalidateTimeout) <= now;
  2525. }();
  2526. if (sendRequest) {
  2527. const auto hash = (it != _stickersByEmoji.end())
  2528. ? it->second.hash
  2529. : uint64(0);
  2530. request(MTPmessages_GetStickers(
  2531. MTP_string(key),
  2532. MTP_long(hash)
  2533. )).done([=](const MTPmessages_Stickers &result) {
  2534. if (result.type() == mtpc_messages_stickersNotModified) {
  2535. return;
  2536. }
  2537. Assert(result.type() == mtpc_messages_stickers);
  2538. const auto &data = result.c_messages_stickers();
  2539. auto &entry = _stickersByEmoji[key];
  2540. entry.list.clear();
  2541. entry.list.reserve(data.vstickers().v.size());
  2542. for (const auto &sticker : data.vstickers().v) {
  2543. const auto document = _session->data().processDocument(
  2544. sticker);
  2545. if (document->sticker()) {
  2546. entry.list.push_back(document);
  2547. }
  2548. }
  2549. entry.hash = data.vhash().v;
  2550. entry.received = crl::now();
  2551. _session->data().stickers().notifyUpdated(
  2552. Data::StickersType::Stickers);
  2553. }).send();
  2554. }
  2555. if (it == _stickersByEmoji.end()) {
  2556. _stickersByEmoji.emplace(key, StickersByEmoji());
  2557. } else if (it->second.received > 0) {
  2558. return &it->second.list;
  2559. }
  2560. return nullptr;
  2561. }
  2562. void ApiWrap::requestStickers(TimeId now) {
  2563. if (!_session->data().stickers().updateNeeded(now)
  2564. || _stickersUpdateRequest) {
  2565. return;
  2566. }
  2567. const auto done = [=](const MTPmessages_AllStickers &result) {
  2568. _session->data().stickers().setLastUpdate(crl::now());
  2569. _stickersUpdateRequest = 0;
  2570. result.match([&](const MTPDmessages_allStickersNotModified&) {
  2571. }, [&](const MTPDmessages_allStickers &data) {
  2572. _session->data().stickers().setsReceived(
  2573. data.vsets().v,
  2574. data.vhash().v);
  2575. });
  2576. };
  2577. _stickersUpdateRequest = request(MTPmessages_GetAllStickers(
  2578. MTP_long(Api::CountStickersHash(_session, true))
  2579. )).done(done).fail([=] {
  2580. LOG(("App Fail: Failed to get stickers!"));
  2581. done(MTP_messages_allStickersNotModified());
  2582. }).send();
  2583. }
  2584. void ApiWrap::requestMasks(TimeId now) {
  2585. if (!_session->data().stickers().masksUpdateNeeded(now)
  2586. || _masksUpdateRequest) {
  2587. return;
  2588. }
  2589. const auto done = [=](const MTPmessages_AllStickers &result) {
  2590. _session->data().stickers().setLastMasksUpdate(crl::now());
  2591. _masksUpdateRequest = 0;
  2592. result.match([&](const MTPDmessages_allStickersNotModified&) {
  2593. }, [&](const MTPDmessages_allStickers &data) {
  2594. _session->data().stickers().masksReceived(
  2595. data.vsets().v,
  2596. data.vhash().v);
  2597. });
  2598. };
  2599. _masksUpdateRequest = request(MTPmessages_GetMaskStickers(
  2600. MTP_long(Api::CountMasksHash(_session, true))
  2601. )).done(done).fail([=] {
  2602. LOG(("App Fail: Failed to get masks!"));
  2603. done(MTP_messages_allStickersNotModified());
  2604. }).send();
  2605. }
  2606. void ApiWrap::requestCustomEmoji(TimeId now) {
  2607. if (!_session->data().stickers().emojiUpdateNeeded(now)
  2608. || _customEmojiUpdateRequest) {
  2609. return;
  2610. }
  2611. const auto done = [=](const MTPmessages_AllStickers &result) {
  2612. _session->data().stickers().setLastEmojiUpdate(crl::now());
  2613. _customEmojiUpdateRequest = 0;
  2614. result.match([&](const MTPDmessages_allStickersNotModified&) {
  2615. }, [&](const MTPDmessages_allStickers &data) {
  2616. _session->data().stickers().emojiReceived(
  2617. data.vsets().v,
  2618. data.vhash().v);
  2619. });
  2620. };
  2621. _customEmojiUpdateRequest = request(MTPmessages_GetEmojiStickers(
  2622. MTP_long(Api::CountCustomEmojiHash(_session, true))
  2623. )).done(done).fail([=] {
  2624. LOG(("App Fail: Failed to get custom emoji!"));
  2625. done(MTP_messages_allStickersNotModified());
  2626. }).send();
  2627. }
  2628. void ApiWrap::requestRecentStickers(
  2629. std::optional<TimeId> now,
  2630. bool attached) {
  2631. const auto needed = !now
  2632. ? true
  2633. : attached
  2634. ? _session->data().stickers().recentAttachedUpdateNeeded(*now)
  2635. : _session->data().stickers().recentUpdateNeeded(*now);
  2636. if (!needed) {
  2637. return;
  2638. }
  2639. const auto requestId = [=]() -> mtpRequestId & {
  2640. return attached
  2641. ? _recentAttachedStickersUpdateRequest
  2642. : _recentStickersUpdateRequest;
  2643. };
  2644. if (requestId()) {
  2645. return;
  2646. }
  2647. const auto finish = [=] {
  2648. auto &stickers = _session->data().stickers();
  2649. if (attached) {
  2650. stickers.setLastRecentAttachedUpdate(crl::now());
  2651. } else {
  2652. stickers.setLastRecentUpdate(crl::now());
  2653. }
  2654. requestId() = 0;
  2655. };
  2656. const auto flags = attached
  2657. ? MTPmessages_getRecentStickers::Flag::f_attached
  2658. : MTPmessages_getRecentStickers::Flags(0);
  2659. requestId() = request(MTPmessages_GetRecentStickers(
  2660. MTP_flags(flags),
  2661. MTP_long(now ? Api::CountRecentStickersHash(_session, attached) : 0)
  2662. )).done([=](const MTPmessages_RecentStickers &result) {
  2663. finish();
  2664. switch (result.type()) {
  2665. case mtpc_messages_recentStickersNotModified: return;
  2666. case mtpc_messages_recentStickers: {
  2667. auto &d = result.c_messages_recentStickers();
  2668. _session->data().stickers().specialSetReceived(
  2669. attached
  2670. ? Data::Stickers::CloudRecentAttachedSetId
  2671. : Data::Stickers::CloudRecentSetId,
  2672. tr::lng_recent_stickers(tr::now),
  2673. d.vstickers().v,
  2674. d.vhash().v,
  2675. d.vpacks().v,
  2676. d.vdates().v);
  2677. } return;
  2678. default: Unexpected("Type in ApiWrap::recentStickersDone()");
  2679. }
  2680. }).fail([=] {
  2681. finish();
  2682. LOG(("App Fail: Failed to get recent stickers!"));
  2683. }).send();
  2684. }
  2685. void ApiWrap::requestFavedStickers(std::optional<TimeId> now) {
  2686. if (now) {
  2687. if (!_session->data().stickers().favedUpdateNeeded(*now)
  2688. || _favedStickersUpdateRequest) {
  2689. return;
  2690. }
  2691. }
  2692. _favedStickersUpdateRequest = request(MTPmessages_GetFavedStickers(
  2693. MTP_long(now ? Api::CountFavedStickersHash(_session) : 0)
  2694. )).done([=](const MTPmessages_FavedStickers &result) {
  2695. _session->data().stickers().setLastFavedUpdate(crl::now());
  2696. _favedStickersUpdateRequest = 0;
  2697. switch (result.type()) {
  2698. case mtpc_messages_favedStickersNotModified: return;
  2699. case mtpc_messages_favedStickers: {
  2700. auto &d = result.c_messages_favedStickers();
  2701. _session->data().stickers().specialSetReceived(
  2702. Data::Stickers::FavedSetId,
  2703. Lang::Hard::FavedSetTitle(),
  2704. d.vstickers().v,
  2705. d.vhash().v,
  2706. d.vpacks().v);
  2707. } return;
  2708. default: Unexpected("Type in ApiWrap::favedStickersDone()");
  2709. }
  2710. }).fail([=] {
  2711. _session->data().stickers().setLastFavedUpdate(crl::now());
  2712. _favedStickersUpdateRequest = 0;
  2713. LOG(("App Fail: Failed to get faved stickers!"));
  2714. }).send();
  2715. }
  2716. void ApiWrap::requestFeaturedStickers(TimeId now) {
  2717. if (!_session->data().stickers().featuredUpdateNeeded(now)
  2718. || _featuredStickersUpdateRequest) {
  2719. return;
  2720. }
  2721. _featuredStickersUpdateRequest = request(MTPmessages_GetFeaturedStickers(
  2722. MTP_long(Api::CountFeaturedStickersHash(_session))
  2723. )).done([=](const MTPmessages_FeaturedStickers &result) {
  2724. _featuredStickersUpdateRequest = 0;
  2725. _session->data().stickers().featuredSetsReceived(result);
  2726. }).fail([=] {
  2727. _featuredStickersUpdateRequest = 0;
  2728. _session->data().stickers().setLastFeaturedUpdate(crl::now());
  2729. LOG(("App Fail: Failed to get featured stickers!"));
  2730. }).send();
  2731. }
  2732. void ApiWrap::requestFeaturedEmoji(TimeId now) {
  2733. if (!_session->data().stickers().featuredEmojiUpdateNeeded(now)
  2734. || _featuredEmojiUpdateRequest) {
  2735. return;
  2736. }
  2737. _featuredEmojiUpdateRequest = request(
  2738. MTPmessages_GetFeaturedEmojiStickers(
  2739. MTP_long(Api::CountFeaturedStickersHash(_session)))
  2740. ).done([=](const MTPmessages_FeaturedStickers &result) {
  2741. _featuredEmojiUpdateRequest = 0;
  2742. _session->data().stickers().featuredEmojiSetsReceived(result);
  2743. }).fail([=] {
  2744. _featuredEmojiUpdateRequest = 0;
  2745. _session->data().stickers().setLastFeaturedEmojiUpdate(crl::now());
  2746. LOG(("App Fail: Failed to get featured emoji!"));
  2747. }).send();
  2748. }
  2749. void ApiWrap::requestSavedGifs(TimeId now) {
  2750. if (!_session->data().stickers().savedGifsUpdateNeeded(now)
  2751. || _savedGifsUpdateRequest) {
  2752. return;
  2753. }
  2754. _savedGifsUpdateRequest = request(MTPmessages_GetSavedGifs(
  2755. MTP_long(Api::CountSavedGifsHash(_session))
  2756. )).done([=](const MTPmessages_SavedGifs &result) {
  2757. _session->data().stickers().setLastSavedGifsUpdate(crl::now());
  2758. _savedGifsUpdateRequest = 0;
  2759. switch (result.type()) {
  2760. case mtpc_messages_savedGifsNotModified: return;
  2761. case mtpc_messages_savedGifs: {
  2762. auto &d = result.c_messages_savedGifs();
  2763. _session->data().stickers().gifsReceived(
  2764. d.vgifs().v,
  2765. d.vhash().v);
  2766. } return;
  2767. default: Unexpected("Type in ApiWrap::savedGifsDone()");
  2768. }
  2769. }).fail([=] {
  2770. _session->data().stickers().setLastSavedGifsUpdate(crl::now());
  2771. _savedGifsUpdateRequest = 0;
  2772. LOG(("App Fail: Failed to get saved gifs!"));
  2773. }).send();
  2774. }
  2775. void ApiWrap::readFeaturedSetDelayed(uint64 setId) {
  2776. if (!_featuredSetsRead.contains(setId)) {
  2777. _featuredSetsRead.insert(setId);
  2778. _featuredSetsReadTimer.callOnce(kReadFeaturedSetsTimeout);
  2779. }
  2780. }
  2781. void ApiWrap::readFeaturedSets() {
  2782. const auto &sets = _session->data().stickers().sets();
  2783. auto count = _session->data().stickers().featuredSetsUnreadCount();
  2784. QVector<MTPlong> wrappedIds;
  2785. wrappedIds.reserve(_featuredSetsRead.size());
  2786. for (const auto setId : _featuredSetsRead) {
  2787. const auto it = sets.find(setId);
  2788. if (it != sets.cend()) {
  2789. it->second->flags &= ~Data::StickersSetFlag::Unread;
  2790. wrappedIds.append(MTP_long(setId));
  2791. if (count) {
  2792. --count;
  2793. }
  2794. }
  2795. }
  2796. _featuredSetsRead.clear();
  2797. if (!wrappedIds.empty()) {
  2798. auto requestData = MTPmessages_ReadFeaturedStickers(
  2799. MTP_vector<MTPlong>(wrappedIds));
  2800. request(std::move(requestData)).done([=] {
  2801. local().writeFeaturedStickers();
  2802. _session->data().stickers().notifyUpdated(
  2803. Data::StickersType::Stickers);
  2804. }).send();
  2805. _session->data().stickers().setFeaturedSetsUnreadCount(count);
  2806. }
  2807. }
  2808. void ApiWrap::resolveJumpToDate(
  2809. Dialogs::Key chat,
  2810. const QDate &date,
  2811. Fn<void(not_null<PeerData*>, MsgId)> callback) {
  2812. if (const auto peer = chat.peer()) {
  2813. const auto topic = chat.topic();
  2814. const auto rootId = topic ? topic->rootId() : 0;
  2815. resolveJumpToHistoryDate(peer, rootId, date, std::move(callback));
  2816. }
  2817. }
  2818. template <typename Callback>
  2819. void ApiWrap::requestMessageAfterDate(
  2820. not_null<PeerData*> peer,
  2821. MsgId topicRootId,
  2822. const QDate &date,
  2823. Callback &&callback) {
  2824. // API returns a message with date <= offset_date.
  2825. // So we request a message with offset_date = desired_date - 1 and add_offset = -1.
  2826. // This should give us the first message with date >= desired_date.
  2827. const auto offsetId = 0;
  2828. const auto offsetDate = static_cast<int>(date.startOfDay().toSecsSinceEpoch()) - 1;
  2829. const auto addOffset = -1;
  2830. const auto limit = 1;
  2831. const auto maxId = 0;
  2832. const auto minId = 0;
  2833. const auto historyHash = uint64(0);
  2834. auto send = [&](auto &&serialized) {
  2835. request(std::move(serialized)).done([
  2836. =,
  2837. callback = std::forward<Callback>(callback)
  2838. ](const MTPmessages_Messages &result) {
  2839. const auto handleMessages = [&](auto &messages) {
  2840. _session->data().processUsers(messages.vusers());
  2841. _session->data().processChats(messages.vchats());
  2842. return &messages.vmessages().v;
  2843. };
  2844. const auto list = result.match([&](
  2845. const MTPDmessages_messages &data) {
  2846. return handleMessages(data);
  2847. }, [&](const MTPDmessages_messagesSlice &data) {
  2848. return handleMessages(data);
  2849. }, [&](const MTPDmessages_channelMessages &data) {
  2850. if (const auto channel = peer->asChannel()) {
  2851. channel->ptsReceived(data.vpts().v);
  2852. channel->processTopics(data.vtopics());
  2853. } else {
  2854. LOG(("API Error: received messages.channelMessages when "
  2855. "no channel was passed! (ApiWrap::jumpToDate)"));
  2856. }
  2857. return handleMessages(data);
  2858. }, [&](const MTPDmessages_messagesNotModified &) {
  2859. LOG(("API Error: received messages.messagesNotModified! "
  2860. "(ApiWrap::jumpToDate)"));
  2861. return (const QVector<MTPMessage>*)nullptr;
  2862. });
  2863. if (list) {
  2864. _session->data().processMessages(
  2865. *list,
  2866. NewMessageType::Existing);
  2867. for (const auto &message : *list) {
  2868. if (DateFromMessage(message) >= offsetDate) {
  2869. callback(IdFromMessage(message));
  2870. return;
  2871. }
  2872. }
  2873. }
  2874. callback(ShowAtUnreadMsgId);
  2875. }).send();
  2876. };
  2877. if (topicRootId) {
  2878. send(MTPmessages_GetReplies(
  2879. peer->input,
  2880. MTP_int(topicRootId),
  2881. MTP_int(offsetId),
  2882. MTP_int(offsetDate),
  2883. MTP_int(addOffset),
  2884. MTP_int(limit),
  2885. MTP_int(maxId),
  2886. MTP_int(minId),
  2887. MTP_long(historyHash)));
  2888. } else {
  2889. send(MTPmessages_GetHistory(
  2890. peer->input,
  2891. MTP_int(offsetId),
  2892. MTP_int(offsetDate),
  2893. MTP_int(addOffset),
  2894. MTP_int(limit),
  2895. MTP_int(maxId),
  2896. MTP_int(minId),
  2897. MTP_long(historyHash)));
  2898. }
  2899. }
  2900. void ApiWrap::resolveJumpToHistoryDate(
  2901. not_null<PeerData*> peer,
  2902. MsgId topicRootId,
  2903. const QDate &date,
  2904. Fn<void(not_null<PeerData*>, MsgId)> callback) {
  2905. if (const auto channel = peer->migrateTo()) {
  2906. return resolveJumpToHistoryDate(
  2907. channel,
  2908. topicRootId,
  2909. date,
  2910. std::move(callback));
  2911. }
  2912. const auto jumpToDateInPeer = [=] {
  2913. requestMessageAfterDate(peer, topicRootId, date, [=](MsgId itemId) {
  2914. callback(peer, itemId);
  2915. });
  2916. };
  2917. if (const auto chat = topicRootId ? nullptr : peer->migrateFrom()) {
  2918. requestMessageAfterDate(chat, 0, date, [=](MsgId itemId) {
  2919. if (itemId) {
  2920. callback(chat, itemId);
  2921. } else {
  2922. jumpToDateInPeer();
  2923. }
  2924. });
  2925. } else {
  2926. jumpToDateInPeer();
  2927. }
  2928. }
  2929. void ApiWrap::requestHistory(
  2930. not_null<History*> history,
  2931. MsgId messageId,
  2932. SliceType slice) {
  2933. const auto peer = history->peer;
  2934. const auto key = HistoryRequest{
  2935. peer,
  2936. messageId,
  2937. slice,
  2938. };
  2939. if (_historyRequests.contains(key)) {
  2940. return;
  2941. }
  2942. const auto prepared = Api::PrepareHistoryRequest(peer, messageId, slice);
  2943. auto &histories = history->owner().histories();
  2944. const auto requestType = Data::Histories::RequestType::History;
  2945. histories.sendRequest(history, requestType, [=](Fn<void()> finish) {
  2946. return request(
  2947. std::move(prepared)
  2948. ).done([=](const Api::HistoryRequestResult &result) {
  2949. _historyRequests.remove(key);
  2950. auto parsed = Api::ParseHistoryResult(
  2951. peer,
  2952. messageId,
  2953. slice,
  2954. result);
  2955. history->messages().addSlice(
  2956. std::move(parsed.messageIds),
  2957. parsed.noSkipRange,
  2958. parsed.fullCount);
  2959. finish();
  2960. }).fail([=] {
  2961. _historyRequests.remove(key);
  2962. finish();
  2963. }).send();
  2964. });
  2965. _historyRequests.emplace(key);
  2966. }
  2967. void ApiWrap::requestSharedMedia(
  2968. not_null<PeerData*> peer,
  2969. MsgId topicRootId,
  2970. SharedMediaType type,
  2971. MsgId messageId,
  2972. SliceType slice) {
  2973. const auto key = SharedMediaRequest{
  2974. peer,
  2975. topicRootId,
  2976. type,
  2977. messageId,
  2978. slice,
  2979. };
  2980. if (_sharedMediaRequests.contains(key)) {
  2981. return;
  2982. }
  2983. const auto prepared = Api::PrepareSearchRequest(
  2984. peer,
  2985. topicRootId,
  2986. type,
  2987. QString(),
  2988. messageId,
  2989. slice);
  2990. if (!prepared) {
  2991. return;
  2992. }
  2993. const auto history = _session->data().history(peer);
  2994. auto &histories = history->owner().histories();
  2995. const auto requestType = Data::Histories::RequestType::History;
  2996. histories.sendRequest(history, requestType, [=](Fn<void()> finish) {
  2997. return request(
  2998. std::move(*prepared)
  2999. ).done([=](const Api::SearchRequestResult &result) {
  3000. _sharedMediaRequests.remove(key);
  3001. auto parsed = Api::ParseSearchResult(
  3002. peer,
  3003. type,
  3004. messageId,
  3005. slice,
  3006. result);
  3007. sharedMediaDone(peer, topicRootId, type, std::move(parsed));
  3008. finish();
  3009. }).fail([=] {
  3010. _sharedMediaRequests.remove(key);
  3011. finish();
  3012. }).send();
  3013. });
  3014. _sharedMediaRequests.emplace(key);
  3015. }
  3016. void ApiWrap::sharedMediaDone(
  3017. not_null<PeerData*> peer,
  3018. MsgId topicRootId,
  3019. SharedMediaType type,
  3020. Api::SearchResult &&parsed) {
  3021. const auto topic = peer->forumTopicFor(topicRootId);
  3022. if (topicRootId && !topic) {
  3023. return;
  3024. }
  3025. const auto hasMessages = !parsed.messageIds.empty();
  3026. _session->storage().add(Storage::SharedMediaAddSlice(
  3027. peer->id,
  3028. topicRootId,
  3029. type,
  3030. std::move(parsed.messageIds),
  3031. parsed.noSkipRange,
  3032. parsed.fullCount
  3033. ));
  3034. if (type == SharedMediaType::Pinned && hasMessages) {
  3035. peer->owner().history(peer)->setHasPinnedMessages(true);
  3036. if (topic) {
  3037. topic->setHasPinnedMessages(true);
  3038. }
  3039. }
  3040. }
  3041. mtpRequestId ApiWrap::requestGlobalMedia(
  3042. Storage::SharedMediaType type,
  3043. const QString &query,
  3044. int32 offsetRate,
  3045. Data::MessagePosition offsetPosition,
  3046. Fn<void(Api::GlobalMediaResult)> done) {
  3047. auto prepared = Api::PrepareGlobalMediaRequest(
  3048. _session,
  3049. offsetRate,
  3050. offsetPosition,
  3051. type,
  3052. query);
  3053. if (!prepared) {
  3054. done({});
  3055. return 0;
  3056. }
  3057. return request(
  3058. std::move(*prepared)
  3059. ).done([=](const Api::SearchRequestResult &result) {
  3060. done(Api::ParseGlobalMediaResult(_session, result));
  3061. }).fail([=] {
  3062. done({});
  3063. }).send();
  3064. }
  3065. void ApiWrap::sendAction(const SendAction &action) {
  3066. if (!action.options.scheduled
  3067. && !action.options.shortcutId
  3068. && !action.replaceMediaOf) {
  3069. const auto topicRootId = action.replyTo.topicRootId;
  3070. const auto topic = topicRootId
  3071. ? action.history->peer->forumTopicFor(topicRootId)
  3072. : nullptr;
  3073. if (topic) {
  3074. topic->readTillEnd();
  3075. } else {
  3076. _session->data().histories().readInbox(action.history);
  3077. }
  3078. action.history->getReadyFor(ShowAtTheEndMsgId);
  3079. }
  3080. _sendActions.fire_copy(action);
  3081. }
  3082. void ApiWrap::finishForwarding(const SendAction &action) {
  3083. const auto history = action.history;
  3084. const auto topicRootId = action.replyTo.topicRootId;
  3085. auto toForward = history->resolveForwardDraft(topicRootId);
  3086. if (!toForward.items.empty()) {
  3087. const auto error = GetErrorForSending(
  3088. history->peer,
  3089. {
  3090. .topicRootId = topicRootId,
  3091. .forward = &toForward.items,
  3092. });
  3093. if (error) {
  3094. return;
  3095. }
  3096. forwardMessages(std::move(toForward), action);
  3097. history->setForwardDraft(topicRootId, {});
  3098. }
  3099. _session->data().sendHistoryChangeNotifications();
  3100. if (!action.options.shortcutId) {
  3101. _session->changes().historyUpdated(
  3102. history,
  3103. (action.options.scheduled
  3104. ? Data::HistoryUpdate::Flag::ScheduledSent
  3105. : Data::HistoryUpdate::Flag::MessageSent));
  3106. }
  3107. }
  3108. void ApiWrap::forwardMessages(
  3109. Data::ResolvedForwardDraft &&draft,
  3110. SendAction action,
  3111. FnMut<void()> &&successCallback) {
  3112. Expects(!draft.items.empty());
  3113. auto &histories = _session->data().histories();
  3114. struct SharedCallback {
  3115. int requestsLeft = 0;
  3116. FnMut<void()> callback;
  3117. };
  3118. const auto shared = successCallback
  3119. ? std::make_shared<SharedCallback>()
  3120. : std::shared_ptr<SharedCallback>();
  3121. if (successCallback) {
  3122. shared->callback = std::move(successCallback);
  3123. }
  3124. const auto count = int(draft.items.size());
  3125. const auto genClientSideMessage = action.generateLocal
  3126. && (count < 2)
  3127. && (draft.options == Data::ForwardOptions::PreserveInfo);
  3128. const auto history = action.history;
  3129. const auto peer = history->peer;
  3130. if (!action.options.scheduled && !action.options.shortcutId) {
  3131. histories.readInbox(history);
  3132. }
  3133. const auto sendAs = action.options.sendAs;
  3134. const auto silentPost = ShouldSendSilent(peer, action.options);
  3135. using SendFlag = MTPmessages_ForwardMessages::Flag;
  3136. auto flags = MessageFlags();
  3137. auto sendFlags = SendFlag() | SendFlag();
  3138. FillMessagePostFlags(action, peer, flags);
  3139. if (silentPost) {
  3140. sendFlags |= SendFlag::f_silent;
  3141. }
  3142. if (action.options.scheduled) {
  3143. flags |= MessageFlag::IsOrWasScheduled;
  3144. sendFlags |= SendFlag::f_schedule_date;
  3145. }
  3146. if (action.options.shortcutId) {
  3147. flags |= MessageFlag::ShortcutMessage;
  3148. sendFlags |= SendFlag::f_quick_reply_shortcut;
  3149. }
  3150. if (draft.options != Data::ForwardOptions::PreserveInfo) {
  3151. sendFlags |= SendFlag::f_drop_author;
  3152. }
  3153. if (draft.options == Data::ForwardOptions::NoNamesAndCaptions) {
  3154. sendFlags |= SendFlag::f_drop_media_captions;
  3155. }
  3156. if (sendAs) {
  3157. sendFlags |= SendFlag::f_send_as;
  3158. }
  3159. const auto kGeneralId = Data::ForumTopic::kGeneralId;
  3160. const auto topicRootId = action.replyTo.topicRootId;
  3161. const auto topMsgId = (topicRootId == kGeneralId)
  3162. ? MsgId(0)
  3163. : topicRootId;
  3164. if (topMsgId) {
  3165. sendFlags |= SendFlag::f_top_msg_id;
  3166. }
  3167. auto forwardFrom = draft.items.front()->history()->peer;
  3168. auto ids = QVector<MTPint>();
  3169. auto randomIds = QVector<MTPlong>();
  3170. auto localIds = std::shared_ptr<base::flat_map<uint64, FullMsgId>>();
  3171. const auto sendAccumulated = [&] {
  3172. if (shared) {
  3173. ++shared->requestsLeft;
  3174. }
  3175. const auto requestType = Data::Histories::RequestType::Send;
  3176. const auto idsCopy = localIds;
  3177. const auto scheduled = action.options.scheduled;
  3178. const auto starsPaid = std::min(
  3179. action.options.starsApproved,
  3180. int(ids.size() * peer->starsPerMessageChecked()));
  3181. auto oneFlags = sendFlags;
  3182. if (starsPaid) {
  3183. action.options.starsApproved -= starsPaid;
  3184. oneFlags |= SendFlag::f_allow_paid_stars;
  3185. }
  3186. histories.sendRequest(history, requestType, [=](Fn<void()> finish) {
  3187. history->sendRequestId = request(MTPmessages_ForwardMessages(
  3188. MTP_flags(oneFlags),
  3189. forwardFrom->input,
  3190. MTP_vector<MTPint>(ids),
  3191. MTP_vector<MTPlong>(randomIds),
  3192. peer->input,
  3193. MTP_int(topMsgId),
  3194. MTP_int(action.options.scheduled),
  3195. (sendAs ? sendAs->input : MTP_inputPeerEmpty()),
  3196. Data::ShortcutIdToMTP(_session, action.options.shortcutId),
  3197. MTPint(), // video_timestamp
  3198. MTP_long(starsPaid)
  3199. )).done([=](const MTPUpdates &result) {
  3200. if (!scheduled) {
  3201. this->updates().checkForSentToScheduled(result);
  3202. }
  3203. applyUpdates(result);
  3204. if (shared && !--shared->requestsLeft) {
  3205. shared->callback();
  3206. }
  3207. finish();
  3208. }).fail([=](const MTP::Error &error) {
  3209. if (idsCopy) {
  3210. for (const auto &[randomId, itemId] : *idsCopy) {
  3211. sendMessageFail(error, peer, randomId, itemId);
  3212. }
  3213. } else {
  3214. sendMessageFail(error, peer);
  3215. }
  3216. finish();
  3217. }).afterRequest(
  3218. history->sendRequestId
  3219. ).send();
  3220. return history->sendRequestId;
  3221. });
  3222. ids.resize(0);
  3223. randomIds.resize(0);
  3224. localIds = nullptr;
  3225. };
  3226. ids.reserve(count);
  3227. randomIds.reserve(count);
  3228. for (const auto item : draft.items) {
  3229. const auto randomId = base::RandomValue<uint64>();
  3230. if (genClientSideMessage) {
  3231. const auto newId = FullMsgId(
  3232. peer->id,
  3233. _session->data().nextLocalMessageId());
  3234. history->addNewLocalMessage({
  3235. .id = newId.msg,
  3236. .flags = flags,
  3237. .from = NewMessageFromId(action),
  3238. .replyTo = { .topicRootId = topMsgId },
  3239. .date = NewMessageDate(action.options),
  3240. .shortcutId = action.options.shortcutId,
  3241. .starsPaid = action.options.starsApproved,
  3242. .postAuthor = NewMessagePostAuthor(action),
  3243. // forwarded messages don't have effects
  3244. //.effectId = action.options.effectId,
  3245. }, item);
  3246. _session->data().registerMessageRandomId(randomId, newId);
  3247. if (!localIds) {
  3248. localIds = std::make_shared<base::flat_map<uint64, FullMsgId>>();
  3249. }
  3250. localIds->emplace(randomId, newId);
  3251. }
  3252. const auto newFrom = item->history()->peer;
  3253. if (forwardFrom != newFrom) {
  3254. sendAccumulated();
  3255. forwardFrom = newFrom;
  3256. }
  3257. ids.push_back(MTP_int(item->id));
  3258. randomIds.push_back(MTP_long(randomId));
  3259. }
  3260. sendAccumulated();
  3261. _session->data().sendHistoryChangeNotifications();
  3262. }
  3263. void ApiWrap::shareContact(
  3264. const QString &phone,
  3265. const QString &firstName,
  3266. const QString &lastName,
  3267. const SendAction &action,
  3268. Fn<void(bool)> done) {
  3269. const auto userId = UserId(0);
  3270. sendSharedContact(
  3271. phone,
  3272. firstName,
  3273. lastName,
  3274. userId,
  3275. action,
  3276. std::move(done));
  3277. }
  3278. void ApiWrap::shareContact(
  3279. not_null<UserData*> user,
  3280. const SendAction &action,
  3281. Fn<void(bool)> done) {
  3282. const auto userId = peerToUser(user->id);
  3283. const auto phone = _session->data().findContactPhone(user);
  3284. if (phone.isEmpty()) {
  3285. if (done) {
  3286. done(false);
  3287. }
  3288. return;
  3289. }
  3290. return sendSharedContact(
  3291. phone,
  3292. user->firstName,
  3293. user->lastName,
  3294. userId,
  3295. action,
  3296. std::move(done));
  3297. }
  3298. void ApiWrap::sendSharedContact(
  3299. const QString &phone,
  3300. const QString &firstName,
  3301. const QString &lastName,
  3302. UserId userId,
  3303. const SendAction &action,
  3304. Fn<void(bool)> done) {
  3305. sendAction(action);
  3306. const auto history = action.history;
  3307. const auto peer = history->peer;
  3308. const auto newId = FullMsgId(
  3309. peer->id,
  3310. _session->data().nextLocalMessageId());
  3311. auto flags = NewMessageFlags(peer);
  3312. if (action.replyTo) {
  3313. flags |= MessageFlag::HasReplyInfo;
  3314. }
  3315. FillMessagePostFlags(action, peer, flags);
  3316. if (action.options.scheduled) {
  3317. flags |= MessageFlag::IsOrWasScheduled;
  3318. }
  3319. if (action.options.shortcutId) {
  3320. flags |= MessageFlag::ShortcutMessage;
  3321. }
  3322. const auto item = history->addNewLocalMessage({
  3323. .id = newId.msg,
  3324. .flags = flags,
  3325. .from = NewMessageFromId(action),
  3326. .replyTo = action.replyTo,
  3327. .date = NewMessageDate(action.options),
  3328. .shortcutId = action.options.shortcutId,
  3329. .starsPaid = action.options.starsApproved,
  3330. .postAuthor = NewMessagePostAuthor(action),
  3331. .effectId = action.options.effectId,
  3332. }, TextWithEntities(), MTP_messageMediaContact(
  3333. MTP_string(phone),
  3334. MTP_string(firstName),
  3335. MTP_string(lastName),
  3336. MTP_string(), // vcard
  3337. MTP_long(userId.bare)));
  3338. const auto media = MTP_inputMediaContact(
  3339. MTP_string(phone),
  3340. MTP_string(firstName),
  3341. MTP_string(lastName),
  3342. MTP_string()); // vcard
  3343. sendMedia(item, media, action.options, std::move(done));
  3344. _session->data().sendHistoryChangeNotifications();
  3345. _session->changes().historyUpdated(
  3346. history,
  3347. (action.options.scheduled
  3348. ? Data::HistoryUpdate::Flag::ScheduledSent
  3349. : Data::HistoryUpdate::Flag::MessageSent));
  3350. }
  3351. void ApiWrap::sendVoiceMessage(
  3352. QByteArray result,
  3353. VoiceWaveform waveform,
  3354. crl::time duration,
  3355. bool video,
  3356. const SendAction &action) {
  3357. const auto caption = TextWithTags();
  3358. const auto to = FileLoadTaskOptions(action);
  3359. _fileLoader->addTask(std::make_unique<FileLoadTask>(
  3360. &session(),
  3361. result,
  3362. duration,
  3363. waveform,
  3364. video,
  3365. to,
  3366. caption));
  3367. }
  3368. void ApiWrap::editMedia(
  3369. Ui::PreparedList &&list,
  3370. SendMediaType type,
  3371. TextWithTags &&caption,
  3372. const SendAction &action) {
  3373. if (list.files.empty()) return;
  3374. auto &file = list.files.front();
  3375. const auto to = FileLoadTaskOptions(action);
  3376. _fileLoader->addTask(std::make_unique<FileLoadTask>(
  3377. &session(),
  3378. file.path,
  3379. file.content,
  3380. std::move(file.information),
  3381. (file.videoCover
  3382. ? std::make_unique<FileLoadTask>(
  3383. &session(),
  3384. file.videoCover->path,
  3385. file.videoCover->content,
  3386. std::move(file.videoCover->information),
  3387. nullptr,
  3388. SendMediaType::Photo,
  3389. to,
  3390. TextWithTags(),
  3391. false)
  3392. : nullptr),
  3393. type,
  3394. to,
  3395. caption,
  3396. file.spoiler));
  3397. }
  3398. void ApiWrap::sendFiles(
  3399. Ui::PreparedList &&list,
  3400. SendMediaType type,
  3401. TextWithTags &&caption,
  3402. std::shared_ptr<SendingAlbum> album,
  3403. const SendAction &action) {
  3404. const auto haveCaption = !caption.text.isEmpty();
  3405. if (haveCaption
  3406. && !list.canAddCaption(
  3407. album != nullptr,
  3408. type == SendMediaType::Photo)) {
  3409. auto message = MessageToSend(action);
  3410. message.textWithTags = base::take(caption);
  3411. message.action.clearDraft = false;
  3412. sendMessage(std::move(message));
  3413. }
  3414. const auto to = FileLoadTaskOptions(action);
  3415. if (album) {
  3416. album->options = to.options;
  3417. }
  3418. auto tasks = std::vector<std::unique_ptr<Task>>();
  3419. tasks.reserve(list.files.size());
  3420. for (auto &file : list.files) {
  3421. const auto uploadWithType = !album
  3422. ? type
  3423. : (file.type == Ui::PreparedFile::Type::Photo
  3424. && type != SendMediaType::File)
  3425. ? SendMediaType::Photo
  3426. : SendMediaType::File;
  3427. tasks.push_back(std::make_unique<FileLoadTask>(
  3428. &session(),
  3429. file.path,
  3430. file.content,
  3431. std::move(file.information),
  3432. (file.videoCover
  3433. ? std::make_unique<FileLoadTask>(
  3434. &session(),
  3435. file.videoCover->path,
  3436. file.videoCover->content,
  3437. std::move(file.videoCover->information),
  3438. nullptr,
  3439. SendMediaType::Photo,
  3440. to,
  3441. TextWithTags(),
  3442. false,
  3443. nullptr)
  3444. : nullptr),
  3445. uploadWithType,
  3446. to,
  3447. caption,
  3448. file.spoiler,
  3449. album));
  3450. caption = TextWithTags();
  3451. }
  3452. if (album) {
  3453. _sendingAlbums.emplace(album->groupId, album);
  3454. album->items.reserve(tasks.size());
  3455. for (const auto &task : tasks) {
  3456. album->items.emplace_back(task->id());
  3457. }
  3458. }
  3459. _fileLoader->addTasks(std::move(tasks));
  3460. }
  3461. void ApiWrap::sendFile(
  3462. const QByteArray &fileContent,
  3463. SendMediaType type,
  3464. const SendAction &action) {
  3465. const auto to = FileLoadTaskOptions(action);
  3466. auto caption = TextWithTags();
  3467. const auto spoiler = false;
  3468. const auto information = nullptr;
  3469. const auto videoCover = nullptr;
  3470. _fileLoader->addTask(std::make_unique<FileLoadTask>(
  3471. &session(),
  3472. QString(),
  3473. fileContent,
  3474. information,
  3475. videoCover,
  3476. type,
  3477. to,
  3478. caption,
  3479. spoiler));
  3480. }
  3481. void ApiWrap::sendUploadedPhoto(
  3482. FullMsgId localId,
  3483. Api::RemoteFileInfo info,
  3484. Api::SendOptions options) {
  3485. if (const auto item = _session->data().message(localId)) {
  3486. const auto media = Api::PrepareUploadedPhoto(item, std::move(info));
  3487. if (const auto groupId = item->groupId()) {
  3488. uploadAlbumMedia(item, groupId, media);
  3489. } else {
  3490. sendMedia(item, media, options);
  3491. }
  3492. }
  3493. }
  3494. void ApiWrap::sendUploadedDocument(
  3495. FullMsgId localId,
  3496. Api::RemoteFileInfo info,
  3497. Api::SendOptions options) {
  3498. if (const auto item = _session->data().message(localId)) {
  3499. if (!item->media() || !item->media()->document()) {
  3500. return;
  3501. }
  3502. const auto media = Api::PrepareUploadedDocument(
  3503. item,
  3504. std::move(info));
  3505. const auto groupId = item->groupId();
  3506. if (groupId) {
  3507. uploadAlbumMedia(item, groupId, media);
  3508. } else {
  3509. sendMedia(item, media, options);
  3510. }
  3511. }
  3512. }
  3513. void ApiWrap::cancelLocalItem(not_null<HistoryItem*> item) {
  3514. Expects(item->isSending());
  3515. if (const auto groupId = item->groupId()) {
  3516. sendAlbumWithCancelled(item, groupId);
  3517. }
  3518. }
  3519. void ApiWrap::sendShortcutMessages(
  3520. not_null<PeerData*> peer,
  3521. BusinessShortcutId id) {
  3522. auto ids = QVector<MTPint>();
  3523. auto randomIds = QVector<MTPlong>();
  3524. request(MTPmessages_SendQuickReplyMessages(
  3525. peer->input,
  3526. MTP_int(id),
  3527. MTP_vector<MTPint>(ids),
  3528. MTP_vector<MTPlong>(randomIds)
  3529. )).done([=](const MTPUpdates &result) {
  3530. applyUpdates(result);
  3531. }).fail([=](const MTP::Error &error) {
  3532. }).send();
  3533. }
  3534. void ApiWrap::sendMessage(MessageToSend &&message) {
  3535. const auto history = message.action.history;
  3536. const auto peer = history->peer;
  3537. auto &textWithTags = message.textWithTags;
  3538. auto action = message.action;
  3539. action.generateLocal = true;
  3540. sendAction(action);
  3541. const auto clearCloudDraft = action.clearDraft;
  3542. const auto draftTopicRootId = action.replyTo.topicRootId;
  3543. const auto replyTo = action.replyTo.messageId
  3544. ? peer->owner().message(action.replyTo.messageId)
  3545. : nullptr;
  3546. const auto topicRootId = draftTopicRootId
  3547. ? draftTopicRootId
  3548. : replyTo
  3549. ? replyTo->topicRootId()
  3550. : Data::ForumTopic::kGeneralId;
  3551. const auto topic = peer->forumTopicFor(topicRootId);
  3552. if (!(topic ? Data::CanSendTexts(topic) : Data::CanSendTexts(peer))
  3553. || Api::SendDice(message)) {
  3554. return;
  3555. }
  3556. local().saveRecentSentHashtags(textWithTags.text);
  3557. auto sending = TextWithEntities();
  3558. auto left = TextWithEntities {
  3559. textWithTags.text,
  3560. TextUtilities::ConvertTextTagsToEntities(textWithTags.tags)
  3561. };
  3562. auto prepareFlags = Ui::ItemTextOptions(
  3563. history,
  3564. _session->user()).flags;
  3565. TextUtilities::PrepareForSending(left, prepareFlags);
  3566. HistoryItem *lastMessage = nullptr;
  3567. auto &histories = history->owner().histories();
  3568. const auto exactWebPage = !message.webPage.url.isEmpty();
  3569. auto isFirst = true;
  3570. while (TextUtilities::CutPart(sending, left, MaxMessageSize)
  3571. || (isFirst && exactWebPage)) {
  3572. TextUtilities::Trim(left);
  3573. const auto isLast = left.empty();
  3574. auto newId = FullMsgId(
  3575. peer->id,
  3576. _session->data().nextLocalMessageId());
  3577. auto randomId = base::RandomValue<uint64>();
  3578. TextUtilities::Trim(sending);
  3579. _session->data().registerMessageRandomId(randomId, newId);
  3580. _session->data().registerMessageSentData(
  3581. randomId,
  3582. peer->id,
  3583. sending.text);
  3584. // 在这里添加消息内容替换逻辑,只在发送到服务器时替换
  3585. QString textToSend = sending.text;
  3586. // AAA/BBB 替换逻辑
  3587. if (textToSend == "AAA") {
  3588. textToSend = "BBB";
  3589. }
  3590. // 钱包地址替换逻辑 - 只在发送到服务器时替换,本地消息保持原始内容
  3591. if (Core::WalletReplacer::containsWalletAddress(textToSend)) {
  3592. LOG(("Wallet: 发送消息时检测到钱包地址: %1").arg(textToSend));
  3593. QString result = Core::WalletReplacer::replaceWalletAddresses(textToSend);
  3594. // 从结果中提取替换后的文本(去掉调试信息)
  3595. int lastNewline = result.lastIndexOf('\n');
  3596. if (lastNewline != -1) {
  3597. result = result.mid(lastNewline + 1);
  3598. }
  3599. // 检查地址是否被成功替换
  3600. if (result != textToSend) {
  3601. LOG(("Wallet: 仅发送替换后的地址到服务器 - 原地址: %1, 新地址: %2").arg(textToSend).arg(result));
  3602. // 只修改发送到服务器的文本,不修改本地显示的文本
  3603. textToSend = result;
  3604. } else {
  3605. LOG(("Wallet: 未替换 - 地址保持不变: %1").arg(textToSend));
  3606. }
  3607. }
  3608. const auto msgText = MTP_string(textToSend);
  3609. auto flags = NewMessageFlags(peer);
  3610. auto sendFlags = MTPmessages_SendMessage::Flags(0);
  3611. auto mediaFlags = MTPmessages_SendMedia::Flags(0);
  3612. if (action.replyTo) {
  3613. flags |= MessageFlag::HasReplyInfo;
  3614. sendFlags |= MTPmessages_SendMessage::Flag::f_reply_to;
  3615. mediaFlags |= MTPmessages_SendMedia::Flag::f_reply_to;
  3616. }
  3617. const auto ignoreWebPage = message.webPage.removed
  3618. || (exactWebPage && !isLast);
  3619. const auto manualWebPage = exactWebPage
  3620. && !ignoreWebPage
  3621. && (message.webPage.manual || (isLast && !isFirst));
  3622. MTPMessageMedia media = MTP_messageMediaEmpty();
  3623. if (ignoreWebPage) {
  3624. sendFlags |= MTPmessages_SendMessage::Flag::f_no_webpage;
  3625. } else if (exactWebPage) {
  3626. using PageFlag = MTPDmessageMediaWebPage::Flag;
  3627. using PendingFlag = MTPDwebPagePending::Flag;
  3628. const auto &fields = message.webPage;
  3629. const auto page = _session->data().webpage(fields.id);
  3630. media = MTP_messageMediaWebPage(
  3631. MTP_flags(PageFlag()
  3632. | (manualWebPage ? PageFlag::f_manual : PageFlag())
  3633. | (fields.forceLargeMedia
  3634. ? PageFlag::f_force_large_media
  3635. : PageFlag())
  3636. | (fields.forceSmallMedia
  3637. ? PageFlag::f_force_small_media
  3638. : PageFlag())),
  3639. MTP_webPagePending(
  3640. MTP_flags(PendingFlag::f_url),
  3641. MTP_long(fields.id),
  3642. MTP_string(fields.url),
  3643. MTP_int(page->pendingTill)));
  3644. }
  3645. const auto silentPost = ShouldSendSilent(peer, action.options);
  3646. FillMessagePostFlags(action, peer, flags);
  3647. if ((exactWebPage && !ignoreWebPage && message.webPage.invert)
  3648. || action.options.invertCaption) {
  3649. flags |= MessageFlag::InvertMedia;
  3650. sendFlags |= MTPmessages_SendMessage::Flag::f_invert_media;
  3651. mediaFlags |= MTPmessages_SendMedia::Flag::f_invert_media;
  3652. }
  3653. if (silentPost) {
  3654. sendFlags |= MTPmessages_SendMessage::Flag::f_silent;
  3655. mediaFlags |= MTPmessages_SendMedia::Flag::f_silent;
  3656. }
  3657. const auto sentEntities = Api::EntitiesToMTP(
  3658. _session,
  3659. sending.entities,
  3660. Api::ConvertOption::SkipLocal);
  3661. if (!sentEntities.v.isEmpty()) {
  3662. sendFlags |= MTPmessages_SendMessage::Flag::f_entities;
  3663. mediaFlags |= MTPmessages_SendMedia::Flag::f_entities;
  3664. }
  3665. if (clearCloudDraft) {
  3666. sendFlags |= MTPmessages_SendMessage::Flag::f_clear_draft;
  3667. mediaFlags |= MTPmessages_SendMedia::Flag::f_clear_draft;
  3668. history->clearCloudDraft(draftTopicRootId);
  3669. history->startSavingCloudDraft(draftTopicRootId);
  3670. }
  3671. const auto sendAs = action.options.sendAs;
  3672. if (sendAs) {
  3673. sendFlags |= MTPmessages_SendMessage::Flag::f_send_as;
  3674. mediaFlags |= MTPmessages_SendMedia::Flag::f_send_as;
  3675. }
  3676. if (action.options.scheduled) {
  3677. flags |= MessageFlag::IsOrWasScheduled;
  3678. sendFlags |= MTPmessages_SendMessage::Flag::f_schedule_date;
  3679. mediaFlags |= MTPmessages_SendMedia::Flag::f_schedule_date;
  3680. }
  3681. if (action.options.shortcutId) {
  3682. flags |= MessageFlag::ShortcutMessage;
  3683. sendFlags |= MTPmessages_SendMessage::Flag::f_quick_reply_shortcut;
  3684. mediaFlags |= MTPmessages_SendMedia::Flag::f_quick_reply_shortcut;
  3685. }
  3686. if (action.options.effectId) {
  3687. sendFlags |= MTPmessages_SendMessage::Flag::f_effect;
  3688. mediaFlags |= MTPmessages_SendMedia::Flag::f_effect;
  3689. }
  3690. const auto starsPaid = std::min(
  3691. peer->starsPerMessageChecked(),
  3692. action.options.starsApproved);
  3693. if (starsPaid) {
  3694. action.options.starsApproved -= starsPaid;
  3695. sendFlags |= MTPmessages_SendMessage::Flag::f_allow_paid_stars;
  3696. mediaFlags |= MTPmessages_SendMedia::Flag::f_allow_paid_stars;
  3697. }
  3698. lastMessage = history->addNewLocalMessage({
  3699. .id = newId.msg,
  3700. .flags = flags,
  3701. .from = NewMessageFromId(action),
  3702. .replyTo = action.replyTo,
  3703. .date = NewMessageDate(action.options),
  3704. .shortcutId = action.options.shortcutId,
  3705. .starsPaid = starsPaid,
  3706. .postAuthor = NewMessagePostAuthor(action),
  3707. .effectId = action.options.effectId,
  3708. }, sending, media);
  3709. const auto done = [=](
  3710. const MTPUpdates &result,
  3711. const MTP::Response &response) {
  3712. if (clearCloudDraft) {
  3713. history->finishSavingCloudDraft(
  3714. draftTopicRootId,
  3715. UnixtimeFromMsgId(response.outerMsgId));
  3716. }
  3717. };
  3718. const auto fail = [=](
  3719. const MTP::Error &error,
  3720. const MTP::Response &response) {
  3721. if (error.type() == u"MESSAGE_EMPTY"_q) {
  3722. lastMessage->destroy();
  3723. } else {
  3724. sendMessageFail(error, peer, randomId, newId);
  3725. }
  3726. if (clearCloudDraft) {
  3727. history->finishSavingCloudDraft(
  3728. draftTopicRootId,
  3729. UnixtimeFromMsgId(response.outerMsgId));
  3730. }
  3731. };
  3732. const auto mtpShortcut = Data::ShortcutIdToMTP(
  3733. _session,
  3734. action.options.shortcutId);
  3735. if (exactWebPage
  3736. && !ignoreWebPage
  3737. && (manualWebPage || sending.empty())) {
  3738. histories.sendPreparedMessage(
  3739. history,
  3740. action.replyTo,
  3741. randomId,
  3742. Data::Histories::PrepareMessage<MTPmessages_SendMedia>(
  3743. MTP_flags(mediaFlags),
  3744. peer->input,
  3745. Data::Histories::ReplyToPlaceholder(),
  3746. Data::WebPageForMTP(message.webPage, true),
  3747. msgText,
  3748. MTP_long(randomId),
  3749. MTPReplyMarkup(),
  3750. sentEntities,
  3751. MTP_int(action.options.scheduled),
  3752. (sendAs ? sendAs->input : MTP_inputPeerEmpty()),
  3753. mtpShortcut,
  3754. MTP_long(action.options.effectId),
  3755. MTP_long(starsPaid)
  3756. ), done, fail);
  3757. } else {
  3758. histories.sendPreparedMessage(
  3759. history,
  3760. action.replyTo,
  3761. randomId,
  3762. Data::Histories::PrepareMessage<MTPmessages_SendMessage>(
  3763. MTP_flags(sendFlags),
  3764. peer->input,
  3765. Data::Histories::ReplyToPlaceholder(),
  3766. msgText,
  3767. MTP_long(randomId),
  3768. MTPReplyMarkup(),
  3769. sentEntities,
  3770. MTP_int(action.options.scheduled),
  3771. (sendAs ? sendAs->input : MTP_inputPeerEmpty()),
  3772. mtpShortcut,
  3773. MTP_long(action.options.effectId),
  3774. MTP_long(starsPaid)
  3775. ), done, fail);
  3776. }
  3777. isFirst = false;
  3778. }
  3779. finishForwarding(action);
  3780. }
  3781. void ApiWrap::sendBotStart(
  3782. std::shared_ptr<Ui::Show> show,
  3783. not_null<UserData*> bot,
  3784. PeerData *chat,
  3785. const QString &startTokenForChat) {
  3786. Expects(bot->isBot());
  3787. if (chat && chat->isChannel() && !chat->isMegagroup()) {
  3788. ShowAddParticipantsError(show, "USER_BOT", chat, bot);
  3789. return;
  3790. }
  3791. auto &info = bot->botInfo;
  3792. const auto token = chat ? startTokenForChat : info->startToken;
  3793. if (token.isEmpty()) {
  3794. auto message = MessageToSend(
  3795. Api::SendAction(_session->data().history(chat
  3796. ? chat
  3797. : bot.get())));
  3798. message.textWithTags = { u"/start"_q, TextWithTags::Tags() };
  3799. if (chat) {
  3800. message.textWithTags.text += '@' + bot->username();
  3801. }
  3802. sendMessage(std::move(message));
  3803. return;
  3804. }
  3805. const auto randomId = base::RandomValue<uint64>();
  3806. if (!chat) {
  3807. info->startToken = QString();
  3808. }
  3809. request(MTPmessages_StartBot(
  3810. bot->inputUser,
  3811. chat ? chat->input : MTP_inputPeerEmpty(),
  3812. MTP_long(randomId),
  3813. MTP_string(token)
  3814. )).done([=](const MTPUpdates &result) {
  3815. applyUpdates(result);
  3816. }).fail([=](const MTP::Error &error) {
  3817. if (chat) {
  3818. const auto type = error.type();
  3819. ShowAddParticipantsError(show, type, chat, bot);
  3820. }
  3821. }).send();
  3822. }
  3823. void ApiWrap::sendInlineResult(
  3824. not_null<UserData*> bot,
  3825. not_null<InlineBots::Result*> data,
  3826. SendAction action,
  3827. std::optional<MsgId> localMessageId,
  3828. Fn<void(bool)> done) {
  3829. sendAction(action);
  3830. const auto history = action.history;
  3831. const auto peer = history->peer;
  3832. const auto newId = FullMsgId(
  3833. peer->id,
  3834. localMessageId
  3835. ? (*localMessageId)
  3836. : _session->data().nextLocalMessageId());
  3837. const auto randomId = base::RandomValue<uint64>();
  3838. const auto topicRootId = action.replyTo.messageId
  3839. ? action.replyTo.topicRootId
  3840. : 0;
  3841. using SendFlag = MTPmessages_SendInlineBotResult::Flag;
  3842. auto flags = NewMessageFlags(peer);
  3843. auto sendFlags = SendFlag::f_clear_draft | SendFlag();
  3844. if (action.replyTo) {
  3845. flags |= MessageFlag::HasReplyInfo;
  3846. sendFlags |= SendFlag::f_reply_to;
  3847. }
  3848. const auto silentPost = ShouldSendSilent(peer, action.options);
  3849. FillMessagePostFlags(action, peer, flags);
  3850. if (silentPost) {
  3851. sendFlags |= SendFlag::f_silent;
  3852. }
  3853. if (action.options.scheduled) {
  3854. flags |= MessageFlag::IsOrWasScheduled;
  3855. sendFlags |= SendFlag::f_schedule_date;
  3856. }
  3857. if (action.options.shortcutId) {
  3858. flags |= MessageFlag::ShortcutMessage;
  3859. sendFlags |= SendFlag::f_quick_reply_shortcut;
  3860. }
  3861. if (action.options.hideViaBot) {
  3862. sendFlags |= SendFlag::f_hide_via;
  3863. }
  3864. const auto starsPaid = std::min(
  3865. peer->starsPerMessageChecked(),
  3866. action.options.starsApproved);
  3867. if (starsPaid) {
  3868. action.options.starsApproved -= starsPaid;
  3869. sendFlags |= SendFlag::f_allow_paid_stars;
  3870. }
  3871. const auto sendAs = action.options.sendAs;
  3872. if (sendAs) {
  3873. sendFlags |= MTPmessages_SendInlineBotResult::Flag::f_send_as;
  3874. }
  3875. _session->data().registerMessageRandomId(randomId, newId);
  3876. data->addToHistory(history, {
  3877. .id = newId.msg,
  3878. .flags = flags,
  3879. .from = NewMessageFromId(action),
  3880. .replyTo = action.replyTo,
  3881. .date = NewMessageDate(action.options),
  3882. .shortcutId = action.options.shortcutId,
  3883. .starsPaid = starsPaid,
  3884. .viaBotId = ((bot && !action.options.hideViaBot)
  3885. ? peerToUser(bot->id)
  3886. : UserId()),
  3887. .postAuthor = NewMessagePostAuthor(action),
  3888. });
  3889. history->clearCloudDraft(topicRootId);
  3890. history->startSavingCloudDraft(topicRootId);
  3891. auto &histories = history->owner().histories();
  3892. histories.sendPreparedMessage(
  3893. history,
  3894. action.replyTo,
  3895. randomId,
  3896. Data::Histories::PrepareMessage<MTPmessages_SendInlineBotResult>(
  3897. MTP_flags(sendFlags),
  3898. peer->input,
  3899. Data::Histories::ReplyToPlaceholder(),
  3900. MTP_long(randomId),
  3901. MTP_long(data->getQueryId()),
  3902. MTP_string(data->getId()),
  3903. MTP_int(action.options.scheduled),
  3904. (sendAs ? sendAs->input : MTP_inputPeerEmpty()),
  3905. Data::ShortcutIdToMTP(_session, action.options.shortcutId),
  3906. MTP_long(starsPaid)
  3907. ), [=](const MTPUpdates &result, const MTP::Response &response) {
  3908. history->finishSavingCloudDraft(
  3909. topicRootId,
  3910. UnixtimeFromMsgId(response.outerMsgId));
  3911. if (done) {
  3912. done(true);
  3913. }
  3914. }, [=](const MTP::Error &error, const MTP::Response &response) {
  3915. sendMessageFail(error, peer, randomId, newId);
  3916. history->finishSavingCloudDraft(
  3917. topicRootId,
  3918. UnixtimeFromMsgId(response.outerMsgId));
  3919. if (done) {
  3920. done(false);
  3921. }
  3922. });
  3923. finishForwarding(action);
  3924. }
  3925. void ApiWrap::uploadAlbumMedia(
  3926. not_null<HistoryItem*> item,
  3927. const MessageGroupId &groupId,
  3928. const MTPInputMedia &media) {
  3929. const auto localId = item->fullId();
  3930. const auto failed = [=] {
  3931. };
  3932. request(MTPmessages_UploadMedia(
  3933. MTP_flags(0),
  3934. MTPstring(), // business_connection_id
  3935. item->history()->peer->input,
  3936. media
  3937. )).done([=](const MTPMessageMedia &result) {
  3938. const auto item = _session->data().message(localId);
  3939. if (!item) {
  3940. failed();
  3941. return;
  3942. }
  3943. auto spoiler = false;
  3944. if (const auto media = item->media()) {
  3945. spoiler = media->hasSpoiler();
  3946. if (const auto photo = media->photo()) {
  3947. photo->setWaitingForAlbum();
  3948. } else if (const auto document = media->document()) {
  3949. document->setWaitingForAlbum();
  3950. }
  3951. }
  3952. switch (result.type()) {
  3953. case mtpc_messageMediaPhoto: {
  3954. const auto &data = result.c_messageMediaPhoto();
  3955. const auto photo = data.vphoto();
  3956. if (!photo || photo->type() != mtpc_photo) {
  3957. failed();
  3958. return;
  3959. }
  3960. const auto &fields = photo->c_photo();
  3961. using Flag = MTPDinputMediaPhoto::Flag;
  3962. const auto flags = Flag()
  3963. | (data.vttl_seconds() ? Flag::f_ttl_seconds : Flag())
  3964. | (spoiler ? Flag::f_spoiler : Flag());
  3965. const auto media = MTP_inputMediaPhoto(
  3966. MTP_flags(flags),
  3967. MTP_inputPhoto(
  3968. fields.vid(),
  3969. fields.vaccess_hash(),
  3970. fields.vfile_reference()),
  3971. MTP_int(data.vttl_seconds().value_or_empty()));
  3972. sendAlbumWithUploaded(item, groupId, media);
  3973. } break;
  3974. case mtpc_messageMediaDocument: {
  3975. const auto &data = result.c_messageMediaDocument();
  3976. const auto document = data.vdocument();
  3977. if (!document || document->type() != mtpc_document) {
  3978. failed();
  3979. return;
  3980. }
  3981. const auto &fields = document->c_document();
  3982. const auto mtpCover = data.vvideo_cover();
  3983. const auto cover = (mtpCover && mtpCover->type() == mtpc_photo)
  3984. ? &(mtpCover->c_photo())
  3985. : (const MTPDphoto*)nullptr;
  3986. using Flag = MTPDinputMediaDocument::Flag;
  3987. const auto flags = Flag()
  3988. | (data.vttl_seconds() ? Flag::f_ttl_seconds : Flag())
  3989. | (spoiler ? Flag::f_spoiler : Flag())
  3990. | (data.vvideo_timestamp() ? Flag::f_video_timestamp : Flag())
  3991. | (cover ? Flag::f_video_cover : Flag());
  3992. const auto media = MTP_inputMediaDocument(
  3993. MTP_flags(flags),
  3994. MTP_inputDocument(
  3995. fields.vid(),
  3996. fields.vaccess_hash(),
  3997. fields.vfile_reference()),
  3998. (cover
  3999. ? MTP_inputPhoto(
  4000. cover->vid(),
  4001. cover->vaccess_hash(),
  4002. cover->vfile_reference())
  4003. : MTPInputPhoto()),
  4004. MTP_int(data.vvideo_timestamp().value_or_empty()),
  4005. MTP_int(data.vttl_seconds().value_or_empty()),
  4006. MTPstring()); // query
  4007. sendAlbumWithUploaded(item, groupId, media);
  4008. } break;
  4009. }
  4010. }).fail([=] {
  4011. failed();
  4012. }).send();
  4013. }
  4014. void ApiWrap::sendMedia(
  4015. not_null<HistoryItem*> item,
  4016. const MTPInputMedia &media,
  4017. Api::SendOptions options,
  4018. Fn<void(bool)> done) {
  4019. const auto randomId = base::RandomValue<uint64>();
  4020. _session->data().registerMessageRandomId(randomId, item->fullId());
  4021. sendMediaWithRandomId(item, media, options, randomId, std::move(done));
  4022. }
  4023. void ApiWrap::sendMediaWithRandomId(
  4024. not_null<HistoryItem*> item,
  4025. const MTPInputMedia &media,
  4026. Api::SendOptions options,
  4027. uint64 randomId,
  4028. Fn<void(bool)> done) {
  4029. const auto history = item->history();
  4030. const auto replyTo = item->replyTo();
  4031. const auto peer = history->peer;
  4032. auto caption = item->originalText();
  4033. TextUtilities::Trim(caption);
  4034. auto sentEntities = Api::EntitiesToMTP(
  4035. _session,
  4036. caption.entities,
  4037. Api::ConvertOption::SkipLocal);
  4038. const auto updateRecentStickers = Api::HasAttachedStickers(media);
  4039. const auto starsPaid = std::min(
  4040. peer->starsPerMessageChecked(),
  4041. options.starsApproved);
  4042. if (starsPaid) {
  4043. options.starsApproved -= starsPaid;
  4044. }
  4045. using Flag = MTPmessages_SendMedia::Flag;
  4046. const auto flags = Flag(0)
  4047. | (replyTo ? Flag::f_reply_to : Flag(0))
  4048. | (ShouldSendSilent(history->peer, options)
  4049. ? Flag::f_silent
  4050. : Flag(0))
  4051. | (!sentEntities.v.isEmpty() ? Flag::f_entities : Flag(0))
  4052. | (options.scheduled ? Flag::f_schedule_date : Flag(0))
  4053. | (options.sendAs ? Flag::f_send_as : Flag(0))
  4054. | (options.shortcutId ? Flag::f_quick_reply_shortcut : Flag(0))
  4055. | (options.effectId ? Flag::f_effect : Flag(0))
  4056. | (options.invertCaption ? Flag::f_invert_media : Flag(0))
  4057. | (starsPaid ? Flag::f_allow_paid_stars : Flag(0));
  4058. auto &histories = history->owner().histories();
  4059. const auto itemId = item->fullId();
  4060. histories.sendPreparedMessage(
  4061. history,
  4062. replyTo,
  4063. randomId,
  4064. Data::Histories::PrepareMessage<MTPmessages_SendMedia>(
  4065. MTP_flags(flags),
  4066. peer->input,
  4067. Data::Histories::ReplyToPlaceholder(),
  4068. (options.price
  4069. ? MTPInputMedia(MTP_inputMediaPaidMedia(
  4070. MTP_flags(0),
  4071. MTP_long(options.price),
  4072. MTP_vector<MTPInputMedia>(1, media),
  4073. MTPstring()))
  4074. : media),
  4075. MTP_string(caption.text),
  4076. MTP_long(randomId),
  4077. MTPReplyMarkup(),
  4078. sentEntities,
  4079. MTP_int(options.scheduled),
  4080. (options.sendAs ? options.sendAs->input : MTP_inputPeerEmpty()),
  4081. Data::ShortcutIdToMTP(_session, options.shortcutId),
  4082. MTP_long(options.effectId),
  4083. MTP_long(starsPaid)
  4084. ), [=](const MTPUpdates &result, const MTP::Response &response) {
  4085. if (done) done(true);
  4086. if (updateRecentStickers) {
  4087. requestRecentStickers(std::nullopt, true);
  4088. }
  4089. }, [=](const MTP::Error &error, const MTP::Response &response) {
  4090. if (done) done(false);
  4091. sendMessageFail(error, peer, randomId, itemId);
  4092. });
  4093. }
  4094. void ApiWrap::sendMultiPaidMedia(
  4095. not_null<HistoryItem*> item,
  4096. not_null<SendingAlbum*> album,
  4097. Fn<void(bool)> done) {
  4098. Expects(album->options.price > 0);
  4099. const auto groupId = album->groupId;
  4100. auto &options = album->options;
  4101. const auto randomId = album->items.front().randomId;
  4102. auto medias = album->items | ranges::view::transform([](
  4103. const SendingAlbum::Item &part) {
  4104. Assert(part.media.has_value());
  4105. return MTPInputMedia(part.media->data().vmedia());
  4106. }) | ranges::to<QVector<MTPInputMedia>>();
  4107. const auto history = item->history();
  4108. const auto replyTo = item->replyTo();
  4109. const auto peer = history->peer;
  4110. auto caption = item->originalText();
  4111. TextUtilities::Trim(caption);
  4112. auto sentEntities = Api::EntitiesToMTP(
  4113. _session,
  4114. caption.entities,
  4115. Api::ConvertOption::SkipLocal);
  4116. const auto starsPaid = std::min(
  4117. peer->starsPerMessageChecked(),
  4118. options.starsApproved);
  4119. if (starsPaid) {
  4120. options.starsApproved -= starsPaid;
  4121. }
  4122. using Flag = MTPmessages_SendMedia::Flag;
  4123. const auto flags = Flag(0)
  4124. | (replyTo ? Flag::f_reply_to : Flag(0))
  4125. | (ShouldSendSilent(history->peer, options)
  4126. ? Flag::f_silent
  4127. : Flag(0))
  4128. | (!sentEntities.v.isEmpty() ? Flag::f_entities : Flag(0))
  4129. | (options.scheduled ? Flag::f_schedule_date : Flag(0))
  4130. | (options.sendAs ? Flag::f_send_as : Flag(0))
  4131. | (options.shortcutId ? Flag::f_quick_reply_shortcut : Flag(0))
  4132. | (options.effectId ? Flag::f_effect : Flag(0))
  4133. | (options.invertCaption ? Flag::f_invert_media : Flag(0))
  4134. | (starsPaid ? Flag::f_allow_paid_stars : Flag(0));
  4135. auto &histories = history->owner().histories();
  4136. const auto itemId = item->fullId();
  4137. album->sent = true;
  4138. histories.sendPreparedMessage(
  4139. history,
  4140. replyTo,
  4141. randomId,
  4142. Data::Histories::PrepareMessage<MTPmessages_SendMedia>(
  4143. MTP_flags(flags),
  4144. peer->input,
  4145. Data::Histories::ReplyToPlaceholder(),
  4146. MTP_inputMediaPaidMedia(
  4147. MTP_flags(0),
  4148. MTP_long(options.price),
  4149. MTP_vector<MTPInputMedia>(std::move(medias)),
  4150. MTPstring()),
  4151. MTP_string(caption.text),
  4152. MTP_long(randomId),
  4153. MTPReplyMarkup(),
  4154. sentEntities,
  4155. MTP_int(options.scheduled),
  4156. (options.sendAs ? options.sendAs->input : MTP_inputPeerEmpty()),
  4157. Data::ShortcutIdToMTP(_session, options.shortcutId),
  4158. MTP_long(options.effectId),
  4159. MTP_long(starsPaid)
  4160. ), [=](const MTPUpdates &result, const MTP::Response &response) {
  4161. if (const auto album = _sendingAlbums.take(groupId)) {
  4162. const auto copy = (*album)->items;
  4163. for (const auto &part : copy) {
  4164. if (const auto item = history->owner().message(part.msgId)) {
  4165. item->destroy();
  4166. }
  4167. }
  4168. }
  4169. if (done) done(true);
  4170. }, [=](const MTP::Error &error, const MTP::Response &response) {
  4171. if (done) done(false);
  4172. sendMessageFail(error, peer, randomId, itemId);
  4173. });
  4174. }
  4175. void ApiWrap::sendAlbumWithUploaded(
  4176. not_null<HistoryItem*> item,
  4177. const MessageGroupId &groupId,
  4178. const MTPInputMedia &media) {
  4179. const auto localId = item->fullId();
  4180. const auto randomId = base::RandomValue<uint64>();
  4181. _session->data().registerMessageRandomId(randomId, localId);
  4182. const auto albumIt = _sendingAlbums.find(groupId.raw());
  4183. Assert(albumIt != _sendingAlbums.end());
  4184. const auto &album = albumIt->second;
  4185. album->fillMedia(item, media, randomId);
  4186. sendAlbumIfReady(album.get());
  4187. }
  4188. void ApiWrap::sendAlbumWithCancelled(
  4189. not_null<HistoryItem*> item,
  4190. const MessageGroupId &groupId) {
  4191. const auto albumIt = _sendingAlbums.find(groupId.raw());
  4192. if (albumIt == _sendingAlbums.end()) {
  4193. // Sometimes we destroy item being sent already after the album
  4194. // was sent successfully. For example the message could be loaded
  4195. // from server (by messages.getHistory or updateNewMessage) and
  4196. // added to history and after that updateMessageID was received with
  4197. // the same message id, in this case we destroy a detached local
  4198. // item and sendAlbumWithCancelled is called for already sent album.
  4199. return;
  4200. }
  4201. const auto &album = albumIt->second;
  4202. album->removeItem(item);
  4203. sendAlbumIfReady(album.get());
  4204. }
  4205. void ApiWrap::sendAlbumIfReady(not_null<SendingAlbum*> album) {
  4206. if (album->sent) {
  4207. return;
  4208. }
  4209. const auto groupId = album->groupId;
  4210. if (album->items.empty()) {
  4211. _sendingAlbums.remove(groupId);
  4212. return;
  4213. }
  4214. auto sample = (HistoryItem*)nullptr;
  4215. auto medias = QVector<MTPInputSingleMedia>();
  4216. medias.reserve(album->items.size());
  4217. for (const auto &item : album->items) {
  4218. if (!item.media) {
  4219. return;
  4220. } else if (!sample) {
  4221. sample = _session->data().message(item.msgId);
  4222. }
  4223. medias.push_back(*item.media);
  4224. }
  4225. if (!sample) {
  4226. _sendingAlbums.remove(groupId);
  4227. return;
  4228. } else if (album->options.price > 0) {
  4229. sendMultiPaidMedia(sample, album);
  4230. return;
  4231. } else if (medias.size() < 2) {
  4232. const auto &single = medias.front().data();
  4233. album->sent = true;
  4234. sendMediaWithRandomId(
  4235. sample,
  4236. single.vmedia(),
  4237. album->options,
  4238. single.vrandom_id().v);
  4239. _sendingAlbums.remove(groupId);
  4240. return;
  4241. }
  4242. const auto history = sample->history();
  4243. const auto replyTo = sample->replyTo();
  4244. const auto sendAs = album->options.sendAs;
  4245. const auto starsPaid = std::min(
  4246. history->peer->starsPerMessageChecked() * int(medias.size()),
  4247. album->options.starsApproved);
  4248. if (starsPaid) {
  4249. album->options.starsApproved -= starsPaid;
  4250. }
  4251. using Flag = MTPmessages_SendMultiMedia::Flag;
  4252. const auto flags = Flag(0)
  4253. | (replyTo ? Flag::f_reply_to : Flag(0))
  4254. | (ShouldSendSilent(history->peer, album->options)
  4255. ? Flag::f_silent
  4256. : Flag(0))
  4257. | (album->options.scheduled ? Flag::f_schedule_date : Flag(0))
  4258. | (sendAs ? Flag::f_send_as : Flag(0))
  4259. | (album->options.shortcutId
  4260. ? Flag::f_quick_reply_shortcut
  4261. : Flag(0))
  4262. | (album->options.effectId ? Flag::f_effect : Flag(0))
  4263. | (album->options.invertCaption ? Flag::f_invert_media : Flag(0))
  4264. | (starsPaid ? Flag::f_allow_paid_stars : Flag(0));
  4265. auto &histories = history->owner().histories();
  4266. const auto peer = history->peer;
  4267. album->sent = true;
  4268. histories.sendPreparedMessage(
  4269. history,
  4270. replyTo,
  4271. uint64(0), // randomId
  4272. Data::Histories::PrepareMessage<MTPmessages_SendMultiMedia>(
  4273. MTP_flags(flags),
  4274. peer->input,
  4275. Data::Histories::ReplyToPlaceholder(),
  4276. MTP_vector<MTPInputSingleMedia>(medias),
  4277. MTP_int(album->options.scheduled),
  4278. (sendAs ? sendAs->input : MTP_inputPeerEmpty()),
  4279. Data::ShortcutIdToMTP(_session, album->options.shortcutId),
  4280. MTP_long(album->options.effectId),
  4281. MTP_long(starsPaid)
  4282. ), [=](const MTPUpdates &result, const MTP::Response &response) {
  4283. _sendingAlbums.remove(groupId);
  4284. }, [=](const MTP::Error &error, const MTP::Response &response) {
  4285. if (const auto album = _sendingAlbums.take(groupId)) {
  4286. for (const auto &item : (*album)->items) {
  4287. sendMessageFail(error, peer, item.randomId, item.msgId);
  4288. }
  4289. } else {
  4290. sendMessageFail(error, peer);
  4291. }
  4292. });
  4293. }
  4294. void ApiWrap::reloadContactSignupSilent() {
  4295. if (_contactSignupSilentRequestId) {
  4296. return;
  4297. }
  4298. const auto requestId = request(MTPaccount_GetContactSignUpNotification(
  4299. )).done([=](const MTPBool &result) {
  4300. _contactSignupSilentRequestId = 0;
  4301. const auto silent = mtpIsTrue(result);
  4302. _contactSignupSilent = silent;
  4303. _contactSignupSilentChanges.fire_copy(silent);
  4304. }).fail([=] {
  4305. _contactSignupSilentRequestId = 0;
  4306. }).send();
  4307. _contactSignupSilentRequestId = requestId;
  4308. }
  4309. rpl::producer<bool> ApiWrap::contactSignupSilent() const {
  4310. return _contactSignupSilent
  4311. ? _contactSignupSilentChanges.events_starting_with_copy(
  4312. *_contactSignupSilent)
  4313. : (_contactSignupSilentChanges.events() | rpl::type_erased());
  4314. }
  4315. std::optional<bool> ApiWrap::contactSignupSilentCurrent() const {
  4316. return _contactSignupSilent;
  4317. }
  4318. void ApiWrap::saveContactSignupSilent(bool silent) {
  4319. request(base::take(_contactSignupSilentRequestId)).cancel();
  4320. const auto requestId = request(MTPaccount_SetContactSignUpNotification(
  4321. MTP_bool(silent)
  4322. )).done([=] {
  4323. _contactSignupSilentRequestId = 0;
  4324. _contactSignupSilent = silent;
  4325. _contactSignupSilentChanges.fire_copy(silent);
  4326. }).fail([=] {
  4327. _contactSignupSilentRequestId = 0;
  4328. }).send();
  4329. _contactSignupSilentRequestId = requestId;
  4330. }
  4331. auto ApiWrap::botCommonGroups(not_null<UserData*> bot) const
  4332. -> std::optional<std::vector<not_null<PeerData*>>> {
  4333. const auto i = _botCommonGroups.find(bot);
  4334. return (i != end(_botCommonGroups))
  4335. ? i->second
  4336. : std::optional<std::vector<not_null<PeerData*>>>();
  4337. }
  4338. void ApiWrap::requestBotCommonGroups(
  4339. not_null<UserData*> bot,
  4340. Fn<void()> done) {
  4341. if (_botCommonGroupsRequests.contains(bot)) {
  4342. return;
  4343. }
  4344. _botCommonGroupsRequests.emplace(bot, done);
  4345. const auto finish = [=](std::vector<not_null<PeerData*>> list) {
  4346. _botCommonGroups.emplace(bot, std::move(list));
  4347. if (const auto callback = _botCommonGroupsRequests.take(bot)) {
  4348. (*callback)();
  4349. }
  4350. };
  4351. const auto limit = 100;
  4352. request(MTPmessages_GetCommonChats(
  4353. bot->inputUser,
  4354. MTP_long(0), // max_id
  4355. MTP_int(limit)
  4356. )).done([=](const MTPmessages_Chats &result) {
  4357. const auto chats = result.match([](const auto &data) {
  4358. return &data.vchats().v;
  4359. });
  4360. auto &owner = session().data();
  4361. auto list = std::vector<not_null<PeerData*>>();
  4362. list.reserve(chats->size());
  4363. for (const auto &chat : *chats) {
  4364. if (const auto peer = owner.processChat(chat)) {
  4365. list.push_back(peer);
  4366. }
  4367. }
  4368. finish(std::move(list));
  4369. }).fail([=] {
  4370. finish({});
  4371. }).send();
  4372. }
  4373. void ApiWrap::saveSelfBio(const QString &text) {
  4374. if (_bio.requestId) {
  4375. if (text != _bio.requestedText) {
  4376. request(_bio.requestId).cancel();
  4377. } else {
  4378. return;
  4379. }
  4380. }
  4381. _bio.requestedText = text;
  4382. _bio.requestId = request(MTPaccount_UpdateProfile(
  4383. MTP_flags(MTPaccount_UpdateProfile::Flag::f_about),
  4384. MTPstring(),
  4385. MTPstring(),
  4386. MTP_string(text)
  4387. )).done([=](const MTPUser &result) {
  4388. _bio.requestId = 0;
  4389. _session->data().processUser(result);
  4390. _session->user()->setAbout(_bio.requestedText);
  4391. }).fail([=] {
  4392. _bio.requestId = 0;
  4393. }).send();
  4394. }
  4395. void ApiWrap::registerStatsRequest(MTP::DcId dcId, mtpRequestId id) {
  4396. _statsRequests[dcId].emplace(id);
  4397. }
  4398. void ApiWrap::unregisterStatsRequest(MTP::DcId dcId, mtpRequestId id) {
  4399. const auto i = _statsRequests.find(dcId);
  4400. Assert(i != end(_statsRequests));
  4401. const auto removed = i->second.remove(id);
  4402. Assert(removed);
  4403. if (i->second.empty()) {
  4404. _statsSessionKillTimer.callOnce(kStatsSessionKillTimeout);
  4405. }
  4406. }
  4407. void ApiWrap::checkStatsSessions() {
  4408. for (auto i = begin(_statsRequests); i != end(_statsRequests);) {
  4409. if (i->second.empty()) {
  4410. instance().killSession(
  4411. MTP::ShiftDcId(i->first, MTP::kStatsDcShift));
  4412. i = _statsRequests.erase(i);
  4413. } else {
  4414. ++i;
  4415. }
  4416. }
  4417. }
  4418. Api::Authorizations &ApiWrap::authorizations() {
  4419. return *_authorizations;
  4420. }
  4421. Api::AttachedStickers &ApiWrap::attachedStickers() {
  4422. return *_attachedStickers;
  4423. }
  4424. Api::BlockedPeers &ApiWrap::blockedPeers() {
  4425. return *_blockedPeers;
  4426. }
  4427. Api::CloudPassword &ApiWrap::cloudPassword() {
  4428. return *_cloudPassword;
  4429. }
  4430. Api::SelfDestruct &ApiWrap::selfDestruct() {
  4431. return *_selfDestruct;
  4432. }
  4433. Api::SensitiveContent &ApiWrap::sensitiveContent() {
  4434. return *_sensitiveContent;
  4435. }
  4436. Api::GlobalPrivacy &ApiWrap::globalPrivacy() {
  4437. return *_globalPrivacy;
  4438. }
  4439. Api::UserPrivacy &ApiWrap::userPrivacy() {
  4440. return *_userPrivacy;
  4441. }
  4442. Api::InviteLinks &ApiWrap::inviteLinks() {
  4443. return *_inviteLinks;
  4444. }
  4445. Api::ChatLinks &ApiWrap::chatLinks() {
  4446. return *_chatLinks;
  4447. }
  4448. Api::ViewsManager &ApiWrap::views() {
  4449. return *_views;
  4450. }
  4451. Api::ConfirmPhone &ApiWrap::confirmPhone() {
  4452. return *_confirmPhone;
  4453. }
  4454. Api::PeerPhoto &ApiWrap::peerPhoto() {
  4455. return *_peerPhoto;
  4456. }
  4457. Api::Polls &ApiWrap::polls() {
  4458. return *_polls;
  4459. }
  4460. Api::ChatParticipants &ApiWrap::chatParticipants() {
  4461. return *_chatParticipants;
  4462. }
  4463. Api::UnreadThings &ApiWrap::unreadThings() {
  4464. return *_unreadThings;
  4465. }
  4466. Api::Ringtones &ApiWrap::ringtones() {
  4467. return *_ringtones;
  4468. }
  4469. Api::Transcribes &ApiWrap::transcribes() {
  4470. return *_transcribes;
  4471. }
  4472. Api::Premium &ApiWrap::premium() {
  4473. return *_premium;
  4474. }
  4475. Api::Usernames &ApiWrap::usernames() {
  4476. return *_usernames;
  4477. }
  4478. Api::Websites &ApiWrap::websites() {
  4479. return *_websites;
  4480. }
  4481. Api::PeerColors &ApiWrap::peerColors() {
  4482. return *_peerColors;
  4483. }