apiwrap.cpp 136 KB

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