apiwrap.cpp 140 KB

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