data_session.cpp 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912
  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 "data/data_session.h"
  8. #include "main/main_session.h"
  9. #include "main/main_session_settings.h"
  10. #include "main/main_app_config.h"
  11. #include "apiwrap.h"
  12. #include "mainwidget.h"
  13. #include "api/api_bot.h"
  14. #include "api/api_premium.h"
  15. #include "api/api_text_entities.h"
  16. #include "api/api_user_names.h"
  17. #include "chat_helpers/stickers_lottie.h"
  18. #include "core/application.h"
  19. #include "core/core_settings.h"
  20. #include "core/mime_type.h" // Core::IsMimeSticker
  21. #include "ui/image/image_location_factory.h" // Images::FromPhotoSize
  22. #include "ui/text/format_values.h" // Ui::FormatPhone
  23. #include "export/export_manager.h"
  24. #include "export/view/export_view_panel_controller.h"
  25. #include "mtproto/mtproto_config.h"
  26. #include "window/notifications_manager.h"
  27. #include "history/history.h"
  28. #include "history/history_item_components.h"
  29. #include "history/view/media/history_view_media.h"
  30. #include "history/view/history_view_element.h"
  31. #include "inline_bots/inline_bot_layout_item.h"
  32. #include "storage/storage_account.h"
  33. #include "storage/storage_encrypted_file.h"
  34. #include "media/player/media_player_instance.h" // instance()->play()
  35. #include "media/audio/media_audio.h"
  36. #include "boxes/abstract_box.h"
  37. #include "passport/passport_form_controller.h"
  38. #include "iv/iv_data.h"
  39. #include "lang/lang_keys.h" // tr::lng_deleted(tr::now) in user name
  40. #include "data/business/data_business_chatbots.h"
  41. #include "data/business/data_business_info.h"
  42. #include "data/business/data_shortcut_messages.h"
  43. #include "data/components/scheduled_messages.h"
  44. #include "data/components/sponsored_messages.h"
  45. #include "data/stickers/data_stickers.h"
  46. #include "data/notify/data_notify_settings.h"
  47. #include "data/data_bot_app.h"
  48. #include "data/data_changes.h"
  49. #include "data/data_group_call.h"
  50. #include "data/data_folder.h"
  51. #include "data/data_channel.h"
  52. #include "data/data_chat.h"
  53. #include "data/data_user.h"
  54. #include "data/data_file_origin.h"
  55. #include "data/data_download_manager.h"
  56. #include "data/data_web_page.h"
  57. #include "data/data_game.h"
  58. #include "data/data_poll.h"
  59. #include "data/data_replies_list.h"
  60. #include "data/data_chat_filters.h"
  61. #include "data/data_send_action.h"
  62. #include "data/data_message_reactions.h"
  63. #include "data/data_emoji_statuses.h"
  64. #include "data/data_forum_icons.h"
  65. #include "data/data_cloud_themes.h"
  66. #include "data/data_saved_messages.h"
  67. #include "data/data_saved_sublist.h"
  68. #include "data/data_stories.h"
  69. #include "data/data_streaming.h"
  70. #include "data/data_media_rotation.h"
  71. #include "data/data_histories.h"
  72. #include "data/data_peer_values.h"
  73. #include "data/data_premium_limits.h"
  74. #include "data/data_forum.h"
  75. #include "data/data_forum_topic.h"
  76. #include "base/platform/base_platform_info.h"
  77. #include "base/unixtime.h"
  78. #include "base/call_delayed.h"
  79. #include "base/random.h"
  80. #include "spellcheck/spellcheck_highlight_syntax.h"
  81. namespace Data {
  82. namespace {
  83. using ViewElement = HistoryView::Element;
  84. // s: box 100x100
  85. // m: box 320x320
  86. // x: box 800x800
  87. // y: box 1280x1280
  88. // w: box 2560x2560 // if loading this fix HistoryPhoto::updateFrom
  89. // a: crop 160x160
  90. // b: crop 320x320
  91. // c: crop 640x640
  92. // d: crop 1280x1280
  93. const auto InlineLevels = "i"_q;
  94. const auto SmallLevels = "sa"_q;
  95. const auto ThumbnailLevels = "mbsa"_q;
  96. const auto LargeLevels = "ydxcwmbsa"_q;
  97. void CheckForSwitchInlineButton(not_null<HistoryItem*> item) {
  98. if (item->out() || !item->hasSwitchInlineButton()) {
  99. return;
  100. }
  101. if (const auto user = item->history()->peer->asUser()) {
  102. if (!user->isBot() || !user->botInfo->inlineReturnTo.key) {
  103. return;
  104. }
  105. if (const auto markup = item->Get<HistoryMessageReplyMarkup>()) {
  106. for (const auto &row : markup->data.rows) {
  107. for (const auto &button : row) {
  108. using ButtonType = HistoryMessageMarkupButton::Type;
  109. if (button.type == ButtonType::SwitchInline) {
  110. const auto session = &item->history()->session();
  111. const auto &windows = session->windows();
  112. if (!windows.empty()) {
  113. Api::SwitchInlineBotButtonReceived(
  114. windows.front(),
  115. button.data);
  116. }
  117. return;
  118. }
  119. }
  120. }
  121. }
  122. }
  123. }
  124. [[nodiscard]] InlineImageLocation FindInlineThumbnail(
  125. const QVector<MTPPhotoSize> &sizes) {
  126. const auto i = ranges::find(
  127. sizes,
  128. mtpc_photoStrippedSize,
  129. &MTPPhotoSize::type);
  130. const auto j = ranges::find(
  131. sizes,
  132. mtpc_photoPathSize,
  133. &MTPPhotoSize::type);
  134. return (i != sizes.end())
  135. ? InlineImageLocation{ i->c_photoStrippedSize().vbytes().v, false }
  136. : (j != sizes.end())
  137. ? InlineImageLocation{ j->c_photoPathSize().vbytes().v, true }
  138. : InlineImageLocation();
  139. }
  140. [[nodiscard]] InlineImageLocation FindDocumentInlineThumbnail(
  141. const MTPDdocument &data) {
  142. return FindInlineThumbnail(data.vthumbs().value_or_empty());
  143. }
  144. [[nodiscard]] MTPPhotoSize FindDocumentThumbnail(const MTPDdocument &data) {
  145. const auto area = [](const MTPPhotoSize &size) {
  146. static constexpr auto kInvalid = 0;
  147. return size.match([](const MTPDphotoSizeEmpty &) {
  148. return kInvalid;
  149. }, [](const MTPDphotoStrippedSize &) {
  150. return kInvalid;
  151. }, [](const MTPDphotoPathSize &) {
  152. return kInvalid;
  153. }, [](const auto &data) {
  154. return (data.vw().v * data.vh().v);
  155. });
  156. };
  157. const auto thumbs = data.vthumbs();
  158. if (!thumbs) {
  159. return MTP_photoSizeEmpty(MTP_string());
  160. }
  161. const auto &list = thumbs->v;
  162. const auto i = ranges::max_element(list, std::less<>(), area);
  163. return (i != list.end() && area(*i) > 0)
  164. ? (*i)
  165. : MTPPhotoSize(MTP_photoSizeEmpty(MTP_string()));
  166. }
  167. [[nodiscard]] std::optional<MTPVideoSize> FindDocumentVideoThumbnail(
  168. const MTPDdocument &data) {
  169. const auto area = [](const MTPVideoSize &size) {
  170. return size.match([](const MTPDvideoSize &data) {
  171. return (data.vw().v * data.vh().v);
  172. }, [](const MTPDvideoSizeEmojiMarkup &) {
  173. return 0;
  174. }, [](const MTPDvideoSizeStickerMarkup &) {
  175. return 0;
  176. });
  177. };
  178. const auto thumbs = data.vvideo_thumbs();
  179. if (!thumbs) {
  180. return std::nullopt;
  181. }
  182. const auto &list = thumbs->v;
  183. const auto i = ranges::max_element(list, std::less<>(), area);
  184. return (i != list.end() && area(*i) > 0)
  185. ? std::make_optional(*i)
  186. : std::nullopt;
  187. }
  188. [[nodiscard]] QByteArray FindPhotoInlineThumbnail(const MTPDphoto &data) {
  189. const auto thumbnail = FindInlineThumbnail(data.vsizes().v);
  190. return !thumbnail.isPath ? thumbnail.bytes : QByteArray();
  191. }
  192. [[nodiscard]] int VideoStartTime(const MTPDvideoSize &data) {
  193. return int(
  194. std::clamp(
  195. std::floor(data.vvideo_start_ts().value_or_empty() * 1000),
  196. 0.,
  197. double(std::numeric_limits<int>::max())));
  198. }
  199. } // namespace
  200. Session::Session(not_null<Main::Session*> session)
  201. : _session(session)
  202. , _cache(Core::App().databases().get(
  203. _session->local().cachePath(),
  204. _session->local().cacheSettings()))
  205. , _bigFileCache(Core::App().databases().get(
  206. _session->local().cacheBigFilePath(),
  207. _session->local().cacheBigFileSettings()))
  208. , _groupFreeTranscribeLevel(session->appConfig().value(
  209. ) | rpl::map([limits = Data::LevelLimits(session)] {
  210. return limits.groupTranscribeLevelMin();
  211. }))
  212. , _chatsList(
  213. session,
  214. FilterId(),
  215. maxPinnedChatsLimitValue(nullptr))
  216. , _contactsList(Dialogs::SortMode::Name)
  217. , _contactsNoChatsList(Dialogs::SortMode::Name)
  218. , _ttlCheckTimer([=] { checkTTLs(); })
  219. , _selfDestructTimer([=] { checkSelfDestructItems(); })
  220. , _pollsClosingTimer([=] { checkPollsClosings(); })
  221. , _watchForOfflineTimer([=] { checkLocalUsersWentOffline(); })
  222. , _groups(this)
  223. , _chatsFilters(std::make_unique<ChatFilters>(this))
  224. , _cloudThemes(std::make_unique<CloudThemes>(session))
  225. , _sendActionManager(std::make_unique<SendActionManager>())
  226. , _streaming(std::make_unique<Streaming>(this))
  227. , _mediaRotation(std::make_unique<MediaRotation>())
  228. , _histories(std::make_unique<Histories>(this))
  229. , _stickers(std::make_unique<Stickers>(this))
  230. , _reactions(std::make_unique<Reactions>(this))
  231. , _emojiStatuses(std::make_unique<EmojiStatuses>(this))
  232. , _forumIcons(std::make_unique<ForumIcons>(this))
  233. , _notifySettings(std::make_unique<NotifySettings>(this))
  234. , _customEmojiManager(std::make_unique<CustomEmojiManager>(this))
  235. , _stories(std::make_unique<Stories>(this))
  236. , _savedMessages(std::make_unique<SavedMessages>(this))
  237. , _chatbots(std::make_unique<Chatbots>(this))
  238. , _businessInfo(std::make_unique<BusinessInfo>(this))
  239. , _shortcutMessages(std::make_unique<ShortcutMessages>(this)) {
  240. _cache->open(_session->local().cacheKey());
  241. _bigFileCache->open(_session->local().cacheBigFileKey());
  242. if constexpr (Platform::IsLinux()) {
  243. const auto wasVersion = _session->local().oldMapVersion();
  244. if (wasVersion >= 1007011 && wasVersion < 1007015) {
  245. _bigFileCache->clear();
  246. _cache->clearByTag(Data::kImageCacheTag);
  247. }
  248. }
  249. setupMigrationViewer();
  250. setupChannelLeavingViewer();
  251. setupPeerNameViewer();
  252. setupUserIsContactViewer();
  253. _chatsList.unreadStateChanges(
  254. ) | rpl::start_with_next([=] {
  255. notifyUnreadBadgeChanged();
  256. }, _lifetime);
  257. _chatsFilters->changed(
  258. ) | rpl::start_with_next([=] {
  259. const auto enabled = _chatsFilters->has();
  260. if (enabled != session->settings().dialogsFiltersEnabled()) {
  261. session->settings().setDialogsFiltersEnabled(enabled);
  262. session->saveSettingsDelayed();
  263. }
  264. }, _lifetime);
  265. _reactions->myTagRenamed(
  266. ) | rpl::start_with_next([=](const ReactionId &id) {
  267. const auto i = _viewsByTag.find(id);
  268. if (i != end(_viewsByTag)) {
  269. for (const auto &view : i->second) {
  270. notifyItemDataChange(view->data());
  271. }
  272. }
  273. }, _lifetime);
  274. Spellchecker::HighlightReady(
  275. ) | rpl::start_with_next([=](uint64 processId) {
  276. highlightProcessDone(processId);
  277. }, _lifetime);
  278. subscribeForTopicRepliesLists();
  279. crl::on_main(_session, [=] {
  280. AmPremiumValue(
  281. _session
  282. ) | rpl::start_with_next([=] {
  283. for (const auto &[document, items] : _documentItems) {
  284. if (document->isVoiceMessage()) {
  285. for (const auto &item : items) {
  286. requestItemResize(item);
  287. }
  288. }
  289. }
  290. }, _lifetime);
  291. _stories->loadMore(Data::StorySourcesList::NotHidden);
  292. });
  293. session->appConfig().ignoredRestrictionReasonsChanges(
  294. ) | rpl::start_with_next([=](std::vector<QString> &&changed) {
  295. auto refresh = std::vector<not_null<const HistoryItem*>>();
  296. for (const auto &[item, reasons] : _possiblyRestricted) {
  297. for (const auto &reason : changed) {
  298. if (reasons.contains(reason)) {
  299. refresh.push_back(item);
  300. break;
  301. }
  302. }
  303. }
  304. for (const auto &item : refresh) {
  305. requestItemViewRefresh(item);
  306. }
  307. }, _lifetime);
  308. }
  309. void Session::subscribeForTopicRepliesLists() {
  310. repliesReadTillUpdates(
  311. ) | rpl::start_with_next([=](const RepliesReadTillUpdate &update) {
  312. if (const auto peer = peerLoaded(update.id.peer)) {
  313. if (const auto topic = peer->forumTopicFor(update.id.msg)) {
  314. topic->replies()->apply(update);
  315. }
  316. }
  317. }, _lifetime);
  318. session().changes().messageUpdates(
  319. MessageUpdate::Flag::NewAdded
  320. | MessageUpdate::Flag::NewMaybeAdded
  321. | MessageUpdate::Flag::ReplyToTopAdded
  322. | MessageUpdate::Flag::Destroyed
  323. ) | rpl::start_with_next([=](const MessageUpdate &update) {
  324. if (const auto topic = update.item->topic()) {
  325. topic->replies()->apply(update);
  326. }
  327. }, _lifetime);
  328. session().changes().topicUpdates(
  329. TopicUpdate::Flag::Creator
  330. ) | rpl::start_with_next([=](const TopicUpdate &update) {
  331. update.topic->replies()->apply(update);
  332. }, _lifetime);
  333. channelDifferenceTooLong(
  334. ) | rpl::start_with_next([=](not_null<ChannelData*> channel) {
  335. if (const auto forum = channel->forum()) {
  336. forum->enumerateTopics([](not_null<ForumTopic*> topic) {
  337. topic->replies()->applyDifferenceTooLong();
  338. });
  339. }
  340. }, _lifetime);
  341. }
  342. void Session::clear() {
  343. // Optimization: clear notifications before destroying items.
  344. Core::App().notifications().clearFromSession(_session);
  345. // We must clear all forums before clearing customEmojiManager.
  346. // Because in Data::ForumTopic an Ui::Text::CustomEmoji is cached.
  347. auto forums = base::flat_set<not_null<ChannelData*>>();
  348. for (const auto &[peerId, peer] : _peers) {
  349. if (const auto channel = peer->asChannel()) {
  350. if (channel->isForum()) {
  351. forums.emplace(channel);
  352. }
  353. }
  354. }
  355. for (const auto &channel : forums) {
  356. channel->setFlags(channel->flags() & ~ChannelDataFlag::Forum);
  357. }
  358. _sendActionManager->clear();
  359. _histories->unloadAll();
  360. _shortcutMessages = nullptr;
  361. _session->scheduledMessages().clear();
  362. _session->sponsoredMessages().clear();
  363. _dependentMessages.clear();
  364. base::take(_messages);
  365. base::take(_nonChannelMessages);
  366. _messageByRandomId.clear();
  367. _sentMessagesData.clear();
  368. cSetRecentInlineBots(RecentInlineBots());
  369. cSetRecentStickers(RecentStickerPack());
  370. HistoryView::Element::ClearGlobal();
  371. _contactsNoChatsList.clear();
  372. _contactsList.clear();
  373. _chatsList.clear();
  374. for (const auto &[id, folder] : _folders) {
  375. folder->clearChatsList();
  376. }
  377. _chatsFilters->clear();
  378. _histories->clearAll();
  379. _webpages.clear();
  380. _locations.clear();
  381. _polls.clear();
  382. _games.clear();
  383. _documents.clear();
  384. _photos.clear();
  385. }
  386. void Session::keepAlive(std::shared_ptr<PhotoMedia> media) {
  387. // NB! This allows PhotoMedia to outlive Main::Session!
  388. // In case this is a problem this code should be rewritten.
  389. crl::on_main(&session(), [media = std::move(media)]{});
  390. }
  391. void Session::keepAlive(std::shared_ptr<DocumentMedia> media) {
  392. // NB! This allows DocumentMedia to outlive Main::Session!
  393. // In case this is a problem this code should be rewritten.
  394. crl::on_main(&session(), [media = std::move(media)] {});
  395. }
  396. not_null<PeerData*> Session::peer(PeerId id) {
  397. const auto i = _peers.find(id);
  398. if (i != _peers.cend()) {
  399. return i->second.get();
  400. }
  401. auto result = [&]() -> std::unique_ptr<PeerData> {
  402. if (peerIsUser(id)) {
  403. return std::make_unique<UserData>(this, id);
  404. } else if (peerIsChat(id)) {
  405. return std::make_unique<ChatData>(this, id);
  406. } else if (peerIsChannel(id)) {
  407. return std::make_unique<ChannelData>(this, id);
  408. }
  409. Unexpected("Peer id type.");
  410. }();
  411. result->input = MTPinputPeer(MTP_inputPeerEmpty());
  412. return _peers.emplace(id, std::move(result)).first->second.get();
  413. }
  414. not_null<UserData*> Session::user(UserId id) {
  415. return peer(peerFromUser(id))->asUser();
  416. }
  417. not_null<ChatData*> Session::chat(ChatId id) {
  418. return peer(peerFromChat(id))->asChat();
  419. }
  420. not_null<ChannelData*> Session::channel(ChannelId id) {
  421. return peer(peerFromChannel(id))->asChannel();
  422. }
  423. PeerData *Session::peerLoaded(PeerId id) const {
  424. const auto i = _peers.find(id);
  425. if (i == end(_peers)) {
  426. return nullptr;
  427. } else if (!i->second->isLoaded()) {
  428. return nullptr;
  429. }
  430. return i->second.get();
  431. }
  432. UserData *Session::userLoaded(UserId id) const {
  433. if (const auto peer = peerLoaded(peerFromUser(id))) {
  434. return peer->asUser();
  435. }
  436. return nullptr;
  437. }
  438. ChatData *Session::chatLoaded(ChatId id) const {
  439. if (const auto peer = peerLoaded(peerFromChat(id))) {
  440. return peer->asChat();
  441. }
  442. return nullptr;
  443. }
  444. ChannelData *Session::channelLoaded(ChannelId id) const {
  445. if (const auto peer = peerLoaded(peerFromChannel(id))) {
  446. return peer->asChannel();
  447. }
  448. return nullptr;
  449. }
  450. not_null<UserData*> Session::processUser(const MTPUser &data) {
  451. const auto result = user(data.match([](const auto &data) {
  452. return data.vid().v;
  453. }));
  454. auto minimal = false;
  455. const MTPUserStatus *status = nullptr;
  456. const MTPUserStatus emptyStatus = MTP_userStatusEmpty();
  457. using UpdateFlag = PeerUpdate::Flag;
  458. auto flags = UpdateFlag::None | UpdateFlag::None;
  459. data.match([&](const MTPDuserEmpty &data) {
  460. const auto canShareThisContact = result->canShareThisContactFast();
  461. result->input = MTP_inputPeerUser(data.vid(), MTP_long(0));
  462. result->inputUser = MTP_inputUser(data.vid(), MTP_long(0));
  463. result->setName(tr::lng_deleted(tr::now), QString(), QString(), QString());
  464. result->setPhoto(MTP_userProfilePhotoEmpty());
  465. result->setFlags(UserDataFlag::Deleted);
  466. if (!result->phone().isEmpty()) {
  467. result->setPhone(QString());
  468. flags |= UpdateFlag::PhoneNumber;
  469. }
  470. result->setBotInfoVersion(-1);
  471. status = &emptyStatus;
  472. result->setIsContact(false);
  473. if (canShareThisContact != result->canShareThisContactFast()) {
  474. flags |= UpdateFlag::CanShareContact;
  475. }
  476. }, [&](const MTPDuser &data) {
  477. minimal = data.is_min();
  478. const auto canShareThisContact = result->canShareThisContactFast();
  479. using Flag = UserDataFlag;
  480. const auto flagsMask = Flag::Deleted
  481. | Flag::Verified
  482. | Flag::Scam
  483. | Flag::Fake
  484. | Flag::BotInlineGeo
  485. | Flag::Premium
  486. | Flag::Support
  487. | Flag::HasRequirePremiumToWrite
  488. | Flag::HasStarsPerMessage
  489. | Flag::MessageMoneyRestrictionsKnown
  490. | (!minimal
  491. ? Flag::Contact
  492. | Flag::MutualContact
  493. | Flag::DiscardMinPhoto
  494. | Flag::StoriesHidden
  495. : Flag());
  496. const auto hasRequirePremiumToWrite
  497. = data.is_contact_require_premium();
  498. const auto hasStarsPerMessage
  499. = data.vsend_paid_messages_stars().has_value();
  500. if (!hasStarsPerMessage) {
  501. result->setStarsPerMessage(0);
  502. }
  503. const auto storiesState = minimal
  504. ? std::optional<Data::Stories::PeerSourceState>()
  505. : data.is_stories_unavailable()
  506. ? Data::Stories::PeerSourceState()
  507. : !data.vstories_max_id()
  508. ? std::optional<Data::Stories::PeerSourceState>()
  509. : stories().peerSourceState(result, data.vstories_max_id()->v);
  510. const auto flagsSet = (data.is_deleted() ? Flag::Deleted : Flag())
  511. | (data.is_verified() ? Flag::Verified : Flag())
  512. | (data.is_scam() ? Flag::Scam : Flag())
  513. | (data.is_fake() ? Flag::Fake : Flag())
  514. | (data.is_bot_inline_geo() ? Flag::BotInlineGeo : Flag())
  515. | (data.is_premium() ? Flag::Premium : Flag())
  516. | (data.is_support() ? Flag::Support : Flag())
  517. | (hasRequirePremiumToWrite
  518. ? (Flag::HasRequirePremiumToWrite
  519. | (result->hasRequirePremiumToWrite()
  520. ? (result->messageMoneyRestrictionsKnown()
  521. ? Flag::MessageMoneyRestrictionsKnown
  522. : Flag())
  523. : Flag()))
  524. : Flag())
  525. | (hasStarsPerMessage
  526. ? (Flag::HasStarsPerMessage
  527. | (result->hasStarsPerMessage()
  528. ? (result->messageMoneyRestrictionsKnown()
  529. ? Flag::MessageMoneyRestrictionsKnown
  530. : Flag())
  531. : Flag()))
  532. : Flag())
  533. | ((!hasRequirePremiumToWrite && !hasStarsPerMessage)
  534. ? Flag::MessageMoneyRestrictionsKnown
  535. : Flag())
  536. | (!minimal
  537. ? (data.is_contact() ? Flag::Contact : Flag())
  538. | (data.is_mutual_contact() ? Flag::MutualContact : Flag())
  539. | (data.is_apply_min_photo()
  540. ? Flag()
  541. : Flag::DiscardMinPhoto)
  542. | (data.is_stories_hidden() ? Flag::StoriesHidden : Flag())
  543. : Flag());
  544. result->setFlags((result->flags() & ~flagsMask) | flagsSet);
  545. result->setBotVerifyDetailsIcon(
  546. data.vbot_verification_icon().value_or_empty());
  547. if (minimal) {
  548. if (result->input.type() == mtpc_inputPeerEmpty) {
  549. result->input = MTP_inputPeerUser(
  550. data.vid(),
  551. MTP_long(data.vaccess_hash().value_or_empty()));
  552. }
  553. if (result->inputUser.type() == mtpc_inputUserEmpty) {
  554. result->inputUser = MTP_inputUser(
  555. data.vid(),
  556. MTP_long(data.vaccess_hash().value_or_empty()));
  557. }
  558. } else {
  559. if (storiesState) {
  560. result->setStoriesState(!storiesState->maxId
  561. ? UserData::StoriesState::None
  562. : (storiesState->maxId > storiesState->readTill)
  563. ? UserData::StoriesState::HasUnread
  564. : UserData::StoriesState::HasRead);
  565. }
  566. if (data.is_self()) {
  567. result->input = MTP_inputPeerSelf();
  568. result->inputUser = MTP_inputUserSelf();
  569. } else if (const auto accessHash = data.vaccess_hash()) {
  570. result->input = MTP_inputPeerUser(data.vid(), *accessHash);
  571. result->inputUser = MTP_inputUser(data.vid(), *accessHash);
  572. } else {
  573. result->input = MTP_inputPeerUser(data.vid(), MTP_long(result->accessHash()));
  574. result->inputUser = MTP_inputUser(data.vid(), MTP_long(result->accessHash()));
  575. }
  576. result->setUnavailableReasons(Data::UnavailableReason::Extract(
  577. data.vrestriction_reason()));
  578. }
  579. if (data.is_deleted()) {
  580. if (!result->phone().isEmpty()) {
  581. result->setPhone(QString());
  582. flags |= UpdateFlag::PhoneNumber;
  583. }
  584. result->setName(tr::lng_deleted(tr::now), QString(), QString(), QString());
  585. result->setPhoto(MTP_userProfilePhotoEmpty());
  586. status = &emptyStatus;
  587. } else {
  588. // apply first_name and last_name from minimal user only if we don't have
  589. // local values for first name and last name already, otherwise skip
  590. const auto noLocalName = result->firstName.isEmpty()
  591. && result->lastName.isEmpty();
  592. const auto fname = (!minimal || noLocalName)
  593. ? TextUtilities::SingleLine(
  594. qs(data.vfirst_name().value_or_empty()))
  595. : result->firstName;
  596. const auto lname = (!minimal || noLocalName)
  597. ? TextUtilities::SingleLine(
  598. qs(data.vlast_name().value_or_empty()))
  599. : result->lastName;
  600. const auto phone = minimal
  601. ? result->phone()
  602. : qs(data.vphone().value_or_empty());
  603. const auto uname = minimal
  604. ? result->username()
  605. : TextUtilities::SingleLine(
  606. qs(data.vusername().value_or_empty()));
  607. const auto phoneChanged = (result->phone() != phone);
  608. if (phoneChanged) {
  609. result->setPhone(phone);
  610. flags |= UpdateFlag::PhoneNumber;
  611. }
  612. const auto nameChanged = (result->firstName != fname)
  613. || (result->lastName != lname);
  614. auto showPhone = !result->isServiceUser()
  615. && !data.is_support()
  616. && !data.is_self()
  617. && !data.is_contact()
  618. && !data.is_mutual_contact();
  619. auto showPhoneChanged = !result->isServiceUser()
  620. && !data.is_self()
  621. && ((showPhone && result->isContact())
  622. || (!showPhone
  623. && !result->isContact()
  624. && !result->phone().isEmpty()));
  625. if (minimal) {
  626. showPhoneChanged = false;
  627. showPhone = !result->isServiceUser()
  628. && !result->isContact()
  629. && !result->phone().isEmpty()
  630. && (result->id != _session->userPeerId());
  631. }
  632. // see also Serialize::readPeer
  633. const auto pname = (showPhoneChanged || phoneChanged || nameChanged)
  634. ? ((showPhone && !phone.isEmpty())
  635. ? Ui::FormatPhone(phone)
  636. : QString())
  637. : result->nameOrPhone;
  638. result->setName(fname, lname, pname, uname);
  639. if (!minimal || result->applyMinPhoto()) {
  640. if (const auto photo = data.vphoto()) {
  641. result->setPhoto(*photo);
  642. } else {
  643. result->setPhoto(MTP_userProfilePhotoEmpty());
  644. }
  645. }
  646. if (const auto accessHash = data.vaccess_hash()) {
  647. result->setAccessHash(accessHash->v);
  648. }
  649. status = data.vstatus();
  650. if (!minimal) {
  651. const auto newUsername = uname;
  652. const auto newUsernames = data.vusernames()
  653. ? Api::Usernames::FromTL(*data.vusernames())
  654. : !newUsername.isEmpty()
  655. ? Data::Usernames{{ newUsername, true, true }}
  656. : Data::Usernames();
  657. result->setUsernames(newUsernames);
  658. }
  659. }
  660. if (const auto &status = data.vemoji_status()) {
  661. result->setEmojiStatus(*status);
  662. } else {
  663. result->setEmojiStatus(EmojiStatusId());
  664. }
  665. if (!minimal) {
  666. if (const auto botInfoVersion = data.vbot_info_version()) {
  667. result->setBotInfoVersion(botInfoVersion->v);
  668. result->botInfo->readsAllHistory = data.is_bot_chat_history();
  669. if (result->botInfo->cantJoinGroups != data.is_bot_nochats()) {
  670. result->botInfo->cantJoinGroups = data.is_bot_nochats();
  671. flags |= UpdateFlag::BotCanBeInvited;
  672. }
  673. if (const auto placeholder = data.vbot_inline_placeholder()) {
  674. result->botInfo->inlinePlaceholder = '_' + qs(*placeholder);
  675. } else {
  676. result->botInfo->inlinePlaceholder = QString();
  677. }
  678. result->botInfo->supportsAttachMenu = data.is_bot_attach_menu();
  679. result->botInfo->supportsBusiness = data.is_bot_business();
  680. result->botInfo->canEditInformation = data.is_bot_can_edit();
  681. result->botInfo->activeUsers = data.vbot_active_users().value_or_empty();
  682. result->botInfo->hasMainApp = data.is_bot_has_main_app();
  683. } else {
  684. result->setBotInfoVersion(-1);
  685. }
  686. result->setIsContact(data.is_contact()
  687. || data.is_mutual_contact());
  688. }
  689. if (canShareThisContact != result->canShareThisContactFast()) {
  690. flags |= UpdateFlag::CanShareContact;
  691. }
  692. if (result->changeColor(data.vcolor())) {
  693. flags |= UpdateFlag::Color;
  694. if (result->isMinimalLoaded()) {
  695. _peerDecorationsUpdated.fire_copy(result);
  696. }
  697. }
  698. });
  699. if (minimal) {
  700. if (!result->isMinimalLoaded()) {
  701. result->setLoadedStatus(PeerData::LoadedStatus::Minimal);
  702. }
  703. } else if (!result->isLoaded()
  704. && (!result->isSelf() || !result->phone().isEmpty())) {
  705. result->setLoadedStatus(PeerData::LoadedStatus::Normal);
  706. }
  707. if (!minimal) {
  708. const auto lastseen = status
  709. ? LastseenFromMTP(*status, result->lastseen())
  710. : Data::LastseenStatus::LongAgo(false);
  711. if (result->updateLastseen(lastseen)) {
  712. flags |= UpdateFlag::OnlineStatus;
  713. }
  714. }
  715. if (flags) {
  716. session().changes().peerUpdated(result, flags);
  717. }
  718. return result;
  719. }
  720. not_null<PeerData*> Session::processChat(const MTPChat &data) {
  721. const auto result = data.match([&](const MTPDchat &data) {
  722. return peer(peerFromChat(data.vid().v));
  723. }, [&](const MTPDchatForbidden &data) {
  724. return peer(peerFromChat(data.vid().v));
  725. }, [&](const MTPDchatEmpty &data) {
  726. return peer(peerFromChat(data.vid().v));
  727. }, [&](const MTPDchannel &data) {
  728. return peer(peerFromChannel(data.vid().v));
  729. }, [&](const MTPDchannelForbidden &data) {
  730. return peer(peerFromChannel(data.vid().v));
  731. });
  732. auto minimal = false;
  733. using UpdateFlag = Data::PeerUpdate::Flag;
  734. auto flags = UpdateFlag::None | UpdateFlag::None;
  735. data.match([&](const MTPDchat &data) {
  736. const auto chat = result->asChat();
  737. const auto canAddMembers = chat->canAddMembers();
  738. if (chat->version() < data.vversion().v) {
  739. chat->setVersion(data.vversion().v);
  740. chat->invalidateParticipants();
  741. }
  742. chat->input = MTP_inputPeerChat(data.vid());
  743. chat->setName(qs(data.vtitle()));
  744. chat->setPhoto(data.vphoto());
  745. chat->date = data.vdate().v;
  746. if (const auto rights = data.vadmin_rights()) {
  747. chat->setAdminRights(ChatAdminRightsInfo(*rights).flags);
  748. } else {
  749. chat->setAdminRights(ChatAdminRights());
  750. }
  751. if (const auto rights = data.vdefault_banned_rights()) {
  752. chat->setDefaultRestrictions(ChatRestrictionsInfo(*rights).flags);
  753. } else {
  754. chat->setDefaultRestrictions(ChatRestrictions());
  755. }
  756. if (const auto migratedTo = data.vmigrated_to()) {
  757. migratedTo->match([&](const MTPDinputChannel &input) {
  758. const auto channel = this->channel(input.vchannel_id().v);
  759. channel->addFlags(ChannelDataFlag::Megagroup);
  760. if (!channel->access) {
  761. channel->setAccessHash(input.vaccess_hash().v);
  762. }
  763. ApplyMigration(chat, channel);
  764. }, [](const MTPDinputChannelFromMessage &) {
  765. LOG(("API Error: "
  766. "migrated_to contains channel from message."));
  767. }, [](const MTPDinputChannelEmpty &) {
  768. });
  769. }
  770. using Flag = ChatDataFlag;
  771. const auto flagsMask = Flag::Left
  772. | Flag::Creator
  773. | Flag::Deactivated
  774. | Flag::Forbidden
  775. | Flag::CallActive
  776. | Flag::CallNotEmpty
  777. | Flag::NoForwards;
  778. const auto flagsSet = (data.is_left() ? Flag::Left : Flag())
  779. | (data.is_creator() ? Flag::Creator : Flag())
  780. | (data.is_deactivated() ? Flag::Deactivated : Flag())
  781. | (data.is_call_active() ? Flag::CallActive : Flag())
  782. | ((data.is_call_not_empty()
  783. || (chat->groupCall()
  784. && chat->groupCall()->fullCount() > 0))
  785. ? Flag::CallNotEmpty
  786. : Flag())
  787. | (data.is_noforwards() ? Flag::NoForwards : Flag());
  788. chat->setFlags((chat->flags() & ~flagsMask) | flagsSet);
  789. chat->count = data.vparticipants_count().v;
  790. if (canAddMembers != chat->canAddMembers()) {
  791. flags |= UpdateFlag::Rights;
  792. }
  793. }, [&](const MTPDchatForbidden &data) {
  794. const auto chat = result->asChat();
  795. const auto canAddMembers = chat->canAddMembers();
  796. chat->input = MTP_inputPeerChat(data.vid());
  797. chat->setName(qs(data.vtitle()));
  798. chat->setPhoto(MTP_chatPhotoEmpty());
  799. chat->date = 0;
  800. chat->count = -1;
  801. chat->invalidateParticipants();
  802. chat->setFlags(ChatDataFlag::Forbidden);
  803. chat->setAdminRights(ChatAdminRights());
  804. chat->setDefaultRestrictions(ChatRestrictions());
  805. if (canAddMembers != chat->canAddMembers()) {
  806. flags |= UpdateFlag::Rights;
  807. }
  808. }, [&](const MTPDchannel &data) {
  809. const auto channel = result->asChannel();
  810. minimal = data.is_min();
  811. if (minimal && !result->isLoaded()) {
  812. LOG(("API Warning: not loaded minimal channel applied."));
  813. }
  814. const auto wasInChannel = channel->amIn();
  815. const auto canViewAdmins = channel->canViewAdmins();
  816. const auto canViewMembers = channel->canViewMembers();
  817. const auto canAddMembers = channel->canAddMembers();
  818. const auto wasCallNotEmpty = Data::ChannelHasActiveCall(channel);
  819. channel->updateLevelHint(data.vlevel().value_or_empty());
  820. channel->updateSubscriptionUntilDate(
  821. data.vsubscription_until_date().value_or_empty());
  822. if (const auto count = data.vparticipants_count()) {
  823. channel->setMembersCount(count->v);
  824. }
  825. if (const auto rights = data.vdefault_banned_rights()) {
  826. channel->setDefaultRestrictions(ChatRestrictionsInfo(*rights).flags);
  827. } else {
  828. channel->setDefaultRestrictions(ChatRestrictions());
  829. }
  830. if (const auto &status = data.vemoji_status()) {
  831. channel->setEmojiStatus(*status);
  832. } else {
  833. channel->setEmojiStatus(EmojiStatusId());
  834. }
  835. if (minimal) {
  836. if (channel->input.type() == mtpc_inputPeerEmpty
  837. || channel->inputChannel.type() == mtpc_inputChannelEmpty) {
  838. channel->setAccessHash(data.vaccess_hash().value_or_empty());
  839. }
  840. } else {
  841. if (const auto rights = data.vadmin_rights()) {
  842. channel->setAdminRights(ChatAdminRightsInfo(*rights).flags);
  843. } else if (channel->hasAdminRights()) {
  844. channel->setAdminRights(ChatAdminRights());
  845. }
  846. if (const auto rights = data.vbanned_rights()) {
  847. channel->setRestrictions(ChatRestrictionsInfo(*rights));
  848. } else if (channel->hasRestrictions()) {
  849. channel->setRestrictions(ChatRestrictionsInfo());
  850. }
  851. channel->setAccessHash(
  852. data.vaccess_hash().value_or(channel->access));
  853. channel->date = data.vdate().v;
  854. channel->setUnavailableReasons(Data::UnavailableReason::Extract(
  855. data.vrestriction_reason()));
  856. }
  857. {
  858. const auto newUsername = qs(data.vusername().value_or_empty());
  859. const auto newUsernames = data.vusernames()
  860. ? Api::Usernames::FromTL(*data.vusernames())
  861. : !newUsername.isEmpty()
  862. ? Data::Usernames{ Data::Username{ newUsername, true, true } }
  863. : Data::Usernames();
  864. channel->setName(
  865. qs(data.vtitle()),
  866. TextUtilities::SingleLine(newUsername));
  867. channel->setUsernames(newUsernames);
  868. }
  869. const auto hasUsername = !channel->username().isEmpty();
  870. using Flag = ChannelDataFlag;
  871. const auto flagsMask = Flag::Broadcast
  872. | Flag::Verified
  873. | Flag::Scam
  874. | Flag::Fake
  875. | Flag::Megagroup
  876. | Flag::Gigagroup
  877. | Flag::Username
  878. | Flag::Signatures
  879. | Flag::SignatureProfiles
  880. | Flag::HasLink
  881. | Flag::SlowmodeEnabled
  882. | Flag::CallActive
  883. | Flag::CallNotEmpty
  884. | Flag::Forbidden
  885. | (!minimal ? (Flag::Left | Flag::Creator) : Flag())
  886. | Flag::NoForwards
  887. | Flag::JoinToWrite
  888. | Flag::RequestToJoin
  889. | Flag::Forum
  890. | ((!minimal && !data.is_stories_hidden_min())
  891. ? Flag::StoriesHidden
  892. : Flag());
  893. const auto storiesState = minimal
  894. ? std::optional<Data::Stories::PeerSourceState>()
  895. : data.is_stories_unavailable()
  896. ? Data::Stories::PeerSourceState()
  897. : !data.vstories_max_id()
  898. ? std::optional<Data::Stories::PeerSourceState>()
  899. : stories().peerSourceState(channel, data.vstories_max_id()->v);
  900. const auto flagsSet = (data.is_broadcast() ? Flag::Broadcast : Flag())
  901. | (data.is_verified() ? Flag::Verified : Flag())
  902. | (data.is_scam() ? Flag::Scam : Flag())
  903. | (data.is_fake() ? Flag::Fake : Flag())
  904. | (data.is_megagroup() ? Flag::Megagroup : Flag())
  905. | (data.is_gigagroup() ? Flag::Gigagroup : Flag())
  906. | (hasUsername ? Flag::Username : Flag())
  907. | (data.is_signatures() ? Flag::Signatures : Flag())
  908. | (data.is_signature_profiles() ? Flag::SignatureProfiles : Flag())
  909. | (data.is_has_link() ? Flag::HasLink : Flag())
  910. | (data.is_slowmode_enabled() ? Flag::SlowmodeEnabled : Flag())
  911. | (data.is_call_active() ? Flag::CallActive : Flag())
  912. | ((data.is_call_not_empty()
  913. || (channel->groupCall()
  914. && channel->groupCall()->fullCount() > 0))
  915. ? Flag::CallNotEmpty
  916. : Flag())
  917. | (!minimal
  918. ? (data.is_left() ? Flag::Left : Flag())
  919. | (data.is_creator() ? Flag::Creator : Flag())
  920. : Flag())
  921. | (data.is_noforwards() ? Flag::NoForwards : Flag())
  922. | (data.is_join_to_send() ? Flag::JoinToWrite : Flag())
  923. | (data.is_join_request() ? Flag::RequestToJoin : Flag())
  924. | ((data.is_forum() && data.is_megagroup())
  925. ? Flag::Forum
  926. : Flag())
  927. | ((!minimal
  928. && !data.is_stories_hidden_min()
  929. && data.is_stories_hidden())
  930. ? Flag::StoriesHidden
  931. : Flag());
  932. channel->setFlags((channel->flags() & ~flagsMask) | flagsSet);
  933. channel->setBotVerifyDetailsIcon(
  934. data.vbot_verification_icon().value_or_empty());
  935. if (!minimal && storiesState) {
  936. result->setStoriesState(!storiesState->maxId
  937. ? UserData::StoriesState::None
  938. : (storiesState->maxId > storiesState->readTill)
  939. ? UserData::StoriesState::HasUnread
  940. : UserData::StoriesState::HasRead);
  941. }
  942. channel->setPhoto(data.vphoto());
  943. channel->setStarsPerMessage(
  944. data.vsend_paid_messages_stars().value_or_empty());
  945. if (wasInChannel != channel->amIn()) {
  946. flags |= UpdateFlag::ChannelAmIn;
  947. }
  948. if (canViewAdmins != channel->canViewAdmins()
  949. || canViewMembers != channel->canViewMembers()
  950. || canAddMembers != channel->canAddMembers()) {
  951. flags |= UpdateFlag::Rights;
  952. }
  953. if (wasCallNotEmpty != Data::ChannelHasActiveCall(channel)) {
  954. flags |= UpdateFlag::GroupCall;
  955. }
  956. if (result->changeColor(data.vcolor())) {
  957. flags |= UpdateFlag::Color;
  958. if (result->isMinimalLoaded()) {
  959. _peerDecorationsUpdated.fire_copy(result);
  960. }
  961. }
  962. }, [&](const MTPDchannelForbidden &data) {
  963. const auto channel = result->asChannel();
  964. auto wasInChannel = channel->amIn();
  965. auto canViewAdmins = channel->canViewAdmins();
  966. auto canViewMembers = channel->canViewMembers();
  967. auto canAddMembers = channel->canAddMembers();
  968. using Flag = ChannelDataFlag;
  969. const auto flagsMask = Flag::Broadcast
  970. | Flag::Megagroup
  971. | Flag::Forbidden;
  972. const auto flagsSet = (data.is_broadcast() ? Flag::Broadcast : Flag())
  973. | (data.is_megagroup() ? Flag::Megagroup : Flag())
  974. | Flag::Forbidden;
  975. channel->setFlags((channel->flags() & ~flagsMask) | flagsSet);
  976. if (channel->hasAdminRights()) {
  977. channel->setAdminRights(ChatAdminRights());
  978. }
  979. if (channel->hasRestrictions()) {
  980. channel->setRestrictions(ChatRestrictionsInfo());
  981. }
  982. channel->setName(qs(data.vtitle()), QString());
  983. channel->setAccessHash(data.vaccess_hash().v);
  984. channel->setPhoto(MTP_chatPhotoEmpty());
  985. channel->date = 0;
  986. channel->setMembersCount(0);
  987. if (wasInChannel != channel->amIn()) {
  988. flags |= UpdateFlag::ChannelAmIn;
  989. }
  990. if (canViewAdmins != channel->canViewAdmins()
  991. || canViewMembers != channel->canViewMembers()
  992. || canAddMembers != channel->canAddMembers()) {
  993. flags |= UpdateFlag::Rights;
  994. }
  995. }, [](const MTPDchatEmpty &) {
  996. });
  997. if (minimal) {
  998. if (!result->isMinimalLoaded()) {
  999. result->setLoadedStatus(PeerData::LoadedStatus::Minimal);
  1000. }
  1001. } else if (!result->isLoaded()) {
  1002. result->setLoadedStatus(PeerData::LoadedStatus::Normal);
  1003. }
  1004. if (flags) {
  1005. session().changes().peerUpdated(result, flags);
  1006. }
  1007. return result;
  1008. }
  1009. UserData *Session::processUsers(const MTPVector<MTPUser> &data) {
  1010. auto result = (UserData*)nullptr;
  1011. for (const auto &user : data.v) {
  1012. result = processUser(user);
  1013. }
  1014. return result;
  1015. }
  1016. PeerData *Session::processChats(const MTPVector<MTPChat> &data) {
  1017. auto result = (PeerData*)nullptr;
  1018. for (const auto &chat : data.v) {
  1019. result = processChat(chat);
  1020. }
  1021. return result;
  1022. }
  1023. void Session::applyMaximumChatVersions(const MTPVector<MTPChat> &data) {
  1024. for (const auto &chat : data.v) {
  1025. chat.match([&](const MTPDchat &data) {
  1026. if (const auto chat = chatLoaded(data.vid().v)) {
  1027. if (data.vversion().v < chat->version()) {
  1028. chat->setVersion(data.vversion().v);
  1029. }
  1030. }
  1031. }, [](const auto &) {
  1032. });
  1033. }
  1034. }
  1035. void Session::registerGroupCall(not_null<GroupCall*> call) {
  1036. _groupCalls.emplace(call->id(), call);
  1037. }
  1038. void Session::unregisterGroupCall(not_null<GroupCall*> call) {
  1039. _groupCalls.remove(call->id());
  1040. }
  1041. GroupCall *Session::groupCall(CallId callId) const {
  1042. const auto i = _groupCalls.find(callId);
  1043. return (i != end(_groupCalls)) ? i->second.get() : nullptr;
  1044. }
  1045. void Session::watchForOffline(not_null<UserData*> user, TimeId now) {
  1046. if (!now) {
  1047. now = base::unixtime::now();
  1048. }
  1049. if (!Data::IsUserOnline(user, now)) {
  1050. return;
  1051. }
  1052. const auto lastseen = user->lastseen();
  1053. const auto till = lastseen.onlineTill();
  1054. const auto &[i, ok] = _watchingForOffline.emplace(user, till);
  1055. if (!ok) {
  1056. if (i->second == till) {
  1057. return;
  1058. }
  1059. i->second = till;
  1060. }
  1061. const auto timeout = Data::OnlineChangeTimeout(lastseen, now);
  1062. const auto fires = _watchForOfflineTimer.isActive()
  1063. ? _watchForOfflineTimer.remainingTime()
  1064. : -1;
  1065. if (fires >= 0 && fires <= timeout) {
  1066. return;
  1067. }
  1068. _watchForOfflineTimer.callOnce(std::max(timeout, crl::time(1)));
  1069. }
  1070. void Session::maybeStopWatchForOffline(not_null<UserData*> user) {
  1071. if (Data::IsUserOnline(user)) {
  1072. return;
  1073. } else if (_watchingForOffline.remove(user)
  1074. && _watchingForOffline.empty()) {
  1075. _watchForOfflineTimer.cancel();
  1076. }
  1077. }
  1078. void Session::checkLocalUsersWentOffline() {
  1079. _watchForOfflineTimer.cancel();
  1080. auto minimal = 86400 * crl::time(1000);
  1081. const auto now = base::unixtime::now();
  1082. for (auto i = begin(_watchingForOffline)
  1083. ; i != end(_watchingForOffline);) {
  1084. const auto user = i->first;
  1085. if (!Data::IsUserOnline(user, now)) {
  1086. i = _watchingForOffline.erase(i);
  1087. session().changes().peerUpdated(
  1088. user,
  1089. PeerUpdate::Flag::OnlineStatus);
  1090. } else {
  1091. const auto timeout = Data::OnlineChangeTimeout(user, now);
  1092. accumulate_min(minimal, timeout);
  1093. ++i;
  1094. }
  1095. }
  1096. if (!_watchingForOffline.empty()) {
  1097. _watchForOfflineTimer.callOnce(std::max(minimal, crl::time(1)));
  1098. }
  1099. }
  1100. auto Session::invitedToCallUsers(CallId callId) const
  1101. -> const base::flat_set<not_null<UserData*>> & {
  1102. static const base::flat_set<not_null<UserData*>> kEmpty;
  1103. const auto i = _invitedToCallUsers.find(callId);
  1104. return (i != _invitedToCallUsers.end()) ? i->second : kEmpty;
  1105. }
  1106. void Session::registerInvitedToCallUser(
  1107. CallId callId,
  1108. not_null<PeerData*> peer,
  1109. not_null<UserData*> user) {
  1110. const auto call = peer->groupCall();
  1111. if (call && call->id() == callId) {
  1112. const auto inCall = ranges::contains(
  1113. call->participants(),
  1114. user,
  1115. &Data::GroupCallParticipant::peer);
  1116. if (inCall) {
  1117. return;
  1118. }
  1119. }
  1120. _invitedToCallUsers[callId].emplace(user);
  1121. _invitesToCalls.fire({ callId, user });
  1122. }
  1123. void Session::unregisterInvitedToCallUser(
  1124. CallId callId,
  1125. not_null<UserData*> user) {
  1126. const auto i = _invitedToCallUsers.find(callId);
  1127. if (i != _invitedToCallUsers.end()) {
  1128. i->second.remove(user);
  1129. if (i->second.empty()) {
  1130. _invitedToCallUsers.erase(i);
  1131. }
  1132. }
  1133. }
  1134. UserData *Session::userByPhone(const QString &phone) const {
  1135. const auto pname = phone.trimmed();
  1136. for (const auto &[peerId, peer] : _peers) {
  1137. if (const auto user = peer->asUser()) {
  1138. if (user->phone() == pname) {
  1139. return user;
  1140. }
  1141. }
  1142. }
  1143. return nullptr;
  1144. }
  1145. PeerData *Session::peerByUsername(const QString &username) const {
  1146. const auto uname = username.trimmed();
  1147. for (const auto &[peerId, peer] : _peers) {
  1148. if (peer->isLoaded()
  1149. && !peer->username().compare(uname, Qt::CaseInsensitive)) {
  1150. return peer.get();
  1151. }
  1152. }
  1153. return nullptr;
  1154. }
  1155. void Session::enumerateUsers(Fn<void(not_null<UserData*>)> action) const {
  1156. for (const auto &[peerId, peer] : _peers) {
  1157. if (const auto user = peer->asUser()) {
  1158. action(user);
  1159. }
  1160. }
  1161. }
  1162. void Session::enumerateGroups(Fn<void(not_null<PeerData*>)> action) const {
  1163. for (const auto &[peerId, peer] : _peers) {
  1164. if (peer->isChat() || peer->isMegagroup()) {
  1165. action(peer.get());
  1166. }
  1167. }
  1168. }
  1169. void Session::enumerateBroadcasts(
  1170. Fn<void(not_null<ChannelData*>)> action) const {
  1171. for (const auto &[peerId, peer] : _peers) {
  1172. if (const auto channel = peer->asChannel()) {
  1173. if (!channel->isMegagroup()) {
  1174. action(channel);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. not_null<History*> Session::history(PeerId peerId) {
  1180. return _histories->findOrCreate(peerId);
  1181. }
  1182. History *Session::historyLoaded(PeerId peerId) const {
  1183. return _histories->find(peerId);
  1184. }
  1185. not_null<History*> Session::history(not_null<const PeerData*> peer) {
  1186. return history(peer->id);
  1187. }
  1188. History *Session::historyLoaded(const PeerData *peer) {
  1189. return peer ? historyLoaded(peer->id) : nullptr;
  1190. }
  1191. void Session::deleteConversationLocally(not_null<PeerData*> peer) {
  1192. const auto markLeft = [&] {
  1193. if (const auto channel = peer->asMegagroup()) {
  1194. channel->addFlags(ChannelDataFlag::Left);
  1195. if (const auto from = channel->getMigrateFromChat()) {
  1196. if (const auto migrated = historyLoaded(from)) {
  1197. migrated->updateChatListExistence();
  1198. }
  1199. }
  1200. }
  1201. };
  1202. if (const auto history = historyLoaded(peer)) {
  1203. if (history->folderKnown()) {
  1204. setChatPinned(history, FilterId(), false);
  1205. }
  1206. removeChatListEntry(history);
  1207. history->clearFolder();
  1208. // We want to mark the channel as left before unloading the history,
  1209. // otherwise some parts of updating may return us to the chats list.
  1210. markLeft();
  1211. history->clear(peer->isChannel()
  1212. ? History::ClearType::Unload
  1213. : History::ClearType::DeleteChat);
  1214. } else {
  1215. markLeft();
  1216. }
  1217. }
  1218. bool Session::chatsListLoaded(Data::Folder *folder) {
  1219. return chatsList(folder)->loaded();
  1220. }
  1221. void Session::chatsListChanged(FolderId folderId) {
  1222. chatsListChanged(folderId ? folder(folderId).get() : nullptr);
  1223. }
  1224. void Session::chatsListChanged(Data::Folder *folder) {
  1225. _chatsListChanged.fire_copy(folder);
  1226. }
  1227. void Session::chatsListDone(Data::Folder *folder) {
  1228. if (folder) {
  1229. folder->chatsList()->setLoaded();
  1230. } else {
  1231. _chatsList.setLoaded();
  1232. }
  1233. _chatsListLoadedEvents.fire_copy(folder);
  1234. }
  1235. void Session::userIsBotChanged(not_null<UserData*> user) {
  1236. if (const auto history = this->history(user)) {
  1237. chatsFilters().refreshHistory(history);
  1238. }
  1239. _userIsBotChanges.fire_copy(user);
  1240. }
  1241. rpl::producer<not_null<UserData*>> Session::userIsBotChanges() const {
  1242. return _userIsBotChanges.events();
  1243. }
  1244. void Session::botCommandsChanged(not_null<PeerData*> peer) {
  1245. _botCommandsChanges.fire_copy(peer);
  1246. }
  1247. rpl::producer<not_null<PeerData*>> Session::botCommandsChanges() const {
  1248. return _botCommandsChanges.events();
  1249. }
  1250. Storage::Cache::Database &Session::cache() {
  1251. return *_cache;
  1252. }
  1253. Storage::Cache::Database &Session::cacheBigFile() {
  1254. return *_bigFileCache;
  1255. }
  1256. void Session::suggestStartExport(TimeId availableAt) {
  1257. _exportAvailableAt = availableAt;
  1258. suggestStartExport();
  1259. }
  1260. void Session::clearExportSuggestion() {
  1261. _exportAvailableAt = 0;
  1262. if (_exportSuggestion) {
  1263. _exportSuggestion->closeBox();
  1264. }
  1265. }
  1266. void Session::suggestStartExport() {
  1267. if (_exportAvailableAt <= 0) {
  1268. return;
  1269. }
  1270. const auto now = base::unixtime::now();
  1271. const auto left = (_exportAvailableAt <= now)
  1272. ? 0
  1273. : (_exportAvailableAt - now);
  1274. if (left) {
  1275. base::call_delayed(
  1276. std::min(left + 5, 3600) * crl::time(1000),
  1277. _session,
  1278. [=] { suggestStartExport(); });
  1279. } else if (Core::App().exportManager().inProgress()) {
  1280. Export::View::ClearSuggestStart(&session());
  1281. } else {
  1282. _exportSuggestion = Export::View::SuggestStart(&session());
  1283. }
  1284. }
  1285. const Passport::SavedCredentials *Session::passportCredentials() const {
  1286. return _passportCredentials ? &_passportCredentials->first : nullptr;
  1287. }
  1288. void Session::rememberPassportCredentials(
  1289. Passport::SavedCredentials data,
  1290. crl::time rememberFor) {
  1291. Expects(rememberFor > 0);
  1292. static auto generation = 0;
  1293. _passportCredentials = std::make_unique<CredentialsWithGeneration>(
  1294. std::move(data),
  1295. ++generation);
  1296. base::call_delayed(rememberFor, _session, [=, check = generation] {
  1297. if (_passportCredentials && _passportCredentials->second == check) {
  1298. forgetPassportCredentials();
  1299. }
  1300. });
  1301. }
  1302. void Session::forgetPassportCredentials() {
  1303. _passportCredentials = nullptr;
  1304. }
  1305. void Session::setupMigrationViewer() {
  1306. session().changes().peerUpdates(
  1307. PeerUpdate::Flag::Migration
  1308. ) | rpl::map([](const PeerUpdate &update) {
  1309. return update.peer->asChat();
  1310. }) | rpl::filter([=](ChatData *chat) {
  1311. return (chat != nullptr);
  1312. }) | rpl::start_with_next([=](not_null<ChatData*> chat) {
  1313. const auto channel = chat->migrateTo();
  1314. if (!channel) {
  1315. return;
  1316. }
  1317. chat->clearGroupCall();
  1318. if (const auto from = historyLoaded(chat)) {
  1319. if (const auto to = historyLoaded(channel)) {
  1320. if (to->inChatList() && from->inChatList()) {
  1321. removeChatListEntry(from);
  1322. }
  1323. }
  1324. }
  1325. }, _lifetime);
  1326. }
  1327. void Session::setupChannelLeavingViewer() {
  1328. session().changes().peerUpdates(
  1329. PeerUpdate::Flag::ChannelAmIn
  1330. ) | rpl::map([](const PeerUpdate &update) {
  1331. return update.peer->asChannel();
  1332. }) | rpl::start_with_next([=](not_null<ChannelData*> channel) {
  1333. if (channel->amIn()) {
  1334. channel->clearInvitePeek();
  1335. } else {
  1336. if (const auto history = historyLoaded(channel->id)) {
  1337. history->removeJoinedMessage();
  1338. history->updateChatListExistence();
  1339. history->updateChatListSortPosition();
  1340. if (!history->inChatList()) {
  1341. history->clearFolder();
  1342. }
  1343. }
  1344. }
  1345. }, _lifetime);
  1346. }
  1347. void Session::setupPeerNameViewer() {
  1348. session().changes().realtimeNameUpdates(
  1349. ) | rpl::start_with_next([=](const NameUpdate &update) {
  1350. const auto peer = update.peer;
  1351. if (const auto history = historyLoaded(peer)) {
  1352. history->refreshChatListNameSortKey();
  1353. }
  1354. const auto &oldLetters = update.oldFirstLetters;
  1355. _contactsNoChatsList.peerNameChanged(peer, oldLetters);
  1356. _contactsList.peerNameChanged(peer, oldLetters);
  1357. }, _lifetime);
  1358. }
  1359. void Session::setupUserIsContactViewer() {
  1360. session().changes().peerUpdates(
  1361. PeerUpdate::Flag::IsContact
  1362. ) | rpl::map([](const PeerUpdate &update) {
  1363. return update.peer->asUser();
  1364. }) | rpl::start_with_next([=](not_null<UserData*> user) {
  1365. const auto i = _contactViews.find(peerToUser(user->id));
  1366. if (i != _contactViews.end()) {
  1367. for (const auto &view : i->second) {
  1368. requestViewResize(view);
  1369. }
  1370. }
  1371. if (!user->isLoaded()) {
  1372. LOG(("API Error: "
  1373. "userIsContactChanged() called for a not loaded user!"));
  1374. return;
  1375. }
  1376. if (user->isContact()) {
  1377. const auto history = this->history(user->id);
  1378. _contactsList.addByName(history);
  1379. if (!history->inChatList()) {
  1380. _contactsNoChatsList.addByName(history);
  1381. }
  1382. } else if (const auto history = historyLoaded(user)) {
  1383. _contactsNoChatsList.remove(history);
  1384. _contactsList.remove(history);
  1385. }
  1386. }, _lifetime);
  1387. }
  1388. Session::~Session() = default;
  1389. template <typename Method>
  1390. void Session::enumerateItemViews(
  1391. not_null<const HistoryItem*> item,
  1392. Method method) {
  1393. if (const auto i = _views.find(item); i != _views.end()) {
  1394. for (const auto view : i->second) {
  1395. method(view);
  1396. }
  1397. }
  1398. }
  1399. void Session::photoLoadSettingsChanged() {
  1400. for (const auto &[id, photo] : _photos) {
  1401. photo->automaticLoadSettingsChanged();
  1402. }
  1403. }
  1404. void Session::documentLoadSettingsChanged() {
  1405. for (const auto &[id, document] : _documents) {
  1406. document->automaticLoadSettingsChanged();
  1407. }
  1408. }
  1409. void Session::notifyPhotoLayoutChanged(not_null<const PhotoData*> photo) {
  1410. if (const auto i = _photoItems.find(photo); i != end(_photoItems)) {
  1411. for (const auto &item : i->second) {
  1412. notifyItemLayoutChange(item);
  1413. }
  1414. }
  1415. }
  1416. void Session::requestPhotoViewRepaint(not_null<const PhotoData*> photo) {
  1417. const auto i = _photoItems.find(photo);
  1418. if (i != end(_photoItems)) {
  1419. for (const auto &item : i->second) {
  1420. requestItemRepaint(item);
  1421. }
  1422. }
  1423. }
  1424. void Session::notifyDocumentLayoutChanged(
  1425. not_null<const DocumentData*> document) {
  1426. const auto i = _documentItems.find(document);
  1427. if (i != end(_documentItems)) {
  1428. for (const auto &item : i->second) {
  1429. notifyItemLayoutChange(item);
  1430. }
  1431. }
  1432. if (const auto items = InlineBots::Layout::documentItems()) {
  1433. if (const auto i = items->find(document); i != items->end()) {
  1434. for (const auto &item : i->second) {
  1435. item->layoutChanged();
  1436. }
  1437. }
  1438. }
  1439. }
  1440. void Session::requestDocumentViewRepaint(
  1441. not_null<const DocumentData*> document) {
  1442. const auto i = _documentItems.find(document);
  1443. if (i != end(_documentItems)) {
  1444. for (const auto &item : i->second) {
  1445. requestItemRepaint(item);
  1446. }
  1447. }
  1448. }
  1449. void Session::requestPollViewRepaint(not_null<const PollData*> poll) {
  1450. if (const auto i = _pollViews.find(poll); i != _pollViews.end()) {
  1451. for (const auto &view : i->second) {
  1452. requestViewResize(view);
  1453. }
  1454. }
  1455. }
  1456. void Session::documentLoadProgress(not_null<DocumentData*> document) {
  1457. requestDocumentViewRepaint(document);
  1458. _documentLoadProgress.fire_copy(document);
  1459. }
  1460. void Session::documentLoadDone(not_null<DocumentData*> document) {
  1461. notifyDocumentLayoutChanged(document);
  1462. _documentLoadProgress.fire_copy(document);
  1463. }
  1464. void Session::documentLoadFail(
  1465. not_null<DocumentData*> document,
  1466. bool started) {
  1467. notifyDocumentLayoutChanged(document);
  1468. _documentLoadProgress.fire_copy(document);
  1469. }
  1470. void Session::photoLoadProgress(not_null<PhotoData*> photo) {
  1471. requestPhotoViewRepaint(photo);
  1472. }
  1473. void Session::photoLoadDone(not_null<PhotoData*> photo) {
  1474. notifyPhotoLayoutChanged(photo);
  1475. }
  1476. void Session::photoLoadFail(
  1477. not_null<PhotoData*> photo,
  1478. bool started) {
  1479. notifyPhotoLayoutChanged(photo);
  1480. }
  1481. void Session::markMediaRead(not_null<const DocumentData*> document) {
  1482. const auto i = _documentItems.find(document);
  1483. if (i != end(_documentItems)) {
  1484. auto items = base::flat_set<not_null<HistoryItem*>>();
  1485. items.reserve(i->second.size());
  1486. for (const auto &item : i->second) {
  1487. if (item->isUnreadMention() || item->isIncomingUnreadMedia()) {
  1488. items.emplace(item);
  1489. }
  1490. }
  1491. _session->api().markContentsRead(items);
  1492. }
  1493. }
  1494. void Session::notifyItemLayoutChange(not_null<const HistoryItem*> item) {
  1495. _itemLayoutChanges.fire_copy(item);
  1496. enumerateItemViews(item, [&](not_null<ViewElement*> view) {
  1497. notifyViewLayoutChange(view);
  1498. });
  1499. }
  1500. rpl::producer<not_null<const HistoryItem*>> Session::itemLayoutChanged() const {
  1501. return _itemLayoutChanges.events();
  1502. }
  1503. void Session::notifyViewLayoutChange(not_null<const ViewElement*> view) {
  1504. _viewLayoutChanges.fire_copy(view);
  1505. }
  1506. rpl::producer<not_null<const ViewElement*>> Session::viewLayoutChanged() const {
  1507. return _viewLayoutChanges.events();
  1508. }
  1509. void Session::notifyNewItemAdded(not_null<HistoryItem*> item) {
  1510. _newItemAdded.fire_copy(item);
  1511. }
  1512. rpl::producer<not_null<HistoryItem*>> Session::newItemAdded() const {
  1513. return _newItemAdded.events();
  1514. }
  1515. void Session::notifyGiftUpdate(GiftUpdate &&update) {
  1516. _giftUpdates.fire(std::move(update));
  1517. }
  1518. rpl::producer<GiftUpdate> Session::giftUpdates() const {
  1519. return _giftUpdates.events();
  1520. }
  1521. HistoryItem *Session::changeMessageId(PeerId peerId, MsgId wasId, MsgId nowId) {
  1522. const auto list = messagesListForInsert(peerId);
  1523. const auto i = list->find(wasId);
  1524. if (i == list->end()) {
  1525. return nullptr;
  1526. }
  1527. const auto item = i->second;
  1528. list->erase(i);
  1529. const auto &[j, ok] = list->emplace(nowId, item);
  1530. if (!peerIsChannel(peerId)) {
  1531. if (IsServerMsgId(wasId)) {
  1532. const auto k = _nonChannelMessages.find(wasId);
  1533. Assert(k != end(_nonChannelMessages));
  1534. _nonChannelMessages.erase(k);
  1535. }
  1536. if (IsServerMsgId(nowId)) {
  1537. _nonChannelMessages.emplace(nowId, item);
  1538. }
  1539. }
  1540. Ensures(ok);
  1541. return item;
  1542. }
  1543. bool Session::queryItemVisibility(not_null<HistoryItem*> item) const {
  1544. auto result = false;
  1545. _itemVisibilityQueries.fire({ item, &result });
  1546. return result;
  1547. }
  1548. bool Session::queryDocumentVisibility(
  1549. not_null<DocumentData*> document) const {
  1550. const auto i = _documentItems.find(document);
  1551. if (i != end(_documentItems)) {
  1552. for (const auto &item : i->second) {
  1553. if (queryItemVisibility(item)) {
  1554. return true;
  1555. }
  1556. }
  1557. }
  1558. return false;
  1559. }
  1560. [[nodiscard]] auto Session::itemVisibilityQueries() const
  1561. -> rpl::producer<Session::ItemVisibilityQuery> {
  1562. return _itemVisibilityQueries.events();
  1563. }
  1564. void Session::itemVisibilitiesUpdated() {
  1565. // This could be rewritten in a more generic form, like:
  1566. // rpl::producer<> itemVisibilitiesUpdates()
  1567. // if someone else requires those methods, using fast for now.
  1568. Core::App().downloadManager().itemVisibilitiesUpdated(_session);
  1569. }
  1570. void Session::notifyItemIdChange(IdChange event) {
  1571. const auto item = changeMessageId(
  1572. event.newId.peer,
  1573. event.oldId,
  1574. event.newId.msg);
  1575. _itemIdChanges.fire_copy(event);
  1576. if (item) {
  1577. const auto refreshViewDataId = [](not_null<ViewElement*> view) {
  1578. view->refreshDataId();
  1579. };
  1580. enumerateItemViews(item, refreshViewDataId);
  1581. if (const auto group = groups().find(item)) {
  1582. const auto leader = group->items.front();
  1583. if (leader != item) {
  1584. enumerateItemViews(leader, refreshViewDataId);
  1585. }
  1586. }
  1587. }
  1588. }
  1589. rpl::producer<Session::IdChange> Session::itemIdChanged() const {
  1590. return _itemIdChanges.events();
  1591. }
  1592. void Session::requestItemRepaint(not_null<const HistoryItem*> item) {
  1593. _itemRepaintRequest.fire_copy(item);
  1594. auto repaintGroupLeader = false;
  1595. auto repaintView = [&](not_null<const ViewElement*> view) {
  1596. if (view->isHiddenByGroup()) {
  1597. repaintGroupLeader = true;
  1598. } else {
  1599. requestViewRepaint(view);
  1600. }
  1601. };
  1602. enumerateItemViews(item, repaintView);
  1603. if (repaintGroupLeader) {
  1604. if (const auto group = groups().find(item)) {
  1605. const auto leader = group->items.front();
  1606. if (leader != item) {
  1607. enumerateItemViews(leader, repaintView);
  1608. }
  1609. }
  1610. }
  1611. const auto history = item->history();
  1612. if (history->lastItemDialogsView().dependsOn(item)) {
  1613. history->updateChatListEntry();
  1614. }
  1615. if (const auto topic = item->topic()) {
  1616. if (topic->lastItemDialogsView().dependsOn(item)) {
  1617. topic->updateChatListEntry();
  1618. }
  1619. }
  1620. if (const auto sublist = item->savedSublist()) {
  1621. if (sublist->lastItemDialogsView().dependsOn(item)) {
  1622. sublist->updateChatListEntry();
  1623. }
  1624. }
  1625. }
  1626. rpl::producer<not_null<const HistoryItem*>> Session::itemRepaintRequest() const {
  1627. return _itemRepaintRequest.events();
  1628. }
  1629. void Session::requestViewRepaint(not_null<const ViewElement*> view) {
  1630. _viewRepaintRequest.fire_copy(view);
  1631. }
  1632. rpl::producer<not_null<const ViewElement*>> Session::viewRepaintRequest() const {
  1633. return _viewRepaintRequest.events();
  1634. }
  1635. void Session::requestItemResize(not_null<const HistoryItem*> item) {
  1636. _itemResizeRequest.fire_copy(item);
  1637. enumerateItemViews(item, [&](not_null<ViewElement*> view) {
  1638. requestViewResize(view);
  1639. });
  1640. }
  1641. rpl::producer<not_null<const HistoryItem*>> Session::itemResizeRequest() const {
  1642. return _itemResizeRequest.events();
  1643. }
  1644. void Session::requestViewResize(not_null<ViewElement*> view) {
  1645. view->setPendingResize();
  1646. _viewResizeRequest.fire_copy(view);
  1647. notifyViewLayoutChange(view);
  1648. }
  1649. rpl::producer<not_null<ViewElement*>> Session::viewResizeRequest() const {
  1650. return _viewResizeRequest.events();
  1651. }
  1652. void Session::requestItemViewRefresh(not_null<const HistoryItem*> item) {
  1653. if (const auto view = item->mainView()) {
  1654. notifyHistoryChangeDelayed(item->history());
  1655. view->refreshInBlock();
  1656. }
  1657. _itemViewRefreshRequest.fire_copy(item);
  1658. }
  1659. rpl::producer<not_null<const HistoryItem*>> Session::itemViewRefreshRequest() const {
  1660. return _itemViewRefreshRequest.events();
  1661. }
  1662. void Session::notifyItemDataChange(not_null<HistoryItem*> item) {
  1663. _itemDataChanges.fire_copy(item);
  1664. }
  1665. rpl::producer<not_null<HistoryItem*>> Session::itemDataChanges() const {
  1666. return _itemDataChanges.events();
  1667. }
  1668. void Session::requestItemTextRefresh(not_null<HistoryItem*> item) {
  1669. const auto call = [&](not_null<HistoryItem*> item) {
  1670. enumerateItemViews(item, [&](not_null<ViewElement*> view) {
  1671. view->itemTextUpdated();
  1672. });
  1673. requestItemResize(item);
  1674. };
  1675. if (const auto group = groups().find(item)) {
  1676. call(group->items.front());
  1677. } else {
  1678. call(item);
  1679. }
  1680. }
  1681. void Session::registerRestricted(
  1682. not_null<const HistoryItem*> item,
  1683. const QString &reason) {
  1684. Expects(item->hasPossibleRestrictions());
  1685. _possiblyRestricted[item].emplace(reason);
  1686. }
  1687. void Session::registerRestricted(
  1688. not_null<const HistoryItem*> item,
  1689. const std::vector<UnavailableReason> &reasons) {
  1690. Expects(item->hasPossibleRestrictions());
  1691. auto &list = _possiblyRestricted[item];
  1692. if (list.empty()) {
  1693. auto &&simple = reasons
  1694. | ranges::views::transform(&UnavailableReason::reason);
  1695. list = { begin(simple), end(simple) };
  1696. } else {
  1697. for (const auto &reason : reasons) {
  1698. list.emplace(reason.reason);
  1699. }
  1700. }
  1701. }
  1702. void Session::registerHighlightProcess(
  1703. uint64 processId,
  1704. not_null<HistoryItem*> item) {
  1705. Expects(item->inHighlightProcess());
  1706. const auto &[i, ok] = _highlightings.emplace(processId, item);
  1707. Ensures(ok);
  1708. }
  1709. void Session::highlightProcessDone(uint64 processId) {
  1710. if (const auto done = _highlightings.take(processId)) {
  1711. for (const auto &[id, item] : _highlightings) {
  1712. if (item == *done) {
  1713. return;
  1714. }
  1715. }
  1716. (*done)->highlightProcessDone();
  1717. }
  1718. }
  1719. void Session::requestUnreadReactionsAnimation(not_null<HistoryItem*> item) {
  1720. enumerateItemViews(item, [&](not_null<ViewElement*> view) {
  1721. view->animateUnreadReactions();
  1722. });
  1723. }
  1724. rpl::producer<not_null<const HistoryItem*>> Session::itemRemoved() const {
  1725. return _itemRemoved.events();
  1726. }
  1727. rpl::producer<not_null<const HistoryItem*>> Session::itemRemoved(
  1728. FullMsgId itemId) const {
  1729. return itemRemoved(
  1730. ) | rpl::filter([=](not_null<const HistoryItem*> item) {
  1731. return (itemId == item->fullId());
  1732. });
  1733. }
  1734. void Session::notifyViewRemoved(not_null<const ViewElement*> view) {
  1735. _viewRemoved.fire_copy(view);
  1736. }
  1737. rpl::producer<not_null<const ViewElement*>> Session::viewRemoved() const {
  1738. return _viewRemoved.events();
  1739. }
  1740. void Session::notifyViewPaidReactionSent(not_null<const ViewElement*> view) {
  1741. _viewPaidReactionSent.fire_copy(view);
  1742. }
  1743. rpl::producer<not_null<const ViewElement*>> Session::viewPaidReactionSent() const {
  1744. return _viewPaidReactionSent.events();
  1745. }
  1746. void Session::notifyHistoryUnloaded(not_null<const History*> history) {
  1747. _historyUnloaded.fire_copy(history);
  1748. }
  1749. rpl::producer<not_null<const History*>> Session::historyUnloaded() const {
  1750. return _historyUnloaded.events();
  1751. }
  1752. void Session::notifyHistoryCleared(not_null<const History*> history) {
  1753. _historyCleared.fire_copy(history);
  1754. }
  1755. rpl::producer<not_null<const History*>> Session::historyCleared() const {
  1756. return _historyCleared.events();
  1757. }
  1758. void Session::notifyHistoryChangeDelayed(not_null<History*> history) {
  1759. history->setHasPendingResizedItems();
  1760. _historiesChanged.insert(history);
  1761. }
  1762. rpl::producer<not_null<History*>> Session::historyChanged() const {
  1763. return _historyChanged.events();
  1764. }
  1765. void Session::sendHistoryChangeNotifications() {
  1766. for (const auto &history : base::take(_historiesChanged)) {
  1767. _historyChanged.fire_copy(history);
  1768. }
  1769. }
  1770. void Session::notifyPinnedDialogsOrderUpdated() {
  1771. _pinnedDialogsOrderUpdated.fire({});
  1772. }
  1773. rpl::producer<> Session::pinnedDialogsOrderUpdated() const {
  1774. return _pinnedDialogsOrderUpdated.events();
  1775. }
  1776. Session::CreditsSubsRebuilderPtr Session::createCreditsSubsRebuilder() {
  1777. if (auto result = activeCreditsSubsRebuilder()) {
  1778. return result;
  1779. }
  1780. auto result = std::make_shared<CreditsSubsRebuilder>();
  1781. _creditsSubsRebuilder = result;
  1782. return result;
  1783. }
  1784. Session::CreditsSubsRebuilderPtr Session::activeCreditsSubsRebuilder() const {
  1785. return _creditsSubsRebuilder.lock();
  1786. }
  1787. void Session::registerHeavyViewPart(not_null<ViewElement*> view) {
  1788. _heavyViewParts.emplace(view);
  1789. }
  1790. void Session::unregisterHeavyViewPart(not_null<ViewElement*> view) {
  1791. _heavyViewParts.remove(view);
  1792. }
  1793. void Session::unloadHeavyViewParts(
  1794. not_null<HistoryView::ElementDelegate*> delegate) {
  1795. if (_heavyViewParts.empty()) {
  1796. return;
  1797. }
  1798. const auto remove = ranges::count(
  1799. _heavyViewParts,
  1800. delegate,
  1801. [](not_null<ViewElement*> element) { return element->delegate(); });
  1802. if (remove == _heavyViewParts.size()) {
  1803. for (const auto &view : base::take(_heavyViewParts)) {
  1804. view->unloadHeavyPart();
  1805. }
  1806. } else {
  1807. auto remove = std::vector<not_null<ViewElement*>>();
  1808. for (const auto &view : _heavyViewParts) {
  1809. if (view->delegate() == delegate) {
  1810. remove.push_back(view);
  1811. }
  1812. }
  1813. for (const auto view : remove) {
  1814. view->unloadHeavyPart();
  1815. }
  1816. }
  1817. }
  1818. void Session::unloadHeavyViewParts(
  1819. not_null<HistoryView::ElementDelegate*> delegate,
  1820. int from,
  1821. int till) {
  1822. if (_heavyViewParts.empty()) {
  1823. return;
  1824. }
  1825. auto remove = std::vector<not_null<ViewElement*>>();
  1826. for (const auto &view : _heavyViewParts) {
  1827. if (view->delegate() == delegate
  1828. && !delegate->elementIntersectsRange(view, from, till)) {
  1829. remove.push_back(view);
  1830. }
  1831. }
  1832. for (const auto view : remove) {
  1833. view->unloadHeavyPart();
  1834. }
  1835. }
  1836. void Session::registerShownSpoiler(not_null<ViewElement*> view) {
  1837. _shownSpoilers.emplace(view);
  1838. }
  1839. void Session::hideShownSpoilers() {
  1840. for (const auto &view : base::take(_shownSpoilers)) {
  1841. view->hideSpoilers();
  1842. requestViewRepaint(view);
  1843. }
  1844. }
  1845. void Session::removeMegagroupParticipant(
  1846. not_null<ChannelData*> channel,
  1847. not_null<UserData*> user) {
  1848. _megagroupParticipantRemoved.fire({ channel, user });
  1849. }
  1850. auto Session::megagroupParticipantRemoved() const
  1851. -> rpl::producer<MegagroupParticipant> {
  1852. return _megagroupParticipantRemoved.events();
  1853. }
  1854. rpl::producer<not_null<UserData*>> Session::megagroupParticipantRemoved(
  1855. not_null<ChannelData*> channel) const {
  1856. return megagroupParticipantRemoved(
  1857. ) | rpl::filter([channel](auto updateChannel, auto user) {
  1858. return (updateChannel == channel);
  1859. }) | rpl::map([](auto updateChannel, auto user) {
  1860. return user;
  1861. });
  1862. }
  1863. void Session::addNewMegagroupParticipant(
  1864. not_null<ChannelData*> channel,
  1865. not_null<UserData*> user) {
  1866. _megagroupParticipantAdded.fire({ channel, user });
  1867. }
  1868. auto Session::megagroupParticipantAdded() const
  1869. -> rpl::producer<MegagroupParticipant> {
  1870. return _megagroupParticipantAdded.events();
  1871. }
  1872. rpl::producer<not_null<UserData*>> Session::megagroupParticipantAdded(
  1873. not_null<ChannelData*> channel) const {
  1874. return megagroupParticipantAdded(
  1875. ) | rpl::filter([channel](auto updateChannel, auto user) {
  1876. return (updateChannel == channel);
  1877. }) | rpl::map([](auto updateChannel, auto user) {
  1878. return user;
  1879. });
  1880. }
  1881. HistoryItemsList Session::idsToItems(
  1882. const MessageIdsList &ids) const {
  1883. return ranges::views::all(
  1884. ids
  1885. ) | ranges::views::transform([&](const FullMsgId &fullId) {
  1886. return message(fullId);
  1887. }) | ranges::views::filter([](HistoryItem *item) {
  1888. return item != nullptr;
  1889. }) | ranges::views::transform([](HistoryItem *item) {
  1890. return not_null<HistoryItem*>(item);
  1891. }) | ranges::to_vector;
  1892. }
  1893. MessageIdsList Session::itemsToIds(
  1894. const HistoryItemsList &items) const {
  1895. return ranges::views::all(
  1896. items
  1897. ) | ranges::views::transform([](not_null<HistoryItem*> item) {
  1898. return item->fullId();
  1899. }) | ranges::to_vector;
  1900. }
  1901. MessageIdsList Session::itemOrItsGroup(not_null<HistoryItem*> item) const {
  1902. if (const auto group = groups().find(item)) {
  1903. return itemsToIds(group->items);
  1904. }
  1905. return { 1, item->fullId() };
  1906. }
  1907. void Session::setChatPinned(
  1908. Dialogs::Key key,
  1909. FilterId filterId,
  1910. bool pinned) {
  1911. Expects(key.entry()->folderKnown());
  1912. const auto list = (filterId
  1913. ? chatsFilters().chatsList(filterId)
  1914. : chatsListFor(key.entry()))->pinned();
  1915. list->setPinned(key, pinned);
  1916. notifyPinnedDialogsOrderUpdated();
  1917. }
  1918. void Session::setPinnedFromEntryList(Dialogs::Key key, bool pinned) {
  1919. Expects(key.entry()->folderKnown());
  1920. const auto list = chatsListFor(key.entry())->pinned();
  1921. if (pinned) {
  1922. list->addPinned(key);
  1923. } else {
  1924. list->setPinned(key, false);
  1925. }
  1926. }
  1927. void Session::applyPinnedChats(
  1928. Data::Folder *folder,
  1929. const QVector<MTPDialogPeer> &list) {
  1930. for (const auto &peer : list) {
  1931. peer.match([&](const MTPDdialogPeer &data) {
  1932. const auto history = this->history(peerFromMTP(data.vpeer()));
  1933. if (folder) {
  1934. history->setFolder(folder);
  1935. } else {
  1936. history->clearFolder();
  1937. }
  1938. }, [&](const MTPDdialogPeerFolder &data) {
  1939. if (folder) {
  1940. LOG(("API Error: Nested folders detected."));
  1941. }
  1942. });
  1943. }
  1944. chatsList(folder)->pinned()->applyList(this, list);
  1945. notifyPinnedDialogsOrderUpdated();
  1946. }
  1947. void Session::applyPinnedTopics(
  1948. not_null<Data::Forum*> forum,
  1949. const QVector<MTPint> &list) {
  1950. forum->topicsList()->pinned()->applyList(forum, list);
  1951. notifyPinnedDialogsOrderUpdated();
  1952. }
  1953. void Session::applyDialogs(
  1954. Data::Folder *requestFolder,
  1955. const QVector<MTPMessage> &messages,
  1956. const QVector<MTPDialog> &dialogs,
  1957. std::optional<int> count) {
  1958. processMessages(messages, NewMessageType::Last);
  1959. for (const auto &dialog : dialogs) {
  1960. dialog.match([&](const auto &data) {
  1961. applyDialog(requestFolder, data);
  1962. });
  1963. }
  1964. if (requestFolder && count) {
  1965. requestFolder->chatsList()->setCloudListSize(*count);
  1966. }
  1967. }
  1968. void Session::applyDialog(
  1969. Data::Folder *requestFolder,
  1970. const MTPDdialog &data) {
  1971. const auto peerId = peerFromMTP(data.vpeer());
  1972. if (!peerId) {
  1973. return;
  1974. }
  1975. const auto history = this->history(peerId);
  1976. history->applyDialog(requestFolder, data);
  1977. setPinnedFromEntryList(history, data.is_pinned());
  1978. if (const auto from = history->peer->migrateFrom()) {
  1979. if (const auto historyFrom = historyLoaded(from)) {
  1980. removeChatListEntry(historyFrom);
  1981. }
  1982. } else if (const auto to = history->peer->migrateTo()) {
  1983. if (to->amIn()) {
  1984. removeChatListEntry(history);
  1985. }
  1986. }
  1987. }
  1988. void Session::applyDialog(
  1989. Data::Folder *requestFolder,
  1990. const MTPDdialogFolder &data) {
  1991. if (requestFolder) {
  1992. LOG(("API Error: requestFolder != nullptr for dialogFolder."));
  1993. }
  1994. const auto folder = processFolder(data.vfolder());
  1995. folder->applyDialog(data);
  1996. setPinnedFromEntryList(folder, data.is_pinned());
  1997. }
  1998. bool Session::pinnedCanPin(not_null<Dialogs::Entry*> entry) const {
  1999. if (const auto sublist = entry->asSublist()) {
  2000. const auto saved = &savedMessages();
  2001. return pinnedChatsOrder(saved).size() < pinnedChatsLimit(saved);
  2002. } else if (const auto topic = entry->asTopic()) {
  2003. const auto forum = topic->forum();
  2004. return pinnedChatsOrder(forum).size() < pinnedChatsLimit(forum);
  2005. } else {
  2006. const auto folder = entry->folder();
  2007. return pinnedChatsOrder(folder).size() < pinnedChatsLimit(folder);
  2008. }
  2009. }
  2010. bool Session::pinnedCanPin(
  2011. FilterId filterId,
  2012. not_null<History*> history) const {
  2013. Expects(filterId != 0);
  2014. const auto &list = chatsFilters().list();
  2015. const auto i = ranges::find(list, filterId, &Data::ChatFilter::id);
  2016. return (i == end(list))
  2017. || (i->always().contains(history))
  2018. || (i->always().size() < pinnedChatsLimit(filterId));
  2019. }
  2020. int Session::pinnedChatsLimit(Data::Folder *folder) const {
  2021. const auto limits = Data::PremiumLimits(_session);
  2022. return folder
  2023. ? limits.dialogsFolderPinnedCurrent()
  2024. : limits.dialogsPinnedCurrent();
  2025. }
  2026. int Session::pinnedChatsLimit(FilterId filterId) const {
  2027. const auto limits = Data::PremiumLimits(_session);
  2028. return limits.dialogFiltersChatsCurrent();
  2029. }
  2030. int Session::pinnedChatsLimit(not_null<Data::Forum*> forum) const {
  2031. const auto limits = Data::PremiumLimits(_session);
  2032. return limits.topicsPinnedCurrent();
  2033. }
  2034. int Session::pinnedChatsLimit(not_null<Data::SavedMessages*> saved) const {
  2035. const auto limits = Data::PremiumLimits(_session);
  2036. return limits.savedSublistsPinnedCurrent();
  2037. }
  2038. rpl::producer<int> Session::maxPinnedChatsLimitValue(
  2039. Data::Folder *folder) const {
  2040. // Premium limit from appconfig.
  2041. // We always use premium limit in the MainList limit producer,
  2042. // because it slices the list to that limit. We don't want to slice
  2043. // premium-ly added chats from the pinned list because of sync issues.
  2044. return _session->appConfig().value(
  2045. ) | rpl::map([folder, limits = Data::PremiumLimits(_session)] {
  2046. return folder
  2047. ? limits.dialogsFolderPinnedPremium()
  2048. : limits.dialogsPinnedPremium();
  2049. });
  2050. }
  2051. rpl::producer<int> Session::maxPinnedChatsLimitValue(
  2052. FilterId filterId) const {
  2053. // Premium limit from appconfig.
  2054. // We always use premium limit in the MainList limit producer,
  2055. // because it slices the list to that limit. We don't want to slice
  2056. // premium-ly added chats from the pinned list because of sync issues.
  2057. return _session->appConfig().value(
  2058. ) | rpl::map([limits = Data::PremiumLimits(_session)] {
  2059. return limits.dialogFiltersChatsPremium();
  2060. });
  2061. }
  2062. rpl::producer<int> Session::maxPinnedChatsLimitValue(
  2063. not_null<Data::Forum*> forum) const {
  2064. return _session->appConfig().value(
  2065. ) | rpl::map([limits = Data::PremiumLimits(_session)] {
  2066. return limits.topicsPinnedCurrent();
  2067. });
  2068. }
  2069. rpl::producer<int> Session::maxPinnedChatsLimitValue(
  2070. not_null<SavedMessages*> saved) const {
  2071. // Premium limit from appconfig.
  2072. // We always use premium limit in the MainList limit producer,
  2073. // because it slices the list to that limit. We don't want to slice
  2074. // premium-ly added chats from the pinned list because of sync issues.
  2075. return _session->appConfig().value(
  2076. ) | rpl::map([limits = Data::PremiumLimits(_session)] {
  2077. return limits.savedSublistsPinnedPremium();
  2078. });
  2079. }
  2080. int Session::groupFreeTranscribeLevel() const {
  2081. return _groupFreeTranscribeLevel.current();
  2082. }
  2083. const std::vector<Dialogs::Key> &Session::pinnedChatsOrder(
  2084. Data::Folder *folder) const {
  2085. return chatsList(folder)->pinned()->order();
  2086. }
  2087. const std::vector<Dialogs::Key> &Session::pinnedChatsOrder(
  2088. FilterId filterId) const {
  2089. return chatsFilters().chatsList(filterId)->pinned()->order();
  2090. }
  2091. const std::vector<Dialogs::Key> &Session::pinnedChatsOrder(
  2092. not_null<Data::Forum*> forum) const {
  2093. return forum->topicsList()->pinned()->order();
  2094. }
  2095. const std::vector<Dialogs::Key> &Session::pinnedChatsOrder(
  2096. not_null<Data::SavedMessages*> saved) const {
  2097. return saved->chatsList()->pinned()->order();
  2098. }
  2099. void Session::clearPinnedChats(Data::Folder *folder) {
  2100. chatsList(folder)->pinned()->clear();
  2101. }
  2102. void Session::reorderTwoPinnedChats(
  2103. FilterId filterId,
  2104. Dialogs::Key key1,
  2105. Dialogs::Key key2) {
  2106. Expects(key1.entry()->folderKnown() && key2.entry()->folderKnown());
  2107. Expects(filterId || (key1.entry()->folder() == key2.entry()->folder()));
  2108. const auto topic = key1.topic();
  2109. const auto list = topic
  2110. ? topic->forum()->topicsList()
  2111. : filterId
  2112. ? chatsFilters().chatsList(filterId)
  2113. : chatsListFor(key1.entry());
  2114. list->pinned()->reorder(key1, key2);
  2115. notifyPinnedDialogsOrderUpdated();
  2116. }
  2117. bool Session::updateExistingMessage(const MTPDmessage &data) {
  2118. const auto peer = peerFromMTP(data.vpeer_id());
  2119. const auto existing = message(peer, data.vid().v);
  2120. if (!existing) {
  2121. return false;
  2122. }
  2123. existing->applySentMessage(data);
  2124. const auto result = (existing->mainView() != nullptr);
  2125. if (result) {
  2126. stickers().checkSavedGif(existing);
  2127. }
  2128. session().changes().messageUpdated(
  2129. existing,
  2130. Data::MessageUpdate::Flag::NewMaybeAdded);
  2131. return result;
  2132. }
  2133. void Session::updateEditedMessage(const MTPMessage &data) {
  2134. const auto existing = data.match([](const MTPDmessageEmpty &)
  2135. -> HistoryItem* {
  2136. return nullptr;
  2137. }, [&](const auto &data) {
  2138. return message(peerFromMTP(data.vpeer_id()), data.vid().v);
  2139. });
  2140. if (!existing) {
  2141. Reactions::CheckUnknownForUnread(this, data);
  2142. return;
  2143. }
  2144. if (existing->isLocalUpdateMedia() && data.type() == mtpc_message) {
  2145. updateExistingMessage(data.c_message());
  2146. }
  2147. data.match([](const MTPDmessageEmpty &) {
  2148. }, [&](const MTPDmessageService &data) {
  2149. existing->applyEdition(data);
  2150. }, [&](const auto &data) {
  2151. existing->applyEdition(HistoryMessageEdition(_session, data));
  2152. });
  2153. }
  2154. void Session::processMessages(
  2155. const QVector<MTPMessage> &data,
  2156. NewMessageType type) {
  2157. auto indices = base::flat_map<uint64, int>();
  2158. for (int i = 0, l = data.size(); i != l; ++i) {
  2159. const auto &message = data[i];
  2160. if (message.type() == mtpc_message) {
  2161. const auto &data = message.c_message();
  2162. // new message, index my forwarded messages to links overview
  2163. if ((type == NewMessageType::Unread)
  2164. && updateExistingMessage(data)) {
  2165. continue;
  2166. }
  2167. }
  2168. const auto id = IdFromMessage(message); // Only 32 bit values here.
  2169. indices.emplace((uint64(uint32(id.bare)) << 32) | uint64(i), i);
  2170. }
  2171. for (const auto &[position, index] : indices) {
  2172. addNewMessage(
  2173. data[index],
  2174. MessageFlags(),
  2175. type);
  2176. }
  2177. }
  2178. void Session::processMessages(
  2179. const MTPVector<MTPMessage> &data,
  2180. NewMessageType type) {
  2181. processMessages(data.v, type);
  2182. }
  2183. void Session::processExistingMessages(
  2184. ChannelData *channel,
  2185. const MTPmessages_Messages &data) {
  2186. data.match([&](const MTPDmessages_channelMessages &data) {
  2187. if (channel) {
  2188. channel->ptsReceived(data.vpts().v);
  2189. channel->processTopics(data.vtopics());
  2190. } else {
  2191. LOG(("App Error: received messages.channelMessages!"));
  2192. }
  2193. }, [](const auto &) {});
  2194. data.match([&](const MTPDmessages_messagesNotModified&) {
  2195. LOG(("API Error: received messages.messagesNotModified!"));
  2196. }, [&](const auto &data) {
  2197. processUsers(data.vusers());
  2198. processChats(data.vchats());
  2199. processMessages(data.vmessages(), NewMessageType::Existing);
  2200. });
  2201. }
  2202. const Session::Messages *Session::messagesList(PeerId peerId) const {
  2203. const auto i = _messages.find(peerId);
  2204. return (i != end(_messages)) ? &i->second : nullptr;
  2205. }
  2206. auto Session::messagesListForInsert(PeerId peerId)
  2207. -> not_null<Messages*> {
  2208. return &_messages[peerId];
  2209. }
  2210. void Session::registerMessage(not_null<HistoryItem*> item) {
  2211. const auto peerId = item->history()->peer->id;
  2212. const auto list = messagesListForInsert(peerId);
  2213. const auto itemId = item->id;
  2214. const auto i = list->find(itemId);
  2215. if (i != list->end()) {
  2216. LOG(("App Error: Trying to re-registerMessage()."));
  2217. i->second->destroy();
  2218. }
  2219. list->emplace(itemId, item);
  2220. if (!peerIsChannel(peerId) && IsServerMsgId(itemId)) {
  2221. _nonChannelMessages.emplace(itemId, item);
  2222. }
  2223. }
  2224. void Session::registerMessageTTL(TimeId when, not_null<HistoryItem*> item) {
  2225. Expects(when > 0);
  2226. auto &list = _ttlMessages[when];
  2227. list.emplace(item);
  2228. const auto nearest = _ttlMessages.begin()->first;
  2229. if (nearest < when && _ttlCheckTimer.isActive()) {
  2230. return;
  2231. }
  2232. scheduleNextTTLs();
  2233. }
  2234. void Session::scheduleNextTTLs() {
  2235. if (_ttlMessages.empty()) {
  2236. return;
  2237. }
  2238. const auto nearest = _ttlMessages.begin()->first;
  2239. const auto now = base::unixtime::now();
  2240. // Set timer not more than for 24 hours.
  2241. const auto maxTimeout = TimeId(86400);
  2242. const auto timeout = std::min(std::max(now, nearest) - now, maxTimeout);
  2243. _ttlCheckTimer.callOnce(timeout * crl::time(1000));
  2244. }
  2245. void Session::unregisterMessageTTL(
  2246. TimeId when,
  2247. not_null<HistoryItem*> item) {
  2248. Expects(when > 0);
  2249. const auto i = _ttlMessages.find(when);
  2250. if (i == end(_ttlMessages)) {
  2251. return;
  2252. }
  2253. auto &list = i->second;
  2254. list.erase(item);
  2255. if (list.empty()) {
  2256. _ttlMessages.erase(i);
  2257. }
  2258. }
  2259. void Session::checkTTLs() {
  2260. _ttlCheckTimer.cancel();
  2261. const auto now = base::unixtime::now();
  2262. while (!_ttlMessages.empty() && _ttlMessages.begin()->first <= now) {
  2263. _ttlMessages.begin()->second.front()->destroy();
  2264. }
  2265. scheduleNextTTLs();
  2266. }
  2267. void Session::processMessagesDeleted(
  2268. PeerId peerId,
  2269. const QVector<MTPint> &data) {
  2270. const auto list = messagesList(peerId);
  2271. const auto affected = historyLoaded(peerId);
  2272. if (!list && !affected) {
  2273. return;
  2274. }
  2275. auto historiesToCheck = base::flat_set<not_null<History*>>();
  2276. for (const auto &messageId : data) {
  2277. const auto i = list ? list->find(messageId.v) : Messages::iterator();
  2278. if (list && i != list->end()) {
  2279. const auto history = i->second->history();
  2280. i->second->destroy();
  2281. if (!history->chatListMessageKnown()) {
  2282. historiesToCheck.emplace(history);
  2283. }
  2284. } else if (affected) {
  2285. affected->unknownMessageDeleted(messageId.v);
  2286. }
  2287. }
  2288. for (const auto &history : historiesToCheck) {
  2289. history->requestChatListMessage();
  2290. }
  2291. }
  2292. void Session::processNonChannelMessagesDeleted(const QVector<MTPint> &data) {
  2293. auto historiesToCheck = base::flat_set<not_null<History*>>();
  2294. for (const auto &messageId : data) {
  2295. if (const auto item = nonChannelMessage(messageId.v)) {
  2296. const auto history = item->history();
  2297. item->destroy();
  2298. if (!history->chatListMessageKnown()) {
  2299. historiesToCheck.emplace(history);
  2300. }
  2301. }
  2302. }
  2303. for (const auto &history : historiesToCheck) {
  2304. history->requestChatListMessage();
  2305. }
  2306. }
  2307. void Session::removeDependencyMessage(not_null<HistoryItem*> item) {
  2308. const auto i = _dependentMessages.find(item);
  2309. if (i != end(_dependentMessages)) {
  2310. const auto items = std::move(i->second);
  2311. _dependentMessages.erase(i);
  2312. for (const auto &dependent : items) {
  2313. dependent->dependencyItemRemoved(item);
  2314. }
  2315. }
  2316. if (item->groupId()) {
  2317. if (const auto group = groups().find(item)) {
  2318. for (const auto &groupedItem : group->items) {
  2319. updateDependentMessages(groupedItem);
  2320. }
  2321. }
  2322. }
  2323. }
  2324. void Session::unregisterMessage(not_null<HistoryItem*> item) {
  2325. const auto peerId = item->history()->peer->id;
  2326. const auto itemId = item->id;
  2327. _itemRemoved.fire_copy(item);
  2328. if (item->hasPossibleRestrictions()) {
  2329. _possiblyRestricted.remove(item);
  2330. }
  2331. session().changes().messageUpdated(
  2332. item,
  2333. Data::MessageUpdate::Flag::Destroyed);
  2334. groups().unregisterMessage(item);
  2335. removeDependencyMessage(item);
  2336. for (auto i = begin(_highlightings); i != end(_highlightings);) {
  2337. if (i->second == item) {
  2338. i = _highlightings.erase(i);
  2339. } else {
  2340. ++i;
  2341. }
  2342. }
  2343. messagesListForInsert(peerId)->erase(itemId);
  2344. if (!peerIsChannel(peerId) && IsServerMsgId(itemId)) {
  2345. _nonChannelMessages.erase(itemId);
  2346. }
  2347. }
  2348. MsgId Session::nextLocalMessageId() {
  2349. Expects(_localMessageIdCounter < EndClientMsgId);
  2350. return _localMessageIdCounter++;
  2351. }
  2352. void Session::setSuggestToGigagroup(
  2353. not_null<ChannelData*> group,
  2354. bool suggest) {
  2355. if (suggest) {
  2356. _suggestToGigagroup.emplace(group);
  2357. } else {
  2358. _suggestToGigagroup.remove(group);
  2359. }
  2360. }
  2361. bool Session::suggestToGigagroup(not_null<ChannelData*> group) const {
  2362. return _suggestToGigagroup.contains(group);
  2363. }
  2364. HistoryItem *Session::message(PeerId peerId, MsgId itemId) const {
  2365. if (!itemId) {
  2366. return nullptr;
  2367. }
  2368. const auto data = messagesList(peerId);
  2369. if (!data) {
  2370. return nullptr;
  2371. }
  2372. const auto i = data->find(itemId);
  2373. return (i != data->end()) ? i->second.get() : nullptr;
  2374. }
  2375. HistoryItem *Session::message(
  2376. not_null<const PeerData*> peer,
  2377. MsgId itemId) const {
  2378. return message(peer->id, itemId);
  2379. }
  2380. HistoryItem *Session::message(FullMsgId itemId) const {
  2381. return message(itemId.peer, itemId.msg);
  2382. }
  2383. HistoryItem *Session::nonChannelMessage(MsgId itemId) const {
  2384. if (!IsServerMsgId(itemId)) {
  2385. return nullptr;
  2386. }
  2387. const auto i = _nonChannelMessages.find(itemId);
  2388. return (i != end(_nonChannelMessages)) ? i->second.get() : nullptr;
  2389. }
  2390. void Session::updateDependentMessages(not_null<HistoryItem*> item) {
  2391. const auto i = _dependentMessages.find(item);
  2392. if (i != end(_dependentMessages)) {
  2393. for (const auto &dependent : i->second) {
  2394. dependent->updateDependencyItem();
  2395. }
  2396. }
  2397. session().changes().messageUpdated(
  2398. item,
  2399. Data::MessageUpdate::Flag::Edited);
  2400. }
  2401. void Session::registerDependentMessage(
  2402. not_null<HistoryItem*> dependent,
  2403. not_null<HistoryItem*> dependency) {
  2404. _dependentMessages[dependency].emplace(dependent);
  2405. }
  2406. void Session::unregisterDependentMessage(
  2407. not_null<HistoryItem*> dependent,
  2408. not_null<HistoryItem*> dependency) {
  2409. const auto i = _dependentMessages.find(dependency);
  2410. if (i != end(_dependentMessages)) {
  2411. if (i->second.remove(dependent) && i->second.empty()) {
  2412. _dependentMessages.erase(i);
  2413. }
  2414. }
  2415. }
  2416. void Session::registerMessageRandomId(uint64 randomId, FullMsgId itemId) {
  2417. _messageByRandomId.emplace(randomId, itemId);
  2418. }
  2419. void Session::unregisterMessageRandomId(uint64 randomId) {
  2420. _messageByRandomId.remove(randomId);
  2421. }
  2422. FullMsgId Session::messageIdByRandomId(uint64 randomId) const {
  2423. const auto i = _messageByRandomId.find(randomId);
  2424. return (i != end(_messageByRandomId)) ? i->second : FullMsgId();
  2425. }
  2426. void Session::registerMessageSentData(
  2427. uint64 randomId,
  2428. PeerId peerId,
  2429. const QString &text) {
  2430. _sentMessagesData.emplace(randomId, SentData{ peerId, text });
  2431. }
  2432. void Session::unregisterMessageSentData(uint64 randomId) {
  2433. _sentMessagesData.remove(randomId);
  2434. }
  2435. Session::SentData Session::messageSentData(uint64 randomId) const {
  2436. const auto i = _sentMessagesData.find(randomId);
  2437. return (i != end(_sentMessagesData)) ? i->second : SentData();
  2438. }
  2439. HistoryItem *Session::addNewMessage(
  2440. const MTPMessage &data,
  2441. MessageFlags localFlags,
  2442. NewMessageType type) {
  2443. return addNewMessage(IdFromMessage(data), data, localFlags, type);
  2444. }
  2445. HistoryItem *Session::addNewMessage(
  2446. MsgId id,
  2447. const MTPMessage &data,
  2448. MessageFlags localFlags,
  2449. NewMessageType type) {
  2450. const auto peerId = PeerFromMessage(data);
  2451. if (!peerId || data.type() == mtpc_messageEmpty) {
  2452. return nullptr;
  2453. }
  2454. const auto result = history(peerId)->addNewMessage(
  2455. id,
  2456. data,
  2457. localFlags,
  2458. type);
  2459. if (type == NewMessageType::Unread) {
  2460. CheckForSwitchInlineButton(result);
  2461. }
  2462. return result;
  2463. }
  2464. int Session::unreadBadge() const {
  2465. return computeUnreadBadge(_chatsList.unreadState());
  2466. }
  2467. bool Session::unreadBadgeMuted() const {
  2468. return computeUnreadBadgeMuted(_chatsList.unreadState());
  2469. }
  2470. int Session::unreadBadgeIgnoreOne(Dialogs::Key key) const {
  2471. const auto remove = (key && key.entry()->inChatList())
  2472. ? key.entry()->chatListUnreadState()
  2473. : Dialogs::UnreadState();
  2474. return computeUnreadBadge(_chatsList.unreadState() - remove);
  2475. }
  2476. bool Session::unreadBadgeMutedIgnoreOne(Dialogs::Key key) const {
  2477. if (!Core::App().settings().includeMutedCounter()) {
  2478. return false;
  2479. }
  2480. const auto remove = (key && key.entry()->inChatList())
  2481. ? key.entry()->chatListUnreadState()
  2482. : Dialogs::UnreadState();
  2483. return computeUnreadBadgeMuted(_chatsList.unreadState() - remove);
  2484. }
  2485. int Session::unreadOnlyMutedBadge() const {
  2486. const auto state = _chatsList.unreadState();
  2487. return Core::App().settings().countUnreadMessages()
  2488. ? state.messagesMuted
  2489. : state.chatsMuted;
  2490. }
  2491. rpl::producer<> Session::unreadBadgeChanges() const {
  2492. return _unreadBadgeChanges.events();
  2493. }
  2494. void Session::notifyUnreadBadgeChanged() {
  2495. _unreadBadgeChanges.fire({});
  2496. }
  2497. void Session::updateRepliesReadTill(RepliesReadTillUpdate update) {
  2498. _repliesReadTillUpdates.fire(std::move(update));
  2499. }
  2500. auto Session::repliesReadTillUpdates() const
  2501. -> rpl::producer<RepliesReadTillUpdate> {
  2502. return _repliesReadTillUpdates.events();
  2503. }
  2504. int Session::computeUnreadBadge(const Dialogs::UnreadState &state) const {
  2505. const auto all = Core::App().settings().includeMutedCounter();
  2506. return std::max(state.marks - (all ? 0 : state.marksMuted), 0)
  2507. + (Core::App().settings().countUnreadMessages()
  2508. ? std::max(state.messages - (all ? 0 : state.messagesMuted), 0)
  2509. : std::max(state.chats - (all ? 0 : state.chatsMuted), 0));
  2510. }
  2511. bool Session::computeUnreadBadgeMuted(
  2512. const Dialogs::UnreadState &state) const {
  2513. if (!Core::App().settings().includeMutedCounter()) {
  2514. return false;
  2515. }
  2516. return (state.marksMuted >= state.marks)
  2517. && (Core::App().settings().countUnreadMessages()
  2518. ? (state.messagesMuted >= state.messages)
  2519. : (state.chatsMuted >= state.chats));
  2520. }
  2521. void Session::selfDestructIn(not_null<HistoryItem*> item, crl::time delay) {
  2522. _selfDestructItems.push_back(item->fullId());
  2523. if (!_selfDestructTimer.isActive()
  2524. || _selfDestructTimer.remainingTime() > delay) {
  2525. _selfDestructTimer.callOnce(delay);
  2526. }
  2527. }
  2528. void Session::checkSelfDestructItems() {
  2529. const auto now = crl::now();
  2530. auto nextDestructIn = crl::time(0);
  2531. for (auto i = _selfDestructItems.begin(); i != _selfDestructItems.cend();) {
  2532. if (const auto item = message(*i)) {
  2533. if (const auto destructIn = item->getSelfDestructIn(now)) {
  2534. if (nextDestructIn > 0) {
  2535. accumulate_min(nextDestructIn, destructIn);
  2536. } else {
  2537. nextDestructIn = destructIn;
  2538. }
  2539. ++i;
  2540. } else {
  2541. i = _selfDestructItems.erase(i);
  2542. }
  2543. } else {
  2544. i = _selfDestructItems.erase(i);
  2545. }
  2546. }
  2547. if (nextDestructIn > 0) {
  2548. _selfDestructTimer.callOnce(nextDestructIn);
  2549. }
  2550. }
  2551. not_null<PhotoData*> Session::photo(PhotoId id) {
  2552. auto i = _photos.find(id);
  2553. if (i == _photos.end()) {
  2554. i = _photos.emplace(
  2555. id,
  2556. std::make_unique<PhotoData>(this, id)).first;
  2557. }
  2558. return i->second.get();
  2559. }
  2560. not_null<PhotoData*> Session::processPhoto(const MTPPhoto &data) {
  2561. return data.match([&](const MTPDphoto &data) {
  2562. return processPhoto(data);
  2563. }, [&](const MTPDphotoEmpty &data) {
  2564. return photo(data.vid().v);
  2565. });
  2566. }
  2567. not_null<PhotoData*> Session::processPhoto(const MTPDphoto &data) {
  2568. const auto result = photo(data.vid().v);
  2569. photoApplyFields(result, data);
  2570. return result;
  2571. }
  2572. not_null<PhotoData*> Session::processPhoto(
  2573. const MTPPhoto &data,
  2574. const PreparedPhotoThumbs &thumbs) {
  2575. Expects(!thumbs.empty());
  2576. const auto find = [&](const QByteArray &levels) {
  2577. const auto kInvalidIndex = int(levels.size());
  2578. const auto level = [&](const auto &pair) {
  2579. const auto letter = pair.first;
  2580. const auto index = levels.indexOf(letter);
  2581. return (index >= 0) ? index : kInvalidIndex;
  2582. };
  2583. const auto result = ranges::max_element(
  2584. thumbs,
  2585. std::greater<>(),
  2586. level);
  2587. return (level(*result) == kInvalidIndex) ? thumbs.end() : result;
  2588. };
  2589. const auto image = [&](const QByteArray &levels) {
  2590. const auto i = find(levels);
  2591. return (i == thumbs.end())
  2592. ? ImageWithLocation()
  2593. : Images::FromImageInMemory(
  2594. i->second.image,
  2595. "JPG",
  2596. i->second.bytes);
  2597. };
  2598. const auto small = image(SmallLevels);
  2599. const auto thumbnail = image(ThumbnailLevels);
  2600. const auto large = image(LargeLevels);
  2601. return data.match([&](const MTPDphoto &data) {
  2602. return photo(
  2603. data.vid().v,
  2604. data.vaccess_hash().v,
  2605. data.vfile_reference().v,
  2606. data.vdate().v,
  2607. data.vdc_id().v,
  2608. data.is_has_stickers(),
  2609. QByteArray(),
  2610. small,
  2611. thumbnail,
  2612. large,
  2613. ImageWithLocation{},
  2614. ImageWithLocation{},
  2615. crl::time(0));
  2616. }, [&](const MTPDphotoEmpty &data) {
  2617. return photo(data.vid().v);
  2618. });
  2619. }
  2620. not_null<PhotoData*> Session::photo(
  2621. PhotoId id,
  2622. const uint64 &access,
  2623. const QByteArray &fileReference,
  2624. TimeId date,
  2625. int32 dc,
  2626. bool hasStickers,
  2627. const QByteArray &inlineThumbnailBytes,
  2628. const ImageWithLocation &small,
  2629. const ImageWithLocation &thumbnail,
  2630. const ImageWithLocation &large,
  2631. const ImageWithLocation &videoSmall,
  2632. const ImageWithLocation &videoLarge,
  2633. crl::time videoStartTime) {
  2634. const auto result = photo(id);
  2635. photoApplyFields(
  2636. result,
  2637. access,
  2638. fileReference,
  2639. date,
  2640. dc,
  2641. hasStickers,
  2642. inlineThumbnailBytes,
  2643. small,
  2644. thumbnail,
  2645. large,
  2646. videoSmall,
  2647. videoLarge,
  2648. videoStartTime);
  2649. return result;
  2650. }
  2651. void Session::photoConvert(
  2652. not_null<PhotoData*> original,
  2653. const MTPPhoto &data) {
  2654. const auto id = data.match([](const auto &data) {
  2655. return data.vid().v;
  2656. });
  2657. const auto idChanged = (original->id != id);
  2658. if (idChanged) {
  2659. auto i = _photos.find(id);
  2660. if (i == _photos.end()) {
  2661. const auto j = _photos.find(original->id);
  2662. Assert(j != _photos.end());
  2663. auto owned = std::move(j->second);
  2664. _photos.erase(j);
  2665. i = _photos.emplace(id, std::move(owned)).first;
  2666. }
  2667. original->id = id;
  2668. original->uploadingData = nullptr;
  2669. if (i->second.get() != original) {
  2670. photoApplyFields(i->second.get(), data);
  2671. }
  2672. }
  2673. photoApplyFields(original, data);
  2674. }
  2675. PhotoData *Session::photoFromWeb(
  2676. const MTPWebDocument &data,
  2677. const ImageLocation &thumbnailLocation) {
  2678. const auto large = Images::FromWebDocument(data);
  2679. if (!large.valid()) {
  2680. return nullptr;
  2681. }
  2682. return photo(
  2683. base::RandomValue<PhotoId>(),
  2684. uint64(0),
  2685. QByteArray(),
  2686. base::unixtime::now(),
  2687. 0,
  2688. false,
  2689. QByteArray(),
  2690. ImageWithLocation{},
  2691. ImageWithLocation{ .location = thumbnailLocation },
  2692. ImageWithLocation{ .location = large },
  2693. ImageWithLocation{},
  2694. ImageWithLocation{},
  2695. crl::time(0));
  2696. }
  2697. void Session::photoApplyFields(
  2698. not_null<PhotoData*> photo,
  2699. const MTPPhoto &data) {
  2700. if (data.type() == mtpc_photo) {
  2701. photoApplyFields(photo, data.c_photo());
  2702. }
  2703. }
  2704. void Session::photoApplyFields(
  2705. not_null<PhotoData*> photo,
  2706. const MTPDphoto &data) {
  2707. const auto &sizes = data.vsizes().v;
  2708. const auto progressive = [&] {
  2709. const auto area = [&](const MTPPhotoSize &size) {
  2710. return size.match([](const MTPDphotoSizeProgressive &data) {
  2711. return data.vw().v * data.vh().v;
  2712. }, [](const auto &) {
  2713. return 0;
  2714. });
  2715. };
  2716. const auto found = ranges::max_element(sizes, std::less<>(), area);
  2717. return (found == sizes.end()
  2718. || found->type() != mtpc_photoSizeProgressive)
  2719. ? sizes.end()
  2720. : found;
  2721. }();
  2722. const auto find = [&](const QByteArray &levels) {
  2723. const auto kInvalidIndex = int(levels.size());
  2724. const auto level = [&](const MTPPhotoSize &size) {
  2725. const auto letter = size.match([](const MTPDphotoSizeEmpty &) {
  2726. return char(0);
  2727. }, [](const auto &size) {
  2728. return size.vtype().v.isEmpty() ? char(0) : size.vtype().v[0];
  2729. });
  2730. const auto index = levels.indexOf(letter);
  2731. return (index >= 0) ? index : kInvalidIndex;
  2732. };
  2733. const auto result = ranges::max_element(
  2734. sizes,
  2735. std::greater<>(),
  2736. level);
  2737. return (level(*result) == kInvalidIndex) ? sizes.end() : result;
  2738. };
  2739. const auto image = [&](const QByteArray &levels) {
  2740. const auto i = find(levels);
  2741. return (i == sizes.end())
  2742. ? ImageWithLocation()
  2743. : Images::FromPhotoSize(_session, data, *i);
  2744. };
  2745. const auto findVideoSize = [&](PhotoSize size)
  2746. -> std::optional<MTPVideoSize> {
  2747. const auto sizes = data.vvideo_sizes();
  2748. if (!sizes) {
  2749. return std::nullopt;
  2750. }
  2751. const auto area = [](const MTPVideoSize &size) {
  2752. return size.match([](const MTPDvideoSize &data) {
  2753. return data.vsize().v ? (data.vw().v * data.vh().v) : 0;
  2754. }, [](const MTPDvideoSizeEmojiMarkup &) {
  2755. return 0;
  2756. }, [](const MTPDvideoSizeStickerMarkup &) {
  2757. return 0;
  2758. });
  2759. };
  2760. const auto type = [](const MTPVideoSize &size) {
  2761. return size.match([](const MTPDvideoSize &data) {
  2762. return data.vtype().v.isEmpty()
  2763. ? char(0)
  2764. : data.vtype().v.front();
  2765. }, [](const auto &) {
  2766. return char(0);
  2767. });
  2768. };
  2769. const auto result = (size == PhotoSize::Small)
  2770. ? ranges::find(sizes->v, 'p', type)
  2771. : ranges::max_element(sizes->v, std::less<>(), area);
  2772. if (result == sizes->v.end() || area(*result) <= 0) {
  2773. return std::nullopt;
  2774. }
  2775. return std::make_optional(*result);
  2776. };
  2777. const auto useProgressive = (progressive != sizes.end());
  2778. const auto large = useProgressive
  2779. ? Images::FromPhotoSize(_session, data, *progressive)
  2780. : image(LargeLevels);
  2781. if (large.location.valid()) {
  2782. const auto videoSmall = findVideoSize(PhotoSize::Small);
  2783. const auto videoLarge = findVideoSize(PhotoSize::Large);
  2784. photoApplyFields(
  2785. photo,
  2786. data.vaccess_hash().v,
  2787. data.vfile_reference().v,
  2788. data.vdate().v,
  2789. data.vdc_id().v,
  2790. data.is_has_stickers(),
  2791. FindPhotoInlineThumbnail(data),
  2792. (useProgressive
  2793. ? ImageWithLocation()
  2794. : image(SmallLevels)),
  2795. (useProgressive
  2796. ? Images::FromProgressiveSize(_session, *progressive, 1)
  2797. : image(ThumbnailLevels)),
  2798. large,
  2799. (videoSmall
  2800. ? Images::FromVideoSize(_session, data, *videoSmall)
  2801. : ImageWithLocation()),
  2802. (videoLarge
  2803. ? Images::FromVideoSize(_session, data, *videoLarge)
  2804. : ImageWithLocation()),
  2805. (videoLarge
  2806. ? videoLarge->match([](const MTPDvideoSize &data) {
  2807. return VideoStartTime(data);
  2808. }, [](const MTPDvideoSizeEmojiMarkup &) { return 0;
  2809. }, [](const MTPDvideoSizeStickerMarkup &) { return 0; })
  2810. : 0));
  2811. }
  2812. }
  2813. void Session::photoApplyFields(
  2814. not_null<PhotoData*> photo,
  2815. const uint64 &access,
  2816. const QByteArray &fileReference,
  2817. TimeId date,
  2818. int32 dc,
  2819. bool hasStickers,
  2820. const QByteArray &inlineThumbnailBytes,
  2821. const ImageWithLocation &small,
  2822. const ImageWithLocation &thumbnail,
  2823. const ImageWithLocation &large,
  2824. const ImageWithLocation &videoSmall,
  2825. const ImageWithLocation &videoLarge,
  2826. crl::time videoStartTime) {
  2827. if (!date) {
  2828. return;
  2829. }
  2830. photo->setRemoteLocation(dc, access, fileReference);
  2831. photo->setFields(date, hasStickers);
  2832. photo->updateImages(
  2833. inlineThumbnailBytes,
  2834. small,
  2835. thumbnail,
  2836. large,
  2837. videoSmall,
  2838. videoLarge,
  2839. videoStartTime);
  2840. }
  2841. not_null<DocumentData*> Session::document(DocumentId id) {
  2842. auto i = _documents.find(id);
  2843. if (i == _documents.cend()) {
  2844. i = _documents.emplace(
  2845. id,
  2846. std::make_unique<DocumentData>(this, id)).first;
  2847. }
  2848. return i->second.get();
  2849. }
  2850. not_null<DocumentData*> Session::processDocument(
  2851. const MTPDocument &data,
  2852. const MTPVector<MTPDocument> *qualities) {
  2853. return data.match([&](const MTPDdocument &data) {
  2854. return processDocument(data, qualities);
  2855. }, [&](const MTPDdocumentEmpty &data) {
  2856. return document(data.vid().v);
  2857. });
  2858. }
  2859. not_null<DocumentData*> Session::processDocument(
  2860. const MTPDdocument &data,
  2861. const MTPVector<MTPDocument> *qualities) {
  2862. const auto result = document(data.vid().v);
  2863. documentApplyFields(result, data);
  2864. if (qualities) {
  2865. result->setVideoQualities(qualities->v);
  2866. }
  2867. return result;
  2868. }
  2869. not_null<DocumentData*> Session::processDocument(
  2870. const MTPdocument &data,
  2871. const ImageWithLocation &thumbnail) {
  2872. return data.match([&](const MTPDdocument &data) {
  2873. return document(
  2874. data.vid().v,
  2875. data.vaccess_hash().v,
  2876. data.vfile_reference().v,
  2877. data.vdate().v,
  2878. data.vattributes().v,
  2879. qs(data.vmime_type()),
  2880. InlineImageLocation(),
  2881. thumbnail,
  2882. ImageWithLocation(), // videoThumbnail
  2883. false, // isPremiumSticker
  2884. data.vdc_id().v,
  2885. data.vsize().v);
  2886. }, [&](const MTPDdocumentEmpty &data) {
  2887. return document(data.vid().v);
  2888. });
  2889. }
  2890. not_null<DocumentData*> Session::document(
  2891. DocumentId id,
  2892. const uint64 &access,
  2893. const QByteArray &fileReference,
  2894. TimeId date,
  2895. const QVector<MTPDocumentAttribute> &attributes,
  2896. const QString &mime,
  2897. const InlineImageLocation &inlineThumbnail,
  2898. const ImageWithLocation &thumbnail,
  2899. const ImageWithLocation &videoThumbnail,
  2900. bool isPremiumSticker,
  2901. int32 dc,
  2902. int64 size) {
  2903. const auto result = document(id);
  2904. documentApplyFields(
  2905. result,
  2906. access,
  2907. fileReference,
  2908. date,
  2909. attributes,
  2910. mime,
  2911. inlineThumbnail,
  2912. thumbnail,
  2913. videoThumbnail,
  2914. isPremiumSticker,
  2915. dc,
  2916. size);
  2917. return result;
  2918. }
  2919. void Session::documentConvert(
  2920. not_null<DocumentData*> original,
  2921. const MTPDocument &data) {
  2922. const auto id = data.match([](const auto &data) {
  2923. return data.vid().v;
  2924. });
  2925. const auto oldCacheKey = original->cacheKey();
  2926. const auto oldGoodKey = original->goodThumbnailCacheKey();
  2927. const auto idChanged = (original->id != id);
  2928. if (idChanged) {
  2929. auto i = _documents.find(id);
  2930. if (i == _documents.end()) {
  2931. const auto j = _documents.find(original->id);
  2932. Assert(j != _documents.end());
  2933. auto owned = std::move(j->second);
  2934. _documents.erase(j);
  2935. i = _documents.emplace(id, std::move(owned)).first;
  2936. }
  2937. original->id = id;
  2938. original->status = FileReady;
  2939. original->uploadingData = nullptr;
  2940. if (i->second.get() != original) {
  2941. documentApplyFields(i->second.get(), data);
  2942. }
  2943. }
  2944. documentApplyFields(original, data);
  2945. if (idChanged) {
  2946. cache().moveIfEmpty(oldCacheKey, original->cacheKey());
  2947. cache().moveIfEmpty(oldGoodKey, original->goodThumbnailCacheKey());
  2948. if (stickers().savedGifs().indexOf(original) >= 0) {
  2949. _session->local().writeSavedGifs();
  2950. }
  2951. }
  2952. }
  2953. DocumentData *Session::documentFromWeb(
  2954. const MTPWebDocument &data,
  2955. const ImageLocation &thumbnailLocation,
  2956. const ImageLocation &videoThumbnailLocation) {
  2957. return data.match([&](const auto &data) {
  2958. return documentFromWeb(
  2959. data,
  2960. thumbnailLocation,
  2961. videoThumbnailLocation);
  2962. });
  2963. }
  2964. DocumentData *Session::documentFromWeb(
  2965. const MTPDwebDocument &data,
  2966. const ImageLocation &thumbnailLocation,
  2967. const ImageLocation &videoThumbnailLocation) {
  2968. const auto result = document(
  2969. base::RandomValue<DocumentId>(),
  2970. uint64(0),
  2971. QByteArray(),
  2972. base::unixtime::now(),
  2973. data.vattributes().v,
  2974. data.vmime_type().v,
  2975. InlineImageLocation(),
  2976. ImageWithLocation{ .location = thumbnailLocation },
  2977. ImageWithLocation{ .location = videoThumbnailLocation },
  2978. false, // isPremiumSticker
  2979. session().mainDcId(),
  2980. int64(0)); // data.vsize().v
  2981. result->setWebLocation(WebFileLocation(
  2982. data.vurl().v,
  2983. data.vaccess_hash().v));
  2984. return result;
  2985. }
  2986. DocumentData *Session::documentFromWeb(
  2987. const MTPDwebDocumentNoProxy &data,
  2988. const ImageLocation &thumbnailLocation,
  2989. const ImageLocation &videoThumbnailLocation) {
  2990. const auto result = document(
  2991. base::RandomValue<DocumentId>(),
  2992. uint64(0),
  2993. QByteArray(),
  2994. base::unixtime::now(),
  2995. data.vattributes().v,
  2996. data.vmime_type().v,
  2997. InlineImageLocation(),
  2998. ImageWithLocation{ .location = thumbnailLocation },
  2999. ImageWithLocation{ .location = videoThumbnailLocation },
  3000. false, // isPremiumSticker
  3001. session().mainDcId(),
  3002. int64(0)); // data.vsize().v
  3003. result->setContentUrl(qs(data.vurl()));
  3004. return result;
  3005. }
  3006. void Session::documentApplyFields(
  3007. not_null<DocumentData*> document,
  3008. const MTPDocument &data) {
  3009. if (data.type() == mtpc_document) {
  3010. documentApplyFields(document, data.c_document());
  3011. }
  3012. }
  3013. void Session::documentApplyFields(
  3014. not_null<DocumentData*> document,
  3015. const MTPDdocument &data) {
  3016. const auto inlineThumbnail = FindDocumentInlineThumbnail(data);
  3017. const auto thumbnailSize = FindDocumentThumbnail(data);
  3018. const auto videoThumbnailSize = FindDocumentVideoThumbnail(data);
  3019. const auto prepared = Images::FromPhotoSize(
  3020. _session,
  3021. data,
  3022. thumbnailSize);
  3023. const auto videoThumbnail = videoThumbnailSize
  3024. ? Images::FromVideoSize(_session, data, *videoThumbnailSize)
  3025. : ImageWithLocation();
  3026. const auto isPremiumSticker = videoThumbnailSize
  3027. && (videoThumbnailSize->c_videoSize().vtype().v == "f");
  3028. documentApplyFields(
  3029. document,
  3030. data.vaccess_hash().v,
  3031. data.vfile_reference().v,
  3032. data.vdate().v,
  3033. data.vattributes().v,
  3034. qs(data.vmime_type()),
  3035. inlineThumbnail,
  3036. prepared,
  3037. videoThumbnail,
  3038. isPremiumSticker,
  3039. data.vdc_id().v,
  3040. data.vsize().v);
  3041. }
  3042. void Session::documentApplyFields(
  3043. not_null<DocumentData*> document,
  3044. const uint64 &access,
  3045. const QByteArray &fileReference,
  3046. TimeId date,
  3047. const QVector<MTPDocumentAttribute> &attributes,
  3048. const QString &mime,
  3049. const InlineImageLocation &inlineThumbnail,
  3050. const ImageWithLocation &thumbnail,
  3051. const ImageWithLocation &videoThumbnail,
  3052. bool isPremiumSticker,
  3053. int32 dc,
  3054. int64 size) {
  3055. if (!date) {
  3056. return;
  3057. }
  3058. document->date = date;
  3059. document->setMimeString(mime);
  3060. document->updateThumbnails(
  3061. inlineThumbnail,
  3062. thumbnail,
  3063. videoThumbnail,
  3064. isPremiumSticker);
  3065. document->size = size;
  3066. document->setattributes(attributes);
  3067. // Uses 'type' that is computed from attributes.
  3068. document->recountIsImage();
  3069. if (dc != 0 && access != 0) {
  3070. document->setRemoteLocation(dc, access, fileReference);
  3071. }
  3072. }
  3073. not_null<DocumentData*> Session::venueIconDocument(const QString &icon) {
  3074. const auto i = _venueIcons.find(icon);
  3075. if (i != end(_venueIcons)) {
  3076. return i->second;
  3077. }
  3078. const auto result = documentFromWeb(MTP_webDocumentNoProxy(
  3079. MTP_string(u"https://ss3.4sqi.net/img/categories_v2/"_q
  3080. + icon
  3081. + u"_64.png"_q),
  3082. MTP_int(0),
  3083. MTP_string("image/png"),
  3084. MTP_vector<MTPDocumentAttribute>()), {}, {});
  3085. _venueIcons.emplace(icon, result);
  3086. return result;
  3087. }
  3088. not_null<WebPageData*> Session::webpage(WebPageId id) {
  3089. auto i = _webpages.find(id);
  3090. if (i == _webpages.cend()) {
  3091. i = _webpages.emplace(
  3092. id,
  3093. std::make_unique<WebPageData>(this, id)).first;
  3094. }
  3095. return i->second.get();
  3096. }
  3097. not_null<WebPageData*> Session::processWebpage(const MTPWebPage &data) {
  3098. switch (data.type()) {
  3099. case mtpc_webPage:
  3100. return processWebpage(data.c_webPage());
  3101. case mtpc_webPageEmpty: {
  3102. const auto result = webpage(data.c_webPageEmpty().vid().v);
  3103. result->type = WebPageType::None;
  3104. if (result->pendingTill > 0) {
  3105. result->pendingTill = 0;
  3106. result->failed = 1;
  3107. notifyWebPageUpdateDelayed(result);
  3108. }
  3109. return result;
  3110. } break;
  3111. case mtpc_webPagePending:
  3112. return processWebpage(data.c_webPagePending());
  3113. case mtpc_webPageNotModified:
  3114. LOG(("API Error: "
  3115. "webPageNotModified is unexpected in Session::webpage()."));
  3116. return webpage(0);
  3117. }
  3118. Unexpected("Type in Session::webpage().");
  3119. }
  3120. not_null<WebPageData*> Session::processWebpage(const MTPDwebPage &data) {
  3121. const auto result = webpage(data.vid().v);
  3122. webpageApplyFields(result, data);
  3123. return result;
  3124. }
  3125. not_null<WebPageData*> Session::processWebpage(
  3126. const MTPDwebPagePending &data) {
  3127. constexpr auto kDefaultPendingTimeout = 60;
  3128. const auto result = webpage(data.vid().v);
  3129. webpageApplyFields(
  3130. result,
  3131. WebPageType::None,
  3132. QString(),
  3133. QString(),
  3134. QString(),
  3135. QString(),
  3136. TextWithEntities(),
  3137. FullStoryId(),
  3138. nullptr,
  3139. nullptr,
  3140. WebPageCollage(),
  3141. nullptr,
  3142. nullptr,
  3143. nullptr,
  3144. 0,
  3145. QString(),
  3146. false,
  3147. false,
  3148. data.vdate().v
  3149. ? data.vdate().v
  3150. : (base::unixtime::now() + kDefaultPendingTimeout));
  3151. return result;
  3152. }
  3153. not_null<WebPageData*> Session::webpage(
  3154. WebPageId id,
  3155. const QString &siteName,
  3156. const TextWithEntities &content) {
  3157. return webpage(
  3158. id,
  3159. WebPageType::Article,
  3160. QString(),
  3161. QString(),
  3162. siteName,
  3163. QString(),
  3164. content,
  3165. nullptr,
  3166. nullptr,
  3167. WebPageCollage(),
  3168. nullptr,
  3169. nullptr,
  3170. nullptr,
  3171. 0,
  3172. QString(),
  3173. false,
  3174. false,
  3175. TimeId(0));
  3176. }
  3177. not_null<WebPageData*> Session::webpage(
  3178. WebPageId id,
  3179. WebPageType type,
  3180. const QString &url,
  3181. const QString &displayUrl,
  3182. const QString &siteName,
  3183. const QString &title,
  3184. const TextWithEntities &description,
  3185. PhotoData *photo,
  3186. DocumentData *document,
  3187. WebPageCollage &&collage,
  3188. std::unique_ptr<Iv::Data> iv,
  3189. std::unique_ptr<WebPageStickerSet> stickerSet,
  3190. std::shared_ptr<UniqueGift> uniqueGift,
  3191. int duration,
  3192. const QString &author,
  3193. bool hasLargeMedia,
  3194. bool photoIsVideoCover,
  3195. TimeId pendingTill) {
  3196. const auto result = webpage(id);
  3197. webpageApplyFields(
  3198. result,
  3199. type,
  3200. url,
  3201. displayUrl,
  3202. siteName,
  3203. title,
  3204. description,
  3205. FullStoryId(),
  3206. photo,
  3207. document,
  3208. std::move(collage),
  3209. std::move(iv),
  3210. std::move(stickerSet),
  3211. std::move(uniqueGift),
  3212. duration,
  3213. author,
  3214. hasLargeMedia,
  3215. photoIsVideoCover,
  3216. pendingTill);
  3217. return result;
  3218. }
  3219. void Session::webpageApplyFields(
  3220. not_null<WebPageData*> page,
  3221. const MTPDwebPage &data) {
  3222. auto description = TextWithEntities{
  3223. qs(data.vdescription().value_or_empty())
  3224. };
  3225. const auto siteName = qs(data.vsite_name().value_or_empty());
  3226. auto parseFlags = TextParseLinks | TextParseMultiline;
  3227. if (siteName == u"Twitter"_q || siteName == u"Instagram"_q) {
  3228. parseFlags |= TextParseHashtags | TextParseMentions;
  3229. }
  3230. TextUtilities::ParseEntities(description, parseFlags);
  3231. const auto pendingTill = TimeId(0);
  3232. const auto photo = data.vphoto();
  3233. const auto document = data.vdocument();
  3234. const auto lookupInAttribute = [&](
  3235. const MTPDwebPageAttributeTheme &data) -> DocumentData* {
  3236. if (const auto documents = data.vdocuments()) {
  3237. for (const auto &document : documents->v) {
  3238. const auto processed = processDocument(document);
  3239. if (processed->isTheme()) {
  3240. return processed;
  3241. }
  3242. }
  3243. }
  3244. return nullptr;
  3245. };
  3246. const auto lookupThemeDocument = [&]() -> DocumentData* {
  3247. if (const auto attributes = data.vattributes()) {
  3248. for (const auto &attribute : attributes->v) {
  3249. const auto result = attribute.match([&](
  3250. const MTPDwebPageAttributeTheme &data) {
  3251. return lookupInAttribute(data);
  3252. }, [](const MTPDwebPageAttributeStory &) {
  3253. return (DocumentData*)nullptr;
  3254. }, [](const MTPDwebPageAttributeStickerSet &) {
  3255. return (DocumentData*)nullptr;
  3256. }, [](const MTPDwebPageAttributeUniqueStarGift &) {
  3257. return (DocumentData*)nullptr;
  3258. });
  3259. if (result) {
  3260. return result;
  3261. }
  3262. }
  3263. }
  3264. return nullptr;
  3265. };
  3266. using WebPageStickerSetPtr = std::unique_ptr<WebPageStickerSet>;
  3267. const auto lookupStickerSet = [&]() -> WebPageStickerSetPtr {
  3268. if (const auto attributes = data.vattributes()) {
  3269. for (const auto &attribute : attributes->v) {
  3270. auto result = attribute.match([&](
  3271. const MTPDwebPageAttributeStickerSet &data) {
  3272. auto result = std::make_unique<WebPageStickerSet>();
  3273. result->isEmoji = data.is_emojis();
  3274. result->isTextColor = data.is_text_color();
  3275. for (const auto &tl : data.vstickers().v) {
  3276. result->items.push_back(processDocument(tl));
  3277. }
  3278. return result;
  3279. }, [](const auto &) {
  3280. return WebPageStickerSetPtr(nullptr);
  3281. });
  3282. if (result && !result->items.empty()) {
  3283. return result;
  3284. }
  3285. }
  3286. }
  3287. return nullptr;
  3288. };
  3289. using UniqueGiftPtr = std::shared_ptr<UniqueGift>;
  3290. const auto lookupUniqueGift = [&]() -> UniqueGiftPtr {
  3291. if (const auto attributes = data.vattributes()) {
  3292. for (const auto &attribute : attributes->v) {
  3293. return attribute.match([&](
  3294. const MTPDwebPageAttributeUniqueStarGift &data) {
  3295. const auto gift = Api::FromTL(_session, data.vgift());
  3296. return gift ? gift->unique : nullptr;
  3297. }, [](const auto &) -> UniqueGiftPtr { return nullptr; });
  3298. }
  3299. }
  3300. return nullptr;
  3301. };
  3302. auto story = (Data::Story*)nullptr;
  3303. auto storyId = FullStoryId();
  3304. if (const auto attributes = data.vattributes()) {
  3305. for (const auto &attribute : attributes->v) {
  3306. attribute.match([&](const MTPDwebPageAttributeStory &data) {
  3307. storyId = FullStoryId{
  3308. peerFromMTP(data.vpeer()),
  3309. data.vid().v,
  3310. };
  3311. if (const auto embed = data.vstory()) {
  3312. story = stories().applySingle(
  3313. peerFromMTP(data.vpeer()),
  3314. *embed);
  3315. } else if (const auto maybe = stories().lookup(storyId)) {
  3316. story = *maybe;
  3317. } else if (maybe.error() == Data::NoStory::Unknown) {
  3318. stories().resolve(storyId, [=] {
  3319. if (const auto maybe = stories().lookup(storyId)) {
  3320. const auto story = *maybe;
  3321. page->document = story->document();
  3322. page->photo = story->photo();
  3323. page->description = story->caption();
  3324. page->type = WebPageType::Story;
  3325. notifyWebPageUpdateDelayed(page);
  3326. }
  3327. });
  3328. }
  3329. }, [](const auto &) {});
  3330. }
  3331. }
  3332. if (const auto page = data.vcached_page()) {
  3333. for (const auto &photo : page->data().vphotos().v) {
  3334. processPhoto(photo);
  3335. }
  3336. for (const auto &document : page->data().vdocuments().v) {
  3337. processDocument(document);
  3338. }
  3339. const auto process = [&](
  3340. const MTPPageBlock &block,
  3341. const auto &self) -> void {
  3342. block.match([&](const MTPDpageBlockChannel &data) {
  3343. processChat(data.vchannel());
  3344. }, [&](const MTPDpageBlockCover &data) {
  3345. self(data.vcover(), self);
  3346. }, [&](const MTPDpageBlockEmbedPost &data) {
  3347. for (const auto &block : data.vblocks().v) {
  3348. self(block, self);
  3349. }
  3350. }, [&](const MTPDpageBlockCollage &data) {
  3351. for (const auto &block : data.vitems().v) {
  3352. self(block, self);
  3353. }
  3354. }, [&](const MTPDpageBlockSlideshow &data) {
  3355. for (const auto &block : data.vitems().v) {
  3356. self(block, self);
  3357. }
  3358. }, [&](const MTPDpageBlockDetails &data) {
  3359. for (const auto &block : data.vblocks().v) {
  3360. self(block, self);
  3361. }
  3362. }, [](const auto &) {});
  3363. };
  3364. for (const auto &block : page->data().vblocks().v) {
  3365. process(block, process);
  3366. }
  3367. }
  3368. const auto type = story ? WebPageType::Story : ParseWebPageType(data);
  3369. auto iv = (data.vcached_page() && !IgnoreIv(type))
  3370. ? std::make_unique<Iv::Data>(data, *data.vcached_page())
  3371. : nullptr;
  3372. webpageApplyFields(
  3373. page,
  3374. type,
  3375. qs(data.vurl()),
  3376. qs(data.vdisplay_url()),
  3377. siteName,
  3378. qs(data.vtitle().value_or_empty()),
  3379. (story ? story->caption() : description),
  3380. storyId,
  3381. (story
  3382. ? story->photo()
  3383. : photo
  3384. ? processPhoto(*photo).get()
  3385. : nullptr),
  3386. (story
  3387. ? story->document()
  3388. : document
  3389. ? processDocument(*document).get()
  3390. : lookupThemeDocument()),
  3391. WebPageCollage(this, data),
  3392. std::move(iv),
  3393. lookupStickerSet(),
  3394. lookupUniqueGift(),
  3395. data.vduration().value_or_empty(),
  3396. qs(data.vauthor().value_or_empty()),
  3397. data.is_has_large_media(),
  3398. data.is_video_cover_photo(),
  3399. pendingTill);
  3400. }
  3401. void Session::webpageApplyFields(
  3402. not_null<WebPageData*> page,
  3403. WebPageType type,
  3404. const QString &url,
  3405. const QString &displayUrl,
  3406. const QString &siteName,
  3407. const QString &title,
  3408. const TextWithEntities &description,
  3409. FullStoryId storyId,
  3410. PhotoData *photo,
  3411. DocumentData *document,
  3412. WebPageCollage &&collage,
  3413. std::unique_ptr<Iv::Data> iv,
  3414. std::unique_ptr<WebPageStickerSet> stickerSet,
  3415. std::shared_ptr<UniqueGift> uniqueGift,
  3416. int duration,
  3417. const QString &author,
  3418. bool hasLargeMedia,
  3419. bool photoIsVideoCover,
  3420. TimeId pendingTill) {
  3421. const auto requestPending = (!page->pendingTill && pendingTill > 0);
  3422. const auto changed = page->applyChanges(
  3423. type,
  3424. url,
  3425. displayUrl,
  3426. siteName,
  3427. title,
  3428. description,
  3429. storyId,
  3430. photo,
  3431. document,
  3432. std::move(collage),
  3433. std::move(iv),
  3434. std::move(stickerSet),
  3435. std::move(uniqueGift),
  3436. duration,
  3437. author,
  3438. hasLargeMedia,
  3439. photoIsVideoCover,
  3440. pendingTill);
  3441. if (requestPending) {
  3442. _session->api().requestWebPageDelayed(page);
  3443. }
  3444. if (changed) {
  3445. notifyWebPageUpdateDelayed(page);
  3446. }
  3447. }
  3448. not_null<GameData*> Session::game(GameId id) {
  3449. auto i = _games.find(id);
  3450. if (i == _games.cend()) {
  3451. i = _games.emplace(id, std::make_unique<GameData>(this, id)).first;
  3452. }
  3453. return i->second.get();
  3454. }
  3455. not_null<GameData*> Session::processGame(const MTPDgame &data) {
  3456. const auto result = game(data.vid().v);
  3457. gameApplyFields(result, data);
  3458. return result;
  3459. }
  3460. not_null<GameData*> Session::game(
  3461. GameId id,
  3462. const uint64 &accessHash,
  3463. const QString &shortName,
  3464. const QString &title,
  3465. const QString &description,
  3466. PhotoData *photo,
  3467. DocumentData *document) {
  3468. const auto result = game(id);
  3469. gameApplyFields(
  3470. result,
  3471. accessHash,
  3472. shortName,
  3473. title,
  3474. description,
  3475. photo,
  3476. document);
  3477. return result;
  3478. }
  3479. void Session::gameConvert(
  3480. not_null<GameData*> original,
  3481. const MTPGame &data) {
  3482. Expects(data.type() == mtpc_game);
  3483. const auto id = data.c_game().vid().v;
  3484. if (original->id != id) {
  3485. auto i = _games.find(id);
  3486. if (i == _games.end()) {
  3487. const auto j = _games.find(original->id);
  3488. Assert(j != _games.end());
  3489. auto owned = std::move(j->second);
  3490. _games.erase(j);
  3491. i = _games.emplace(id, std::move(owned)).first;
  3492. }
  3493. original->id = id;
  3494. original->accessHash = 0;
  3495. if (i->second.get() != original) {
  3496. gameApplyFields(i->second.get(), data.c_game());
  3497. }
  3498. }
  3499. gameApplyFields(original, data.c_game());
  3500. }
  3501. void Session::gameApplyFields(
  3502. not_null<GameData*> game,
  3503. const MTPDgame &data) {
  3504. const auto document = data.vdocument();
  3505. gameApplyFields(
  3506. game,
  3507. data.vaccess_hash().v,
  3508. qs(data.vshort_name()),
  3509. qs(data.vtitle()),
  3510. qs(data.vdescription()),
  3511. processPhoto(data.vphoto()),
  3512. document ? processDocument(*document).get() : nullptr);
  3513. }
  3514. void Session::gameApplyFields(
  3515. not_null<GameData*> game,
  3516. const uint64 &accessHash,
  3517. const QString &shortName,
  3518. const QString &title,
  3519. const QString &description,
  3520. PhotoData *photo,
  3521. DocumentData *document) {
  3522. if (game->accessHash) {
  3523. return;
  3524. }
  3525. game->accessHash = accessHash;
  3526. game->shortName = shortName;
  3527. game->title = TextUtilities::SingleLine(title);
  3528. game->description = description;
  3529. game->photo = photo;
  3530. game->document = document;
  3531. notifyGameUpdateDelayed(game);
  3532. }
  3533. not_null<BotAppData*> Session::botApp(BotAppId id) {
  3534. const auto i = _botApps.find(id);
  3535. return (i != end(_botApps))
  3536. ? i->second.get()
  3537. : _botApps.emplace(
  3538. id,
  3539. std::make_unique<BotAppData>(this, id)).first->second.get();
  3540. }
  3541. BotAppData *Session::findBotApp(PeerId botId, const QString &appName) const {
  3542. for (const auto &[id, app] : _botApps) {
  3543. if (app->botId == botId && app->shortName == appName) {
  3544. return app.get();
  3545. }
  3546. }
  3547. return nullptr;
  3548. }
  3549. BotAppData *Session::processBotApp(
  3550. PeerId botId,
  3551. const MTPBotApp &data) {
  3552. return data.match([&](const MTPDbotApp &data) {
  3553. const auto result = botApp(data.vid().v);
  3554. result->botId = botId;
  3555. result->shortName = qs(data.vshort_name());
  3556. result->title = qs(data.vtitle());
  3557. result->description = qs(data.vdescription());
  3558. result->photo = processPhoto(data.vphoto());
  3559. result->document = data.vdocument()
  3560. ? processDocument(*data.vdocument()).get()
  3561. : nullptr;
  3562. result->accessHash = data.vaccess_hash().v;
  3563. result->hash = data.vhash().v;
  3564. return result.get();
  3565. }, [](const MTPDbotAppNotModified &) {
  3566. return (BotAppData*)nullptr;
  3567. });
  3568. }
  3569. not_null<PollData*> Session::poll(PollId id) {
  3570. auto i = _polls.find(id);
  3571. if (i == _polls.cend()) {
  3572. i = _polls.emplace(id, std::make_unique<PollData>(this, id)).first;
  3573. }
  3574. return i->second.get();
  3575. }
  3576. not_null<PollData*> Session::processPoll(const MTPPoll &data) {
  3577. return data.match([&](const MTPDpoll &data) {
  3578. const auto id = data.vid().v;
  3579. const auto result = poll(id);
  3580. const auto changed = result->applyChanges(data);
  3581. if (changed) {
  3582. notifyPollUpdateDelayed(result);
  3583. }
  3584. if (result->closeDate > 0 && !result->closed()) {
  3585. _pollsClosings.emplace(result->closeDate, result);
  3586. checkPollsClosings();
  3587. }
  3588. return result;
  3589. });
  3590. }
  3591. not_null<PollData*> Session::processPoll(const MTPDmessageMediaPoll &data) {
  3592. const auto result = processPoll(data.vpoll());
  3593. const auto changed = result->applyResults(data.vresults());
  3594. if (changed) {
  3595. notifyPollUpdateDelayed(result);
  3596. }
  3597. return result;
  3598. }
  3599. void Session::checkPollsClosings() {
  3600. const auto now = base::unixtime::now();
  3601. auto closest = 0;
  3602. for (auto i = _pollsClosings.begin(); i != _pollsClosings.end();) {
  3603. if (i->first <= now) {
  3604. if (i->second->closeByTimer()) {
  3605. notifyPollUpdateDelayed(i->second);
  3606. }
  3607. i = _pollsClosings.erase(i);
  3608. } else {
  3609. if (!closest) {
  3610. closest = i->first;
  3611. }
  3612. ++i;
  3613. }
  3614. }
  3615. if (closest) {
  3616. _pollsClosingTimer.callOnce((closest - now) * crl::time(1000));
  3617. } else {
  3618. _pollsClosingTimer.cancel();
  3619. }
  3620. }
  3621. void Session::applyUpdate(const MTPDupdateMessagePoll &update) {
  3622. const auto updated = [&] {
  3623. const auto poll = update.vpoll();
  3624. const auto i = _polls.find(update.vpoll_id().v);
  3625. return (i == end(_polls))
  3626. ? nullptr
  3627. : poll
  3628. ? processPoll(*poll).get()
  3629. : i->second.get();
  3630. }();
  3631. if (updated && updated->applyResults(update.vresults())) {
  3632. notifyPollUpdateDelayed(updated);
  3633. }
  3634. }
  3635. void Session::applyUpdate(const MTPDupdateChatParticipants &update) {
  3636. const auto chatId = update.vparticipants().match([](const auto &update) {
  3637. return update.vchat_id().v;
  3638. });
  3639. if (const auto chat = chatLoaded(chatId)) {
  3640. ApplyChatUpdate(chat, update);
  3641. for (const auto &user : chat->participants) {
  3642. if (user->isBot() && !user->botInfo->inited) {
  3643. _session->api().requestFullPeer(user);
  3644. }
  3645. }
  3646. }
  3647. }
  3648. void Session::applyUpdate(const MTPDupdateChatParticipantAdd &update) {
  3649. if (const auto chat = chatLoaded(update.vchat_id().v)) {
  3650. ApplyChatUpdate(chat, update);
  3651. }
  3652. }
  3653. void Session::applyUpdate(const MTPDupdateChatParticipantDelete &update) {
  3654. if (const auto chat = chatLoaded(update.vchat_id().v)) {
  3655. ApplyChatUpdate(chat, update);
  3656. }
  3657. }
  3658. void Session::applyUpdate(const MTPDupdateChatParticipantAdmin &update) {
  3659. if (const auto chat = chatLoaded(update.vchat_id().v)) {
  3660. ApplyChatUpdate(chat, update);
  3661. }
  3662. }
  3663. void Session::applyUpdate(const MTPDupdateChatDefaultBannedRights &update) {
  3664. if (const auto peer = peerLoaded(peerFromMTP(update.vpeer()))) {
  3665. if (const auto chat = peer->asChat()) {
  3666. ApplyChatUpdate(chat, update);
  3667. } else if (const auto channel = peer->asChannel()) {
  3668. ApplyChannelUpdate(channel, update);
  3669. } else {
  3670. LOG(("API Error: "
  3671. "User received in updateChatDefaultBannedRights."));
  3672. }
  3673. }
  3674. }
  3675. not_null<Data::CloudImage*> Session::location(const LocationPoint &point) {
  3676. const auto i = _locations.find(point);
  3677. if (i != _locations.cend()) {
  3678. return i->second.get();
  3679. }
  3680. const auto location = Data::ComputeLocation(point);
  3681. const auto prepared = ImageWithLocation{
  3682. .location = ImageLocation(
  3683. { location },
  3684. location.width,
  3685. location.height)
  3686. };
  3687. return _locations.emplace(
  3688. point,
  3689. std::make_unique<Data::CloudImage>(
  3690. _session,
  3691. prepared)).first->second.get();
  3692. }
  3693. void Session::registerPhotoItem(
  3694. not_null<const PhotoData*> photo,
  3695. not_null<HistoryItem*> item) {
  3696. _photoItems[photo].insert(item);
  3697. }
  3698. void Session::unregisterPhotoItem(
  3699. not_null<const PhotoData*> photo,
  3700. not_null<HistoryItem*> item) {
  3701. const auto i = _photoItems.find(photo);
  3702. if (i != _photoItems.end()) {
  3703. auto &items = i->second;
  3704. if (items.remove(item) && items.empty()) {
  3705. _photoItems.erase(i);
  3706. }
  3707. }
  3708. }
  3709. void Session::registerDocumentItem(
  3710. not_null<const DocumentData*> document,
  3711. not_null<HistoryItem*> item) {
  3712. _documentItems[document].insert(item);
  3713. }
  3714. void Session::unregisterDocumentItem(
  3715. not_null<const DocumentData*> document,
  3716. not_null<HistoryItem*> item) {
  3717. const auto i = _documentItems.find(document);
  3718. if (i != _documentItems.end()) {
  3719. auto &items = i->second;
  3720. if (items.remove(item) && items.empty()) {
  3721. _documentItems.erase(i);
  3722. }
  3723. }
  3724. }
  3725. void Session::registerWebPageView(
  3726. not_null<const WebPageData*> page,
  3727. not_null<ViewElement*> view) {
  3728. _webpageViews[page].insert(view);
  3729. }
  3730. void Session::unregisterWebPageView(
  3731. not_null<const WebPageData*> page,
  3732. not_null<ViewElement*> view) {
  3733. const auto i = _webpageViews.find(page);
  3734. if (i != _webpageViews.end()) {
  3735. auto &items = i->second;
  3736. if (items.remove(view) && items.empty()) {
  3737. _webpageViews.erase(i);
  3738. }
  3739. }
  3740. }
  3741. void Session::registerWebPageItem(
  3742. not_null<const WebPageData*> page,
  3743. not_null<HistoryItem*> item) {
  3744. _webpageItems[page].insert(item);
  3745. }
  3746. void Session::unregisterWebPageItem(
  3747. not_null<const WebPageData*> page,
  3748. not_null<HistoryItem*> item) {
  3749. const auto i = _webpageItems.find(page);
  3750. if (i != _webpageItems.end()) {
  3751. auto &items = i->second;
  3752. if (items.remove(item) && items.empty()) {
  3753. _webpageItems.erase(i);
  3754. }
  3755. }
  3756. }
  3757. void Session::registerGameView(
  3758. not_null<const GameData*> game,
  3759. not_null<ViewElement*> view) {
  3760. _gameViews[game].insert(view);
  3761. }
  3762. void Session::unregisterGameView(
  3763. not_null<const GameData*> game,
  3764. not_null<ViewElement*> view) {
  3765. const auto i = _gameViews.find(game);
  3766. if (i != _gameViews.end()) {
  3767. auto &items = i->second;
  3768. if (items.remove(view) && items.empty()) {
  3769. _gameViews.erase(i);
  3770. }
  3771. }
  3772. }
  3773. void Session::registerPollView(
  3774. not_null<const PollData*> poll,
  3775. not_null<ViewElement*> view) {
  3776. _pollViews[poll].insert(view);
  3777. }
  3778. void Session::unregisterPollView(
  3779. not_null<const PollData*> poll,
  3780. not_null<ViewElement*> view) {
  3781. const auto i = _pollViews.find(poll);
  3782. if (i != _pollViews.end()) {
  3783. auto &items = i->second;
  3784. if (items.remove(view) && items.empty()) {
  3785. _pollViews.erase(i);
  3786. }
  3787. }
  3788. }
  3789. void Session::registerContactView(
  3790. UserId contactId,
  3791. not_null<ViewElement*> view) {
  3792. if (!contactId) {
  3793. return;
  3794. }
  3795. _contactViews[contactId].insert(view);
  3796. }
  3797. void Session::unregisterContactView(
  3798. UserId contactId,
  3799. not_null<ViewElement*> view) {
  3800. if (!contactId) {
  3801. return;
  3802. }
  3803. const auto i = _contactViews.find(contactId);
  3804. if (i != _contactViews.end()) {
  3805. auto &items = i->second;
  3806. if (items.remove(view) && items.empty()) {
  3807. _contactViews.erase(i);
  3808. }
  3809. }
  3810. }
  3811. void Session::registerContactItem(
  3812. UserId contactId,
  3813. not_null<HistoryItem*> item) {
  3814. if (!contactId) {
  3815. return;
  3816. }
  3817. const auto contact = userLoaded(contactId);
  3818. const auto canShare = contact ? contact->canShareThisContact() : false;
  3819. _contactItems[contactId].insert(item);
  3820. if (contact && canShare != contact->canShareThisContact()) {
  3821. session().changes().peerUpdated(
  3822. contact,
  3823. PeerUpdate::Flag::CanShareContact);
  3824. }
  3825. if (const auto i = _views.find(item); i != _views.end()) {
  3826. for (const auto view : i->second) {
  3827. if (const auto media = view->media()) {
  3828. media->updateSharedContactUserId(contactId);
  3829. }
  3830. }
  3831. }
  3832. }
  3833. void Session::unregisterContactItem(
  3834. UserId contactId,
  3835. not_null<HistoryItem*> item) {
  3836. if (!contactId) {
  3837. return;
  3838. }
  3839. const auto contact = userLoaded(contactId);
  3840. const auto canShare = contact ? contact->canShareThisContact() : false;
  3841. const auto i = _contactItems.find(contactId);
  3842. if (i != _contactItems.end()) {
  3843. auto &items = i->second;
  3844. if (items.remove(item) && items.empty()) {
  3845. _contactItems.erase(i);
  3846. }
  3847. }
  3848. if (contact && canShare != contact->canShareThisContact()) {
  3849. session().changes().peerUpdated(
  3850. contact,
  3851. PeerUpdate::Flag::CanShareContact);
  3852. }
  3853. }
  3854. void Session::registerCallItem(not_null<HistoryItem*> item) {
  3855. _callItems.emplace(item);
  3856. }
  3857. void Session::unregisterCallItem(not_null<HistoryItem*> item) {
  3858. _callItems.erase(item);
  3859. }
  3860. void Session::destroyAllCallItems() {
  3861. while (!_callItems.empty()) {
  3862. (*_callItems.begin())->destroy();
  3863. }
  3864. }
  3865. void Session::registerStoryItem(
  3866. FullStoryId id,
  3867. not_null<HistoryItem*> item) {
  3868. _storyItems[id].emplace(item);
  3869. }
  3870. void Session::unregisterStoryItem(
  3871. FullStoryId id,
  3872. not_null<HistoryItem*> item) {
  3873. const auto i = _storyItems.find(id);
  3874. if (i != _storyItems.end()) {
  3875. auto &items = i->second;
  3876. if (items.remove(item) && items.empty()) {
  3877. _storyItems.erase(i);
  3878. }
  3879. }
  3880. }
  3881. void Session::refreshStoryItemViews(FullStoryId id) {
  3882. const auto i = _storyItems.find(id);
  3883. if (i != _storyItems.end()) {
  3884. for (const auto item : i->second) {
  3885. if (const auto media = item->media()) {
  3886. if (media->storyMention()) {
  3887. item->updateStoryMentionText();
  3888. }
  3889. }
  3890. requestItemViewRefresh(item);
  3891. }
  3892. }
  3893. }
  3894. void Session::documentMessageRemoved(not_null<DocumentData*> document) {
  3895. if (_documentItems.find(document) != _documentItems.end()) {
  3896. return;
  3897. }
  3898. if (document->loading()) {
  3899. document->cancel();
  3900. }
  3901. }
  3902. void Session::checkPlayingAnimations() {
  3903. auto check = base::flat_set<not_null<ViewElement*>>();
  3904. for (const auto &view : _heavyViewParts) {
  3905. if (const auto media = view->media()) {
  3906. if (const auto document = media->getDocument()) {
  3907. if (document->isAnimation() || document->isVideoFile()) {
  3908. check.emplace(view);
  3909. }
  3910. } else if (const auto photo = media->getPhoto()) {
  3911. if (photo->hasVideo()) {
  3912. check.emplace(view);
  3913. }
  3914. }
  3915. }
  3916. }
  3917. for (const auto &view : check) {
  3918. view->media()->checkAnimation();
  3919. }
  3920. }
  3921. HistoryItem *Session::findWebPageItem(not_null<WebPageData*> page) const {
  3922. const auto i = _webpageItems.find(page);
  3923. if (i != _webpageItems.end()) {
  3924. for (const auto &item : i->second) {
  3925. if (item->isRegular()) {
  3926. return item;
  3927. }
  3928. }
  3929. }
  3930. return nullptr;
  3931. }
  3932. QString Session::findContactPhone(not_null<UserData*> contact) const {
  3933. const auto result = contact->phone();
  3934. return result.isEmpty()
  3935. ? findContactPhone(peerToUser(contact->id))
  3936. : Ui::FormatPhone(result);
  3937. }
  3938. QString Session::findContactPhone(UserId contactId) const {
  3939. const auto i = _contactItems.find(contactId);
  3940. if (i != _contactItems.end()) {
  3941. if (const auto media = (*begin(i->second))->media()) {
  3942. if (const auto contact = media->sharedContact()) {
  3943. return contact->phoneNumber;
  3944. }
  3945. }
  3946. }
  3947. return QString();
  3948. }
  3949. bool Session::hasPendingWebPageGamePollNotification() const {
  3950. return !_webpagesUpdated.empty()
  3951. || !_gamesUpdated.empty()
  3952. || !_pollsUpdated.empty();
  3953. }
  3954. void Session::notifyWebPageUpdateDelayed(not_null<WebPageData*> page) {
  3955. const auto invoke = !hasPendingWebPageGamePollNotification();
  3956. _webpagesUpdated.insert(page);
  3957. if (invoke) {
  3958. crl::on_main(_session, [=] { sendWebPageGamePollNotifications(); });
  3959. }
  3960. }
  3961. void Session::notifyGameUpdateDelayed(not_null<GameData*> game) {
  3962. const auto invoke = !hasPendingWebPageGamePollNotification();
  3963. _gamesUpdated.insert(game);
  3964. if (invoke) {
  3965. crl::on_main(_session, [=] { sendWebPageGamePollNotifications(); });
  3966. }
  3967. }
  3968. void Session::notifyPollUpdateDelayed(not_null<PollData*> poll) {
  3969. const auto invoke = !hasPendingWebPageGamePollNotification();
  3970. _pollsUpdated.insert(poll);
  3971. if (invoke) {
  3972. crl::on_main(_session, [=] { sendWebPageGamePollNotifications(); });
  3973. }
  3974. }
  3975. void Session::sendWebPageGamePollNotifications() {
  3976. auto resize = std::vector<not_null<ViewElement*>>();
  3977. for (const auto &page : base::take(_webpagesUpdated)) {
  3978. _webpageUpdates.fire_copy(page);
  3979. if (const auto i = _webpageViews.find(page)
  3980. ; i != _webpageViews.end()) {
  3981. resize.insert(end(resize), begin(i->second), end(i->second));
  3982. }
  3983. }
  3984. for (const auto &game : base::take(_gamesUpdated)) {
  3985. if (const auto i = _gameViews.find(game); i != _gameViews.end()) {
  3986. resize.insert(end(resize), begin(i->second), end(i->second));
  3987. }
  3988. }
  3989. for (const auto &poll : base::take(_pollsUpdated)) {
  3990. if (const auto i = _pollViews.find(poll); i != _pollViews.end()) {
  3991. resize.insert(end(resize), begin(i->second), end(i->second));
  3992. }
  3993. }
  3994. for (const auto &view : resize) {
  3995. requestViewResize(view);
  3996. }
  3997. }
  3998. rpl::producer<not_null<WebPageData*>> Session::webPageUpdates() const {
  3999. return _webpageUpdates.events();
  4000. }
  4001. void Session::channelDifferenceTooLong(not_null<ChannelData*> channel) {
  4002. _channelDifferenceTooLong.fire_copy(channel);
  4003. }
  4004. rpl::producer<not_null<ChannelData*>> Session::channelDifferenceTooLong() const {
  4005. return _channelDifferenceTooLong.events();
  4006. }
  4007. void Session::registerItemView(not_null<ViewElement*> view) {
  4008. _views[view->data()].push_back(view);
  4009. }
  4010. void Session::unregisterItemView(not_null<ViewElement*> view) {
  4011. Expects(!_heavyViewParts.contains(view));
  4012. _shownSpoilers.remove(view);
  4013. const auto i = _views.find(view->data());
  4014. if (i != end(_views)) {
  4015. auto &list = i->second;
  4016. list.erase(ranges::remove(list, view), end(list));
  4017. if (list.empty()) {
  4018. _views.erase(i);
  4019. }
  4020. }
  4021. using namespace HistoryView;
  4022. if (Element::Hovered() == view) {
  4023. Element::Hovered(nullptr);
  4024. }
  4025. if (Element::Pressed() == view) {
  4026. Element::Pressed(nullptr);
  4027. }
  4028. if (Element::HoveredLink() == view) {
  4029. Element::HoveredLink(nullptr);
  4030. }
  4031. if (Element::PressedLink() == view) {
  4032. Element::PressedLink(nullptr);
  4033. }
  4034. if (Element::Moused() == view) {
  4035. Element::Moused(nullptr);
  4036. }
  4037. }
  4038. not_null<Folder*> Session::folder(FolderId id) {
  4039. if (const auto result = folderLoaded(id)) {
  4040. return result;
  4041. }
  4042. const auto &[it, ok] = _folders.emplace(
  4043. id,
  4044. std::make_unique<Folder>(this, id));
  4045. return it->second.get();
  4046. }
  4047. Folder *Session::folderLoaded(FolderId id) const {
  4048. const auto it = _folders.find(id);
  4049. return (it == end(_folders)) ? nullptr : it->second.get();
  4050. }
  4051. not_null<Folder*> Session::processFolder(const MTPFolder &data) {
  4052. return data.match([&](const MTPDfolder &data) {
  4053. return processFolder(data);
  4054. });
  4055. }
  4056. not_null<Folder*> Session::processFolder(const MTPDfolder &data) {
  4057. return folder(data.vid().v);
  4058. }
  4059. not_null<Dialogs::MainList*> Session::chatsListFor(
  4060. not_null<Dialogs::Entry*> entry) {
  4061. const auto topic = entry->asTopic();
  4062. return topic
  4063. ? topic->forum()->topicsList()
  4064. : entry->asSublist()
  4065. ? _savedMessages->chatsList()
  4066. : chatsList(entry->folder());
  4067. }
  4068. not_null<Dialogs::MainList*> Session::chatsList(Data::Folder *folder) {
  4069. return folder ? folder->chatsList().get() : &_chatsList;
  4070. }
  4071. not_null<const Dialogs::MainList*> Session::chatsList(
  4072. Data::Folder *folder) const {
  4073. return folder ? folder->chatsList() : &_chatsList;
  4074. }
  4075. not_null<Dialogs::IndexedList*> Session::contactsList() {
  4076. return &_contactsList;
  4077. }
  4078. not_null<Dialogs::IndexedList*> Session::contactsNoChatsList() {
  4079. return &_contactsNoChatsList;
  4080. }
  4081. void Session::refreshChatListEntry(Dialogs::Key key) {
  4082. Expects(key.entry()->folderKnown());
  4083. using namespace Dialogs;
  4084. const auto entry = key.entry();
  4085. const auto history = entry->asHistory();
  4086. const auto topic = entry->asTopic();
  4087. const auto mainList = chatsListFor(entry);
  4088. auto event = ChatListEntryRefresh{ .key = key };
  4089. const auto creating = event.existenceChanged = !entry->inChatList();
  4090. if (creating && topic && topic->creating()) {
  4091. return;
  4092. } else if (event.existenceChanged) {
  4093. const auto mainRow = entry->addToChatList(0, mainList);
  4094. _contactsNoChatsList.remove(key, mainRow);
  4095. } else {
  4096. event.moved = entry->adjustByPosInChatList(0, mainList);
  4097. }
  4098. if (event) {
  4099. _chatListEntryRefreshes.fire(std::move(event));
  4100. }
  4101. if (!history) {
  4102. return;
  4103. }
  4104. for (const auto &filter : _chatsFilters->list()) {
  4105. const auto id = filter.id();
  4106. if (!id) {
  4107. continue;
  4108. }
  4109. const auto filterList = chatsFilters().chatsList(id);
  4110. auto event = ChatListEntryRefresh{ .key = key, .filterId = id };
  4111. if (filter.contains(history)) {
  4112. event.existenceChanged = !entry->inChatList(id);
  4113. if (event.existenceChanged) {
  4114. entry->addToChatList(id, filterList);
  4115. } else {
  4116. event.moved = entry->adjustByPosInChatList(id, filterList);
  4117. }
  4118. } else if (entry->inChatList(id)) {
  4119. entry->removeFromChatList(id, filterList);
  4120. event.existenceChanged = true;
  4121. }
  4122. if (event) {
  4123. _chatListEntryRefreshes.fire(std::move(event));
  4124. }
  4125. }
  4126. if (creating) {
  4127. if (const auto from = history->peer->migrateFrom()) {
  4128. if (const auto migrated = historyLoaded(from)) {
  4129. removeChatListEntry(migrated);
  4130. }
  4131. }
  4132. if (const auto forum = history->peer->forum()) {
  4133. forum->preloadTopics();
  4134. }
  4135. }
  4136. }
  4137. void Session::removeChatListEntry(Dialogs::Key key) {
  4138. using namespace Dialogs;
  4139. const auto entry = key.entry();
  4140. if (!entry->inChatList()) {
  4141. return;
  4142. }
  4143. Assert(entry->folderKnown());
  4144. for (const auto &filter : _chatsFilters->list()) {
  4145. const auto id = filter.id();
  4146. if (id && entry->inChatList(id)) {
  4147. entry->removeFromChatList(id, chatsFilters().chatsList(id));
  4148. _chatListEntryRefreshes.fire(ChatListEntryRefresh{
  4149. .key = key,
  4150. .filterId = id,
  4151. .existenceChanged = true
  4152. });
  4153. }
  4154. }
  4155. const auto mainList = chatsListFor(entry);
  4156. entry->removeFromChatList(0, mainList);
  4157. _chatListEntryRefreshes.fire(ChatListEntryRefresh{
  4158. .key = key,
  4159. .existenceChanged = true
  4160. });
  4161. if (_contactsList.contains(key)) {
  4162. if (!_contactsNoChatsList.contains(key)) {
  4163. _contactsNoChatsList.addByName(key);
  4164. }
  4165. }
  4166. if (const auto topic = key.topic()) {
  4167. Core::App().notifications().clearFromTopic(topic);
  4168. } else if (const auto history = key.history()) {
  4169. Core::App().notifications().clearFromHistory(history);
  4170. }
  4171. }
  4172. auto Session::chatListEntryRefreshes() const
  4173. -> rpl::producer<ChatListEntryRefresh> {
  4174. return _chatListEntryRefreshes.events();
  4175. }
  4176. void Session::dialogsRowReplaced(DialogsRowReplacement replacement) {
  4177. _dialogsRowReplacements.fire(std::move(replacement));
  4178. }
  4179. auto Session::dialogsRowReplacements() const
  4180. -> rpl::producer<DialogsRowReplacement> {
  4181. return _dialogsRowReplacements.events();
  4182. }
  4183. void Session::serviceNotification(
  4184. const TextWithEntities &message,
  4185. const MTPMessageMedia &media,
  4186. bool invertMedia) {
  4187. const auto date = base::unixtime::now();
  4188. if (!peerLoaded(PeerData::kServiceNotificationsId)) {
  4189. processUser(MTP_user(
  4190. MTP_flags(
  4191. MTPDuser::Flag::f_first_name
  4192. | MTPDuser::Flag::f_phone
  4193. | MTPDuser::Flag::f_status
  4194. | MTPDuser::Flag::f_verified),
  4195. MTP_long(peerToUser(PeerData::kServiceNotificationsId).bare),
  4196. MTPlong(), // access_hash
  4197. MTP_string("Telegram"),
  4198. MTPstring(), // last_name
  4199. MTPstring(), // username
  4200. MTP_string("42777"),
  4201. MTP_userProfilePhotoEmpty(),
  4202. MTP_userStatusRecently(MTP_flags(0)),
  4203. MTPint(), // bot_info_version
  4204. MTPVector<MTPRestrictionReason>(),
  4205. MTPstring(), // bot_inline_placeholder
  4206. MTPstring(), // lang_code
  4207. MTPEmojiStatus(),
  4208. MTPVector<MTPUsername>(),
  4209. MTPint(), // stories_max_id
  4210. MTPPeerColor(), // color
  4211. MTPPeerColor(), // profile_color
  4212. MTPint(), // bot_active_users
  4213. MTPlong(), // bot_verification_icon
  4214. MTPlong())); // send_paid_messages_stars
  4215. }
  4216. const auto history = this->history(PeerData::kServiceNotificationsId);
  4217. const auto insert = [=] {
  4218. insertCheckedServiceNotification(message, media, date, invertMedia);
  4219. };
  4220. if (!history->folderKnown()) {
  4221. histories().requestDialogEntry(history, insert);
  4222. } else {
  4223. insert();
  4224. }
  4225. }
  4226. void Session::insertCheckedServiceNotification(
  4227. const TextWithEntities &message,
  4228. const MTPMessageMedia &media,
  4229. TimeId date,
  4230. bool invertMedia) {
  4231. const auto flags = MTPDmessage::Flag::f_entities
  4232. | MTPDmessage::Flag::f_from_id
  4233. | MTPDmessage::Flag::f_media
  4234. | (invertMedia
  4235. ? MTPDmessage::Flag::f_invert_media
  4236. : MTPDmessage::Flag());
  4237. const auto localFlags = MessageFlag::ClientSideUnread
  4238. | MessageFlag::Local;
  4239. auto sending = TextWithEntities(), left = message;
  4240. while (TextUtilities::CutPart(sending, left, MaxMessageSize)) {
  4241. const auto id = nextLocalMessageId();
  4242. addNewMessage(
  4243. id,
  4244. MTP_message(
  4245. MTP_flags(flags),
  4246. MTP_int(0), // Not used (would've been trimmed to 32 bits).
  4247. peerToMTP(PeerData::kServiceNotificationsId),
  4248. MTPint(), // from_boosts_applied
  4249. peerToMTP(PeerData::kServiceNotificationsId),
  4250. MTPPeer(), // saved_peer_id
  4251. MTPMessageFwdHeader(),
  4252. MTPlong(), // via_bot_id
  4253. MTPlong(), // via_business_bot_id
  4254. MTPMessageReplyHeader(),
  4255. MTP_int(date),
  4256. MTP_string(sending.text),
  4257. media,
  4258. MTPReplyMarkup(),
  4259. Api::EntitiesToMTP(&session(), sending.entities),
  4260. MTPint(), // views
  4261. MTPint(), // forwards
  4262. MTPMessageReplies(),
  4263. MTPint(), // edit_date
  4264. MTPstring(),
  4265. MTPlong(),
  4266. MTPMessageReactions(),
  4267. MTPVector<MTPRestrictionReason>(),
  4268. MTPint(), // ttl_period
  4269. MTPint(), // quick_reply_shortcut_id
  4270. MTPlong(), // effect
  4271. MTPFactCheck(),
  4272. MTPint(), // report_delivery_until_date
  4273. MTPlong()), // paid_message_stars
  4274. localFlags,
  4275. NewMessageType::Unread);
  4276. }
  4277. sendHistoryChangeNotifications();
  4278. }
  4279. void Session::setMimeForwardIds(MessageIdsList &&list) {
  4280. _mimeForwardIds = std::move(list);
  4281. }
  4282. MessageIdsList Session::takeMimeForwardIds() {
  4283. return std::move(_mimeForwardIds);
  4284. }
  4285. void Session::setTopPromoted(
  4286. History *promoted,
  4287. const QString &type,
  4288. const QString &message) {
  4289. const auto changed = (_topPromoted != promoted);
  4290. if (!changed
  4291. && (!promoted || promoted->topPromotionMessage() == message)) {
  4292. return;
  4293. }
  4294. if (changed) {
  4295. if (_topPromoted) {
  4296. _topPromoted->cacheTopPromotion(false, QString(), QString());
  4297. }
  4298. }
  4299. const auto old = std::exchange(_topPromoted, promoted);
  4300. if (_topPromoted) {
  4301. histories().requestDialogEntry(_topPromoted);
  4302. _topPromoted->cacheTopPromotion(true, type, message);
  4303. _topPromoted->requestChatListMessage();
  4304. session().changes().historyUpdated(
  4305. _topPromoted,
  4306. HistoryUpdate::Flag::TopPromoted);
  4307. }
  4308. if (changed && old) {
  4309. session().changes().historyUpdated(
  4310. old,
  4311. HistoryUpdate::Flag::TopPromoted);
  4312. }
  4313. }
  4314. bool Session::updateWallpapers(const MTPaccount_WallPapers &data) {
  4315. return data.match([&](const MTPDaccount_wallPapers &data) {
  4316. setWallpapers(data.vwallpapers().v, data.vhash().v);
  4317. return true;
  4318. }, [&](const MTPDaccount_wallPapersNotModified &) {
  4319. return false;
  4320. });
  4321. }
  4322. void Session::setWallpapers(const QVector<MTPWallPaper> &data, uint64 hash) {
  4323. _wallpapersHash = hash;
  4324. _wallpapers.clear();
  4325. _wallpapers.reserve(data.size() + 2);
  4326. _wallpapers.push_back(Data::Legacy1DefaultWallPaper());
  4327. _wallpapers.back().setLocalImageAsThumbnail(std::make_shared<Image>(
  4328. u":/gui/art/bg_initial.jpg"_q));
  4329. for (const auto &paper : data) {
  4330. if (const auto parsed = Data::WallPaper::Create(&session(), paper)) {
  4331. _wallpapers.push_back(*parsed);
  4332. }
  4333. }
  4334. // Put the legacy2 (flowers) wallpaper to the front of the list.
  4335. const auto legacy2 = ranges::find_if(
  4336. _wallpapers,
  4337. Data::IsLegacy2DefaultWallPaper);
  4338. if (legacy2 != end(_wallpapers)) {
  4339. ranges::rotate(begin(_wallpapers), legacy2, legacy2 + 1);
  4340. }
  4341. // Put the legacy3 (static gradient) wallpaper to the front of the list.
  4342. const auto legacy3 = ranges::find_if(
  4343. _wallpapers,
  4344. Data::IsLegacy3DefaultWallPaper);
  4345. if (legacy3 != end(_wallpapers)) {
  4346. ranges::rotate(begin(_wallpapers), legacy3, legacy3 + 1);
  4347. }
  4348. if (ranges::none_of(_wallpapers, Data::IsDefaultWallPaper)) {
  4349. _wallpapers.push_back(Data::DefaultWallPaper());
  4350. _wallpapers.back().setLocalImageAsThumbnail(std::make_shared<Image>(
  4351. u":/gui/art/bg_thumbnail.png"_q));
  4352. }
  4353. }
  4354. void Session::removeWallpaper(const WallPaper &paper) {
  4355. const auto i = ranges::find(_wallpapers, paper.id(), &WallPaper::id);
  4356. if (i != end(_wallpapers)) {
  4357. _wallpapers.erase(i);
  4358. }
  4359. }
  4360. const std::vector<WallPaper> &Session::wallpapers() const {
  4361. return _wallpapers;
  4362. }
  4363. uint64 Session::wallpapersHash() const {
  4364. return _wallpapersHash;
  4365. }
  4366. MTP::DcId Session::statsDcId(not_null<PeerData*> peer) {
  4367. const auto it = _peerStatsDcIds.find(peer);
  4368. return (it == end(_peerStatsDcIds)) ? MTP::DcId(0) : it->second;
  4369. }
  4370. void Session::applyStatsDcId(
  4371. not_null<PeerData*> peer,
  4372. MTP::DcId dcId) {
  4373. if (dcId != peer->session().mainDcId()) {
  4374. _peerStatsDcIds[peer] = dcId;
  4375. }
  4376. }
  4377. void Session::saveViewAsMessages(
  4378. not_null<Forum*> forum,
  4379. bool viewAsMessages) {
  4380. const auto channel = forum->channel();
  4381. if (const auto requestId = _viewAsMessagesRequests.take(channel)) {
  4382. _session->api().request(*requestId).cancel();
  4383. }
  4384. _viewAsMessagesRequests[channel] = _session->api().request(
  4385. MTPchannels_ToggleViewForumAsMessages(
  4386. channel->inputChannel,
  4387. MTP_bool(viewAsMessages))
  4388. ).done([=] {
  4389. _viewAsMessagesRequests.remove(channel);
  4390. }).fail([=] {
  4391. _viewAsMessagesRequests.remove(channel);
  4392. }).send();
  4393. channel->setViewAsMessagesFlag(viewAsMessages);
  4394. }
  4395. void Session::webViewResultSent(WebViewResultSent &&sent) {
  4396. return _webViewResultSent.fire(std::move(sent));
  4397. }
  4398. auto Session::webViewResultSent() const -> rpl::producer<WebViewResultSent> {
  4399. return _webViewResultSent.events();
  4400. }
  4401. rpl::producer<not_null<PeerData*>> Session::peerDecorationsUpdated() const {
  4402. return _peerDecorationsUpdated.events();
  4403. }
  4404. void Session::viewTagsChanged(
  4405. not_null<ViewElement*> view,
  4406. std::vector<Data::ReactionId> &&was,
  4407. std::vector<Data::ReactionId> &&now) {
  4408. for (const auto &id : now) {
  4409. const auto i = ranges::remove(was, id);
  4410. if (i != end(was)) {
  4411. was.erase(i, end(was));
  4412. } else {
  4413. _viewsByTag[id].emplace(view);
  4414. }
  4415. }
  4416. for (const auto &id : was) {
  4417. const auto i = _viewsByTag.find(id);
  4418. if (i != end(_viewsByTag)
  4419. && i->second.remove(view)
  4420. && i->second.empty()) {
  4421. _viewsByTag.erase(i);
  4422. }
  4423. }
  4424. }
  4425. void Session::sentToScheduled(SentToScheduled value) {
  4426. _sentToScheduled.fire(std::move(value));
  4427. }
  4428. rpl::producer<SentToScheduled> Session::sentToScheduled() const {
  4429. return _sentToScheduled.events();
  4430. }
  4431. void Session::sentFromScheduled(SentFromScheduled value) {
  4432. _sentFromScheduled.fire(std::move(value));
  4433. }
  4434. rpl::producer<SentFromScheduled> Session::sentFromScheduled() const {
  4435. return _sentFromScheduled.events();
  4436. }
  4437. void Session::clearLocalStorage() {
  4438. _cache->close();
  4439. _cache->clear();
  4440. _bigFileCache->close();
  4441. _bigFileCache->clear();
  4442. }
  4443. } // namespace Data