history_item.cpp 179 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343
  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 "history/history_item.h"
  8. #include "api/api_premium.h"
  9. #include "api/api_sensitive_content.h"
  10. #include "lang/lang_keys.h"
  11. #include "mainwidget.h"
  12. #include "calls/calls_instance.h" // Core::App().calls().joinGroupCall.
  13. #include "history/view/history_view_item_preview.h"
  14. #include "history/view/history_view_message.h"
  15. #include "history/view/history_view_service_message.h"
  16. #include "history/view/media/history_view_media_grouped.h"
  17. #include "history/history_item_components.h"
  18. #include "history/history_item_helpers.h"
  19. #include "history/history_unread_things.h"
  20. #include "history/history.h"
  21. #include "iv/iv_data.h"
  22. #include "mtproto/mtproto_config.h"
  23. #include "ui/text/format_values.h"
  24. #include "ui/text/text_isolated_emoji.h"
  25. #include "ui/text/text_utilities.h"
  26. #include "settings/settings_credits_graphics.h" // ShowRefundInfoBox.
  27. #include "storage/file_upload.h"
  28. #include "storage/storage_shared_media.h"
  29. #include "main/main_account.h"
  30. #include "main/main_domain.h"
  31. #include "main/main_session.h"
  32. #include "main/main_session_settings.h"
  33. #include "menu/menu_ttl_validator.h"
  34. #include "apiwrap.h"
  35. #include "media/audio/media_audio.h"
  36. #include "core/application.h"
  37. #include "window/window_controller.h"
  38. #include "window/window_session_controller.h"
  39. #include "core/click_handler_types.h"
  40. #include "base/unixtime.h"
  41. #include "base/timer_rpl.h"
  42. #include "boxes/send_credits_box.h"
  43. #include "api/api_text_entities.h"
  44. #include "api/api_updates.h"
  45. #include "data/business/data_shortcut_messages.h"
  46. #include "data/components/scheduled_messages.h"
  47. #include "data/components/sponsored_messages.h"
  48. #include "data/notify/data_notify_settings.h"
  49. #include "data/data_bot_app.h"
  50. #include "data/data_saved_messages.h"
  51. #include "data/data_saved_sublist.h"
  52. #include "data/data_changes.h"
  53. #include "data/data_session.h"
  54. #include "data/data_message_reactions.h"
  55. #include "data/data_folder.h"
  56. #include "data/data_forum.h"
  57. #include "data/data_forum_topic.h"
  58. #include "data/data_channel.h"
  59. #include "data/data_chat.h"
  60. #include "data/data_game.h"
  61. #include "data/data_histories.h"
  62. #include "data/data_history_messages.h"
  63. #include "data/data_user.h"
  64. #include "data/data_group_call.h" // Data::GroupCall::id().
  65. #include "data/data_poll.h" // PollData::publicVotes.
  66. #include "data/data_stories.h"
  67. #include "data/data_web_page.h"
  68. #include "chat_helpers/stickers_gift_box_pack.h"
  69. #include "payments/payments_checkout_process.h" // CheckoutProcess::Start.
  70. #include "payments/payments_non_panel_process.h" // ProcessNonPanelPaymentFormFactory.
  71. #include "platform/platform_notifications_manager.h"
  72. #include "spellcheck/spellcheck_highlight_syntax.h"
  73. #include "styles/style_dialogs.h"
  74. namespace {
  75. constexpr auto kNotificationTextLimit = 255;
  76. constexpr auto kPinnedMessageTextLimit = 16;
  77. using ItemPreview = HistoryView::ItemPreview;
  78. template <typename T>
  79. [[nodiscard]] PreparedServiceText PrepareEmptyText(const T &) {
  80. return PreparedServiceText();
  81. };
  82. template <typename T>
  83. [[nodiscard]] PreparedServiceText PrepareErrorText(const T &data) {
  84. if constexpr (!std::is_same_v<T, MTPDmessageActionEmpty>) {
  85. const auto name = QString::fromUtf8(typeid(data).name());
  86. LOG(("API Error: %1 received.").arg(name));
  87. }
  88. return PreparedServiceText{ { tr::lng_message_empty(tr::now) } };
  89. }
  90. [[nodiscard]] TextWithEntities SpoilerLoginCode(TextWithEntities text) {
  91. const auto r = QRegularExpression(u"([\\d\\-]{4,8})"_q);
  92. const auto m = r.match(text.text);
  93. if (!m.hasMatch()) {
  94. return text;
  95. }
  96. const auto codeStart = int(m.capturedStart(1));
  97. const auto codeLength = int(m.capturedLength(1));
  98. auto i = text.entities.begin();
  99. const auto e = text.entities.end();
  100. while (i != e && i->offset() < codeStart) {
  101. if (i->offset() + i->length() > codeStart) {
  102. return text; // Entities should not intersect code.
  103. }
  104. ++i;
  105. }
  106. text.entities.insert(i, { EntityType::Spoiler, codeStart, codeLength });
  107. return text;
  108. }
  109. [[nodiscard]] bool HasNotEmojiAndSpaces(const QString &text) {
  110. if (text.isEmpty()) {
  111. return false;
  112. }
  113. auto emoji = 0;
  114. auto start = text.data();
  115. const auto end = start + text.size();
  116. while (start < end) {
  117. if (start->isSpace()) {
  118. ++start;
  119. } else if (Ui::Emoji::Find(start, end, &emoji)) {
  120. start += emoji;
  121. } else {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. [[nodiscard]] HistoryItemCommonFields ForwardedFields(
  128. HistoryItemCommonFields fields,
  129. not_null<History*> history,
  130. not_null<HistoryItem*> original) {
  131. if (fields.flags & MessageFlag::FakeHistoryItem) {
  132. return fields;
  133. }
  134. fields.flags |= NewForwardedFlags(history->peer, fields.from, original);
  135. return fields;
  136. }
  137. [[nodiscard]] TextWithEntities AmountAndStarCurrency(
  138. not_null<Main::Session*> session,
  139. int64 amount,
  140. const QString &currency) {
  141. if (currency == Ui::kCreditsCurrency) {
  142. return Ui::CreditsEmojiSmall(session).append(
  143. Lang::FormatCountDecimal(std::abs(amount)));
  144. }
  145. return { Ui::FillAmountAndCurrency(amount, currency) };
  146. }
  147. } // namespace
  148. void HistoryItem::HistoryItem::Destroyer::operator()(HistoryItem *value) {
  149. if (value) {
  150. value->destroy();
  151. }
  152. }
  153. struct HistoryItem::CreateConfig {
  154. ReplyFields reply;
  155. UserId viaBotId = 0;
  156. UserId viaBusinessBotId = 0;
  157. int viewsCount = -1;
  158. int forwardsCount = -1;
  159. int boostsApplied = 0;
  160. QString postAuthor;
  161. MsgId originalId = 0;
  162. TimeId originalDate = 0;
  163. PeerId originalSenderId = 0;
  164. QString originalSenderName;
  165. QString originalPostAuthor;
  166. PeerId savedSublistPeer = 0;
  167. QString forwardPsaType;
  168. PeerId savedFromPeer = 0;
  169. MsgId savedFromMsgId = 0;
  170. PeerId savedFromSenderId = 0;
  171. QString savedFromSenderName;
  172. bool savedFromOutgoing = false;
  173. TimeId editDate = 0;
  174. HistoryMessageMarkupData markup;
  175. HistoryMessageRepliesData replies;
  176. bool imported = false;
  177. // For messages created from existing messages (forwarded).
  178. const HistoryMessageReplyMarkup *inlineMarkup = nullptr;
  179. std::vector<Data::UnavailableReason> restrictions;
  180. };
  181. void HistoryItem::FillForwardedInfo(
  182. CreateConfig &config,
  183. const MTPDmessageFwdHeader &data) {
  184. config.originalId = data.vchannel_post().value_or_empty();
  185. config.originalDate = data.vdate().v;
  186. if (const auto fromId = data.vfrom_id()) {
  187. config.originalSenderId = peerFromMTP(*fromId);
  188. }
  189. config.originalSenderName = qs(data.vfrom_name().value_or_empty());
  190. config.originalPostAuthor = qs(data.vpost_author().value_or_empty());
  191. config.forwardPsaType = qs(data.vpsa_type().value_or_empty());
  192. const auto savedFromPeer = data.vsaved_from_peer();
  193. const auto savedFromMsgId = data.vsaved_from_msg_id();
  194. if (savedFromPeer && savedFromMsgId) {
  195. config.savedFromPeer = peerFromMTP(*savedFromPeer);
  196. config.savedFromMsgId = savedFromMsgId->v;
  197. }
  198. config.savedFromSenderId = data.vsaved_from_id()
  199. ? peerFromMTP(*data.vsaved_from_id())
  200. : PeerId();
  201. config.savedFromSenderName = qs(
  202. data.vsaved_from_name().value_or_empty());
  203. config.savedFromOutgoing = data.is_saved_out();
  204. config.imported = data.is_imported();
  205. }
  206. std::unique_ptr<Data::Media> HistoryItem::CreateMedia(
  207. not_null<HistoryItem*> item,
  208. const MTPMessageMedia &media) {
  209. using Result = std::unique_ptr<Data::Media>;
  210. return media.match([&](const MTPDmessageMediaContact &media) -> Result {
  211. return std::make_unique<Data::MediaContact>(
  212. item,
  213. media.vuser_id().v,
  214. qs(media.vfirst_name()),
  215. qs(media.vlast_name()),
  216. qs(media.vphone_number()),
  217. Data::SharedContact::ParseVcard(qs(media.vvcard())));
  218. }, [&](const MTPDmessageMediaGeo &media) -> Result {
  219. return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
  220. return std::make_unique<Data::MediaLocation>(
  221. item,
  222. Data::LocationPoint(point));
  223. }, [](const MTPDgeoPointEmpty &) -> Result {
  224. return nullptr;
  225. });
  226. }, [&](const MTPDmessageMediaGeoLive &media) -> Result {
  227. return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
  228. return std::make_unique<Data::MediaLocation>(
  229. item,
  230. Data::LocationPoint(point),
  231. media.vperiod().v);
  232. }, [](const MTPDgeoPointEmpty &) -> Result {
  233. return nullptr;
  234. });
  235. }, [&](const MTPDmessageMediaVenue &media) -> Result {
  236. return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
  237. return std::make_unique<Data::MediaLocation>(
  238. item,
  239. Data::LocationPoint(point),
  240. qs(media.vtitle()),
  241. qs(media.vaddress()));
  242. }, [](const MTPDgeoPointEmpty &data) -> Result {
  243. return nullptr;
  244. });
  245. }, [&](const MTPDmessageMediaPhoto &media) -> Result {
  246. const auto photo = media.vphoto();
  247. if (media.vttl_seconds()) {
  248. LOG(("App Error: "
  249. "Unexpected MTPMessageMediaPhoto "
  250. "with ttl_seconds in CreateMedia."));
  251. return nullptr;
  252. } else if (!photo) {
  253. LOG(("API Error: "
  254. "Got MTPMessageMediaPhoto "
  255. "without photo and without ttl_seconds."));
  256. return nullptr;
  257. }
  258. return photo->match([&](const MTPDphoto &photo) -> Result {
  259. return std::make_unique<Data::MediaPhoto>(
  260. item,
  261. item->history()->owner().processPhoto(photo),
  262. media.is_spoiler());
  263. }, [](const MTPDphotoEmpty &) -> Result {
  264. return nullptr;
  265. });
  266. }, [&](const MTPDmessageMediaDocument &media) -> Result {
  267. const auto document = media.vdocument();
  268. if (media.vttl_seconds() && media.is_video()) {
  269. LOG(("App Error: "
  270. "Unexpected MTPMessageMediaDocument "
  271. "with ttl_seconds in CreateMedia."));
  272. return nullptr;
  273. } else if (!document) {
  274. LOG(("API Error: "
  275. "Got MTPMessageMediaDocument "
  276. "without document and without ttl_seconds."));
  277. return nullptr;
  278. }
  279. return document->match([&](const MTPDdocument &document) -> Result {
  280. const auto list = media.valt_documents();
  281. const auto owner = &item->history()->owner();
  282. const auto data = owner->processDocument(document, list);
  283. using Args = Data::MediaFile::Args;
  284. return std::make_unique<Data::MediaFile>(item, data, Args{
  285. .ttlSeconds = media.vttl_seconds().value_or_empty(),
  286. .videoCover = (media.vvideo_cover()
  287. ? owner->processPhoto(*media.vvideo_cover()).get()
  288. : nullptr),
  289. .videoTimestamp = media.vvideo_timestamp().value_or_empty(),
  290. .hasQualitiesList = list && !list->v.isEmpty(),
  291. .skipPremiumEffect = media.is_nopremium(),
  292. .spoiler = media.is_spoiler(),
  293. });
  294. }, [](const MTPDdocumentEmpty &) -> Result {
  295. return nullptr;
  296. });
  297. }, [&](const MTPDmessageMediaWebPage &media) {
  298. using Flag = MediaWebPageFlag;
  299. const auto flags = Flag()
  300. | (media.is_force_large_media()
  301. ? Flag::ForceLargeMedia
  302. : Flag())
  303. | (media.is_force_small_media()
  304. ? Flag::ForceSmallMedia
  305. : Flag())
  306. | (media.is_manual() ? Flag::Manual : Flag())
  307. | (media.is_safe() ? Flag::Safe : Flag());
  308. return media.vwebpage().match([](const MTPDwebPageEmpty &) -> Result {
  309. return nullptr;
  310. }, [&](const MTPDwebPagePending &webpage) -> Result {
  311. return std::make_unique<Data::MediaWebPage>(
  312. item,
  313. item->history()->owner().processWebpage(webpage),
  314. flags);
  315. }, [&](const MTPDwebPage &webpage) -> Result {
  316. return std::make_unique<Data::MediaWebPage>(
  317. item,
  318. item->history()->owner().processWebpage(webpage),
  319. flags);
  320. }, [](const MTPDwebPageNotModified &) -> Result {
  321. LOG(("API Error: "
  322. "webPageNotModified is unexpected in message media."));
  323. return nullptr;
  324. });
  325. }, [&](const MTPDmessageMediaGame &media) -> Result {
  326. return media.vgame().match([&](const MTPDgame &game) {
  327. return std::make_unique<Data::MediaGame>(
  328. item,
  329. item->history()->owner().processGame(game));
  330. });
  331. }, [&](const MTPDmessageMediaInvoice &media) -> Result {
  332. return std::make_unique<Data::MediaInvoice>(
  333. item,
  334. Data::ComputeInvoiceData(item, media));
  335. }, [&](const MTPDmessageMediaPoll &media) -> Result {
  336. return std::make_unique<Data::MediaPoll>(
  337. item,
  338. item->history()->owner().processPoll(media));
  339. }, [&](const MTPDmessageMediaDice &media) -> Result {
  340. return std::make_unique<Data::MediaDice>(
  341. item,
  342. qs(media.vemoticon()),
  343. media.vvalue().v);
  344. }, [&](const MTPDmessageMediaStory &media) -> Result {
  345. return std::make_unique<Data::MediaStory>(item, FullStoryId{
  346. peerFromMTP(media.vpeer()),
  347. media.vid().v,
  348. }, media.is_via_mention());
  349. }, [&](const MTPDmessageMediaGiveaway &media) -> Result {
  350. return std::make_unique<Data::MediaGiveawayStart>(
  351. item,
  352. Data::ComputeGiveawayStartData(item, media));
  353. }, [&](const MTPDmessageMediaGiveawayResults &media) -> Result {
  354. return std::make_unique<Data::MediaGiveawayResults>(
  355. item,
  356. Data::ComputeGiveawayResultsData(item, media));
  357. }, [&](const MTPDmessageMediaPaidMedia &media) -> Result {
  358. return std::make_unique<Data::MediaInvoice>(
  359. item,
  360. Data::ComputeInvoiceData(item, media));
  361. }, [](const MTPDmessageMediaEmpty &) -> Result {
  362. return nullptr;
  363. }, [](const MTPDmessageMediaUnsupported &) -> Result {
  364. return nullptr;
  365. });
  366. }
  367. HistoryItem::HistoryItem(
  368. not_null<History*> history,
  369. MsgId id,
  370. const MTPDmessage &data,
  371. MessageFlags localFlags)
  372. : HistoryItem(history, {
  373. .id = id,
  374. .flags = FlagsFromMTP(id, data.vflags().v, localFlags),
  375. .from = data.vfrom_id() ? peerFromMTP(*data.vfrom_id()) : PeerId(0),
  376. .date = data.vdate().v,
  377. .shortcutId = data.vquick_reply_shortcut_id().value_or_empty(),
  378. .starsPaid = int(data.vpaid_message_stars().value_or_empty()),
  379. .effectId = data.veffect().value_or_empty(),
  380. }) {
  381. _boostsApplied = data.vfrom_boosts_applied().value_or_empty();
  382. // Called only for server-received messages, not locally created ones.
  383. applyInitialEffectWatched();
  384. const auto media = data.vmedia();
  385. const auto checked = media
  386. ? CheckMessageMedia(*media)
  387. : MediaCheckResult::Good;
  388. if (checked == MediaCheckResult::Unsupported) {
  389. _flags &= ~MessageFlag::HasPostAuthor;
  390. _flags |= MessageFlag::Legacy;
  391. createComponents(data);
  392. setText(UnsupportedMessageText());
  393. } else if (checked == MediaCheckResult::Empty) {
  394. AddComponents(HistoryServiceData::Bit());
  395. setServiceText({
  396. tr::lng_message_empty(tr::now, Ui::Text::WithEntities)
  397. });
  398. } else if ((checked == MediaCheckResult::HasUnsupportedTimeToLive)
  399. || (checked == MediaCheckResult::HasExpiredMediaTimeToLive)) {
  400. createServiceFromMtp(data);
  401. applyTTL(data);
  402. } else if (checked == MediaCheckResult::HasStoryMention) {
  403. setMedia(*data.vmedia());
  404. createServiceFromMtp(data);
  405. applyTTL(data);
  406. } else {
  407. createComponents(data);
  408. if (const auto media = data.vmedia()) {
  409. setMedia(*media);
  410. }
  411. auto textWithEntities = TextWithEntities{
  412. qs(data.vmessage()),
  413. Api::EntitiesFromMTP(
  414. &history->session(),
  415. data.ventities().value_or_empty())
  416. };
  417. setText(_media ? textWithEntities : EnsureNonEmpty(textWithEntities));
  418. if (const auto groupedId = data.vgrouped_id()) {
  419. setGroupId(
  420. MessageGroupId::FromRaw(
  421. history->peer->id,
  422. groupedId->v,
  423. _flags & MessageFlag::IsOrWasScheduled));
  424. }
  425. setReactions(data.vreactions());
  426. applyTTL(data);
  427. if (const auto check = FromMTP(this, data.vfactcheck())) {
  428. AddComponents(HistoryMessageFactcheck::Bit());
  429. Get<HistoryMessageFactcheck>()->data = check;
  430. }
  431. }
  432. if (const auto until = data.vreport_delivery_until_date()) {
  433. if (base::unixtime::now() < TimeId(until->v)) {
  434. history->owner().histories().reportDelivery(this);
  435. }
  436. }
  437. }
  438. HistoryItem::HistoryItem(
  439. not_null<History*> history,
  440. MsgId id,
  441. const MTPDmessageService &data,
  442. MessageFlags localFlags)
  443. : HistoryItem(history, {
  444. .id = id,
  445. .flags = FlagsFromMTP(id, data.vflags().v, localFlags),
  446. .from = data.vfrom_id() ? peerFromMTP(*data.vfrom_id()) : PeerId(0),
  447. .date = data.vdate().v,
  448. }) {
  449. data.vaction().match([&](const MTPDmessageActionPhoneCall &data) {
  450. createComponents(CreateConfig());
  451. _media = std::make_unique<Data::MediaCall>(
  452. this,
  453. Data::ComputeCallData(data));
  454. setTextValue({});
  455. }, [&](const auto &) {
  456. createServiceFromMtp(data);
  457. });
  458. setReactions(data.vreactions());
  459. applyTTL(data);
  460. }
  461. HistoryItem::HistoryItem(
  462. not_null<History*> history,
  463. MsgId id,
  464. const MTPDmessageEmpty &data,
  465. MessageFlags localFlags)
  466. : HistoryItem(
  467. history,
  468. { .id = id, .flags = localFlags },
  469. PreparedServiceText{ tr::lng_message_empty(
  470. tr::now,
  471. Ui::Text::WithEntities) }) {
  472. }
  473. HistoryItem::HistoryItem(
  474. not_null<History*> history,
  475. HistoryItemCommonFields &&fields,
  476. PreparedServiceText &&message,
  477. PhotoData *photo)
  478. : HistoryItem(history, fields) {
  479. setServiceText(std::move(message));
  480. if (photo) {
  481. _media = std::make_unique<Data::MediaPhoto>(
  482. this,
  483. history->peer,
  484. photo);
  485. }
  486. }
  487. HistoryItem::HistoryItem(
  488. not_null<History*> history,
  489. HistoryItemCommonFields &&fields,
  490. not_null<HistoryItem*> original)
  491. : HistoryItem(history, ForwardedFields(fields, history, original)) {
  492. const auto peer = history->peer;
  493. auto config = CreateConfig();
  494. const auto originalMedia = original->media();
  495. const auto dropForwardInfo = fields.ignoreForwardFrom
  496. || original->computeDropForwardedInfo();
  497. const auto topicRootId = fields.replyTo.topicRootId;
  498. config.reply.messageId = config.reply.topMessageId = topicRootId;
  499. config.reply.topicPost = (topicRootId != 0) ? 1 : 0;
  500. if (const auto originalReply = original->Get<HistoryMessageReply>()) {
  501. if (originalReply->external()) {
  502. config.reply = originalReply->fields().clone(this);
  503. if (!config.reply.externalPeerId) {
  504. config.reply.messageId = 0;
  505. }
  506. }
  507. }
  508. if (!dropForwardInfo) {
  509. config.originalDate = original->originalDate();
  510. if (const auto info = original->originalHiddenSenderInfo()) {
  511. config.originalSenderName = info->name;
  512. } else if (const auto originalSender = original->originalSender()) {
  513. config.originalSenderId = originalSender->id;
  514. if (originalSender->isChannel()) {
  515. config.originalId = original->originalId();
  516. }
  517. } else {
  518. Unexpected("Corrupt forwarded information in message.");
  519. }
  520. config.originalPostAuthor = original->originalPostAuthor();
  521. }
  522. if (peer->isSelf()) {
  523. //
  524. // iOS app sends you to the original post if we forward a forward from channel.
  525. // But server returns not the original post but the forward in saved_from_...
  526. //
  527. //if (config.originalId) {
  528. // config.savedFromPeer = config.senderOriginal;
  529. // config.savedFromMsgId = config.originalId;
  530. //} else {
  531. config.savedFromPeer = original->history()->peer->id;
  532. config.savedFromMsgId = original->id;
  533. //}
  534. config.savedFromOutgoing = original->out();
  535. config.savedFromSenderId = original->Get<HistoryMessageForwarded>()
  536. ? original->author()->id
  537. : PeerId();
  538. }
  539. if (_flags & MessageFlag::HasPostAuthor) {
  540. config.postAuthor = fields.postAuthor;
  541. }
  542. if (const auto fwdViaBot = original->viaBot()) {
  543. config.viaBotId = peerToUser(fwdViaBot->id);
  544. } else if (originalMedia && originalMedia->game()) {
  545. if (const auto sender = original->originalSender()) {
  546. if (const auto user = sender->asUser()) {
  547. if (user->isBot()) {
  548. config.viaBotId = peerToUser(user->id);
  549. }
  550. }
  551. }
  552. }
  553. const auto fwdViewsCount = original->viewsCount();
  554. if (fwdViewsCount > 0) {
  555. config.viewsCount = fwdViewsCount;
  556. } else if ((isPost() && !isScheduled())
  557. || (original->originalSender()
  558. && original->originalSender()->isChannel())) {
  559. config.viewsCount = 1;
  560. }
  561. const auto mediaOriginal = original->media();
  562. if (CopyMarkupToForward(original)) {
  563. config.inlineMarkup = original->inlineReplyMarkup();
  564. }
  565. createComponents(std::move(config));
  566. const auto ignoreMedia = [&] {
  567. if (mediaOriginal && mediaOriginal->webpage()) {
  568. if (peer->amRestricted(ChatRestriction::EmbedLinks)) {
  569. return true;
  570. }
  571. }
  572. return false;
  573. };
  574. if (mediaOriginal && !ignoreMedia()) {
  575. _media = mediaOriginal->clone(this);
  576. if (original->invertMedia()) {
  577. _flags |= MessageFlag::InvertMedia;
  578. }
  579. }
  580. const auto dropText = fields.ignoreForwardCaptions
  581. && _media
  582. && (_media->photo() || _media->document())
  583. && !_media->webpage();
  584. setText(dropText
  585. ? TextWithEntities()
  586. : dropForwardInfo
  587. ? DropDisallowedCustomEmoji(history->peer, original->originalText())
  588. : original->originalText());
  589. if (fields.groupedId) {
  590. setGroupId(MessageGroupId::FromRaw(
  591. history->peer->id,
  592. fields.groupedId,
  593. _flags & MessageFlag::IsOrWasScheduled));
  594. }
  595. }
  596. HistoryItem::HistoryItem(
  597. not_null<History*> history,
  598. HistoryItemCommonFields &&fields,
  599. const TextWithEntities &textWithEntities,
  600. const MTPMessageMedia &media)
  601. : HistoryItem(history, fields) {
  602. createComponentsHelper(std::move(fields));
  603. setMedia(media);
  604. setText(textWithEntities);
  605. if (fields.groupedId) {
  606. setGroupId(MessageGroupId::FromRaw(
  607. history->peer->id,
  608. fields.groupedId,
  609. _flags & MessageFlag::IsOrWasScheduled));
  610. }
  611. }
  612. HistoryItem::HistoryItem(
  613. not_null<History*> history,
  614. HistoryItemCommonFields &&fields,
  615. not_null<DocumentData*> document,
  616. const TextWithEntities &caption)
  617. : HistoryItem(history, fields) {
  618. createComponentsHelper(std::move(fields));
  619. const auto video = document->video();
  620. using Args = Data::MediaFile::Args;
  621. _media = std::make_unique<Data::MediaFile>(this, document, Args{
  622. .hasQualitiesList = video && !video->qualities.empty(),
  623. .skipPremiumEffect = !history->session().premium(),
  624. });
  625. setText(caption);
  626. }
  627. HistoryItem::HistoryItem(
  628. not_null<History*> history,
  629. HistoryItemCommonFields &&fields,
  630. not_null<PhotoData*> photo,
  631. const TextWithEntities &caption)
  632. : HistoryItem(history, fields) {
  633. createComponentsHelper(std::move(fields));
  634. const auto spoiler = false;
  635. _media = std::make_unique<Data::MediaPhoto>(this, photo, spoiler);
  636. setText(caption);
  637. }
  638. HistoryItem::HistoryItem(
  639. not_null<History*> history,
  640. HistoryItemCommonFields &&fields,
  641. not_null<GameData*> game)
  642. : HistoryItem(history, fields) {
  643. createComponentsHelper(std::move(fields));
  644. _media = std::make_unique<Data::MediaGame>(this, game);
  645. setTextValue({});
  646. }
  647. HistoryItem::HistoryItem(
  648. not_null<History*> history,
  649. MsgId id,
  650. Data::SponsoredFrom from,
  651. const TextWithEntities &textWithEntities,
  652. HistoryItem *injectedAfter)
  653. : HistoryItem(history, {
  654. .id = id,
  655. .flags = (MessageFlag::Local
  656. | MessageFlag::Sponsored
  657. | (history->peer->isChannel() ? MessageFlag::Post : MessageFlag(0))),
  658. .date = NewMessageDate(injectedAfter ? injectedAfter->date() : 0),
  659. }) {
  660. const auto webpage = history->peer->owner().webpage(
  661. history->peer->owner().nextLocalMessageId().bare,
  662. WebPageType::None,
  663. from.link,
  664. from.link,
  665. from.isRecommended
  666. ? tr::lng_recommended_message_title(tr::now)
  667. : tr::lng_sponsored_message_title(tr::now),
  668. from.title,
  669. textWithEntities,
  670. (from.photoId
  671. ? history->owner().photo(from.photoId).get()
  672. : nullptr),
  673. nullptr,
  674. WebPageCollage(),
  675. nullptr,
  676. nullptr,
  677. nullptr,
  678. 0,
  679. QString(),
  680. false,
  681. false,
  682. 0);
  683. auto webpageMedia = std::make_unique<Data::MediaWebPage>(
  684. this,
  685. webpage,
  686. MediaWebPageFlag::Sponsored);
  687. _media = std::move(webpageMedia);
  688. }
  689. HistoryItem::HistoryItem(
  690. not_null<History*> history,
  691. const HistoryItemCommonFields &fields)
  692. : id(fields.id)
  693. , _history(history)
  694. , _from((fields.flags & MessageFlag::HasFromId && fields.from)
  695. ? history->owner().peer(fields.from)
  696. : history->peer)
  697. , _flags(FinalizeMessageFlags(history, fields.flags))
  698. , _date(fields.date)
  699. , _starsPaid(fields.starsPaid)
  700. , _shortcutId(fields.shortcutId)
  701. , _effectId(fields.effectId) {
  702. Expects(!_shortcutId
  703. || isSending()
  704. || _history->owner().shortcutMessages().lookupId(this));
  705. if (isHistoryEntry() && IsClientMsgId(id)) {
  706. _history->registerClientSideMessage(this);
  707. }
  708. if (_effectId) {
  709. _history->owner().reactions().preloadEffectImageFor(_effectId);
  710. }
  711. }
  712. HistoryItem::HistoryItem(
  713. not_null<History*> history,
  714. MsgId id,
  715. not_null<Data::Story*> story)
  716. : HistoryItem(history, {
  717. .id = id,
  718. .flags = (MessageFlag::Local
  719. | MessageFlag::Outgoing
  720. | MessageFlag::HasFromId
  721. | MessageFlag::FakeHistoryItem
  722. | MessageFlag::StoryItem),
  723. .from = history->peer->id,
  724. .date = story->date(),
  725. }) {
  726. setStoryFields(story);
  727. }
  728. HistoryItem::~HistoryItem() {
  729. _media = nullptr;
  730. clearSavedMedia();
  731. if (const auto reply = Get<HistoryMessageReply>()) {
  732. reply->clearData(this);
  733. }
  734. if (const auto saved = Get<HistoryMessageSaved>()) {
  735. saved->sublist->removeOne(this);
  736. }
  737. clearDependencyMessage();
  738. applyTTL(0);
  739. }
  740. TimeId HistoryItem::date() const {
  741. return _date;
  742. }
  743. int HistoryItem::starsPaid() const {
  744. return _starsPaid;
  745. }
  746. bool HistoryItem::awaitingVideoProcessing() const {
  747. return (_flags & MessageFlag::EstimatedDate);
  748. }
  749. HistoryServiceDependentData *HistoryItem::GetServiceDependentData() {
  750. if (const auto pinned = Get<HistoryServicePinned>()) {
  751. return pinned;
  752. } else if (const auto gamescore = Get<HistoryServiceGameScore>()) {
  753. return gamescore;
  754. } else if (const auto payment = Get<HistoryServicePayment>()) {
  755. return payment;
  756. } else if (const auto info = Get<HistoryServiceTopicInfo>()) {
  757. return info;
  758. } else if (const auto same = Get<HistoryServiceSameBackground>()) {
  759. return same;
  760. } else if (const auto results = Get<HistoryServiceGiveawayResults>()) {
  761. return results;
  762. }
  763. return nullptr;
  764. }
  765. auto HistoryItem::GetServiceDependentData() const
  766. -> const HistoryServiceDependentData * {
  767. return const_cast<HistoryItem*>(this)->GetServiceDependentData();
  768. }
  769. void HistoryItem::dependencyItemRemoved(not_null<HistoryItem*> dependency) {
  770. if (const auto reply = Get<HistoryMessageReply>()) {
  771. const auto documentId = reply->replyToDocumentId;
  772. reply->itemRemoved(this, dependency);
  773. if (documentId != reply->replyToDocumentId
  774. && generateLocalEntitiesByReply()) {
  775. _history->owner().requestItemTextRefresh(this);
  776. }
  777. } else {
  778. clearDependencyMessage();
  779. updateDependentServiceText();
  780. }
  781. }
  782. void HistoryItem::dependencyStoryRemoved(
  783. not_null<Data::Story*> dependency) {
  784. if (const auto reply = Get<HistoryMessageReply>()) {
  785. const auto documentId = reply->replyToDocumentId;
  786. reply->storyRemoved(this, dependency);
  787. if (documentId != reply->replyToDocumentId
  788. && generateLocalEntitiesByReply()) {
  789. _history->owner().requestItemTextRefresh(this);
  790. }
  791. }
  792. }
  793. void HistoryItem::updateDependencyItem() {
  794. if (const auto reply = Get<HistoryMessageReply>()) {
  795. const auto documentId = reply->replyToDocumentId;
  796. const auto webpageId = reply->replyToWebPageId;
  797. reply->updateData(this, true);
  798. const auto mediaIdChanged = (documentId != reply->replyToDocumentId)
  799. || (webpageId != reply->replyToWebPageId);
  800. if (mediaIdChanged && generateLocalEntitiesByReply()) {
  801. _history->owner().requestItemTextRefresh(this);
  802. }
  803. } else if (GetServiceDependentData()) {
  804. updateServiceDependent(true);
  805. }
  806. }
  807. void HistoryItem::updateDependentServiceText() {
  808. if (Has<HistoryServicePinned>()) {
  809. updateServiceText(preparePinnedText());
  810. } else if (Has<HistoryServiceGameScore>()) {
  811. updateServiceText(prepareGameScoreText());
  812. } else if (Has<HistoryServicePayment>()) {
  813. updateServiceText(preparePaymentSentText());
  814. }
  815. }
  816. void HistoryItem::updateServiceDependent(bool force) {
  817. auto dependent = GetServiceDependentData();
  818. Assert(dependent != nullptr);
  819. if (!force) {
  820. if (!dependent->msgId || dependent->msg) {
  821. dependent->pendingResolve = false;
  822. return;
  823. }
  824. }
  825. if (!dependent->lnk) {
  826. dependent->lnk = JumpToMessageClickHandler(
  827. (dependent->peerId
  828. ? _history->owner().peer(dependent->peerId)
  829. : _history->peer),
  830. dependent->msgId,
  831. fullId());
  832. }
  833. auto gotDependencyItem = false;
  834. if (!dependent->msg) {
  835. dependent->msg = _history->owner().message(
  836. (dependent->peerId
  837. ? dependent->peerId
  838. : _history->peer->id),
  839. dependent->msgId);
  840. if (dependent->msg) {
  841. if (dependent->msg->isEmpty()) {
  842. // Really it is deleted.
  843. dependent->msg = nullptr;
  844. force = true;
  845. } else {
  846. _history->owner().registerDependentMessage(
  847. this,
  848. dependent->msg);
  849. gotDependencyItem = true;
  850. }
  851. }
  852. }
  853. // Record resolve state for upcoming on-demand resolving.
  854. if (dependent->msg || !dependent->msgId || force) {
  855. dependent->pendingResolve = false;
  856. } else {
  857. dependent->pendingResolve = true;
  858. dependent->requestedResolve = false;
  859. }
  860. // updateDependentServiceText may call UpdateComponents!
  861. // So the `dependent` pointer becomes invalid.
  862. if (dependent->msg) {
  863. updateDependentServiceText();
  864. } else if (force) {
  865. if (dependent->msgId > 0) {
  866. dependent->msgId = 0;
  867. gotDependencyItem = true;
  868. }
  869. updateDependentServiceText();
  870. }
  871. if (force && gotDependencyItem) {
  872. Core::App().notifications().checkDelayed();
  873. }
  874. }
  875. MsgId HistoryItem::dependencyMsgId() const {
  876. if (auto dependent = GetServiceDependentData()) {
  877. return dependent->msgId;
  878. }
  879. return replyToId();
  880. }
  881. void HistoryItem::checkBuyButton() {
  882. if (const auto invoice = _media ? _media->invoice() : nullptr) {
  883. if (invoice->receiptMsgId) {
  884. replaceBuyWithReceiptInMarkup();
  885. }
  886. }
  887. }
  888. void HistoryItem::resolveDependent(
  889. not_null<HistoryServiceDependentData*> dependent) {
  890. if (!dependent->pendingResolve || dependent->requestedResolve) {
  891. return;
  892. }
  893. dependent->requestedResolve = true;
  894. RequestDependentMessageItem(
  895. this,
  896. (dependent->peerId ? dependent->peerId : _history->peer->id),
  897. dependent->msgId);
  898. }
  899. void HistoryItem::resolveDependent(not_null<HistoryMessageReply*> reply) {
  900. if (!reply->acquireResolve()) {
  901. return;
  902. } else if (const auto messageId = reply->messageId()) {
  903. if (Data::IsScheduledMsgId(messageId)) {
  904. reply->updateData(this);
  905. if (!reply->acquireResolve()) {
  906. return;
  907. }
  908. }
  909. RequestDependentMessageItem(
  910. this,
  911. reply->externalPeerId(),
  912. messageId);
  913. } else if (reply->storyId()) {
  914. RequestDependentMessageStory(
  915. this,
  916. reply->externalPeerId(),
  917. reply->storyId());
  918. }
  919. }
  920. void HistoryItem::resolveDependent() {
  921. if (const auto dependent = GetServiceDependentData()) {
  922. resolveDependent(dependent);
  923. } else if (const auto reply = Get<HistoryMessageReply>()) {
  924. resolveDependent(reply);
  925. }
  926. }
  927. bool HistoryItem::notificationReady() const {
  928. if (const auto dependent = GetServiceDependentData()) {
  929. if (dependent->msg || !dependent->msgId) {
  930. return true;
  931. }
  932. const_cast<HistoryItem*>(this)->resolveDependent(
  933. const_cast<HistoryServiceDependentData*>(dependent));
  934. }
  935. return true;
  936. }
  937. void HistoryItem::finishEdition(int oldKeyboardTop) {
  938. if (const auto group = _history->owner().groups().find(this)) {
  939. for (const auto &item : group->items) {
  940. _history->owner().requestItemViewRefresh(item);
  941. item->invalidateChatListEntry();
  942. }
  943. } else {
  944. _history->owner().requestItemViewRefresh(this);
  945. invalidateChatListEntry();
  946. }
  947. // Should be completely redesigned as the oldTop no longer exists.
  948. //if (oldKeyboardTop >= 0) { // #TODO edit bot message
  949. // if (auto keyboard = Get<HistoryMessageReplyMarkup>()) {
  950. // keyboard->oldTop = oldKeyboardTop;
  951. // }
  952. //}
  953. _history->owner().updateDependentMessages(this);
  954. }
  955. void HistoryItem::setGroupId(MessageGroupId groupId) {
  956. Expects(!_groupId);
  957. _groupId = groupId;
  958. _history->owner().groups().registerMessage(this);
  959. }
  960. bool HistoryItem::checkCommentsLinkedChat(ChannelId id) const {
  961. if (!id) {
  962. return true;
  963. } else if (const auto channel = _history->peer->asChannel()) {
  964. if (channel->linkedChatKnown()
  965. || !(channel->flags() & ChannelDataFlag::HasLink)) {
  966. const auto linked = channel->linkedChat();
  967. if (!linked || peerToChannel(linked->id) != id) {
  968. return false;
  969. }
  970. }
  971. return true;
  972. }
  973. return false;
  974. }
  975. void HistoryItem::setReplyMarkup(HistoryMessageMarkupData &&markup) {
  976. const auto requestUpdate = [&] {
  977. history()->owner().requestItemResize(this);
  978. history()->session().changes().messageUpdated(
  979. this,
  980. Data::MessageUpdate::Flag::ReplyMarkup);
  981. };
  982. if (markup.isNull()) {
  983. if (_flags & MessageFlag::HasReplyMarkup) {
  984. _flags &= ~MessageFlag::HasReplyMarkup;
  985. if (Has<HistoryMessageReplyMarkup>()) {
  986. RemoveComponents(HistoryMessageReplyMarkup::Bit());
  987. }
  988. requestUpdate();
  989. }
  990. return;
  991. }
  992. // optimization: don't create markup component for the case
  993. // MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag
  994. if (markup.isTrivial()) {
  995. bool changed = false;
  996. if (Has<HistoryMessageReplyMarkup>()) {
  997. RemoveComponents(HistoryMessageReplyMarkup::Bit());
  998. changed = true;
  999. }
  1000. if (!(_flags & MessageFlag::HasReplyMarkup)) {
  1001. _flags |= MessageFlag::HasReplyMarkup;
  1002. changed = true;
  1003. }
  1004. if (changed) {
  1005. requestUpdate();
  1006. }
  1007. } else {
  1008. if (!(_flags & MessageFlag::HasReplyMarkup)) {
  1009. _flags |= MessageFlag::HasReplyMarkup;
  1010. }
  1011. if (!Has<HistoryMessageReplyMarkup>()) {
  1012. AddComponents(HistoryMessageReplyMarkup::Bit());
  1013. }
  1014. Get<HistoryMessageReplyMarkup>()->updateData(std::move(markup));
  1015. requestUpdate();
  1016. }
  1017. }
  1018. void HistoryItem::setCommentsInboxReadTill(MsgId readTillId) {
  1019. const auto views = Get<HistoryMessageViews>();
  1020. if (!views) {
  1021. return;
  1022. }
  1023. const auto newReadTillId = std::max(readTillId.bare, int64(1));
  1024. const auto ignore = (newReadTillId < views->commentsInboxReadTillId);
  1025. if (ignore) {
  1026. return;
  1027. }
  1028. const auto changed = (newReadTillId > views->commentsInboxReadTillId);
  1029. if (!changed) {
  1030. return;
  1031. }
  1032. const auto wasUnread = areCommentsUnread();
  1033. views->commentsInboxReadTillId = newReadTillId;
  1034. if (wasUnread && !areCommentsUnread()) {
  1035. _history->owner().requestItemRepaint(this);
  1036. }
  1037. }
  1038. void HistoryItem::setCommentsMaxId(MsgId maxId) {
  1039. if (const auto views = Get<HistoryMessageViews>()) {
  1040. if (views->commentsMaxId != maxId) {
  1041. const auto wasUnread = areCommentsUnread();
  1042. views->commentsMaxId = maxId;
  1043. if (wasUnread != areCommentsUnread()) {
  1044. _history->owner().requestItemRepaint(this);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. void HistoryItem::setCommentsPossibleMaxId(MsgId possibleMaxId) {
  1050. if (const auto views = Get<HistoryMessageViews>()) {
  1051. if (views->commentsMaxId < possibleMaxId) {
  1052. const auto wasUnread = areCommentsUnread();
  1053. views->commentsMaxId = possibleMaxId;
  1054. if (!wasUnread && areCommentsUnread()) {
  1055. _history->owner().requestItemRepaint(this);
  1056. }
  1057. }
  1058. }
  1059. }
  1060. bool HistoryItem::areCommentsUnread() const {
  1061. const auto views = Get<HistoryMessageViews>();
  1062. if (!views
  1063. || !views->commentsMegagroupId
  1064. || !checkCommentsLinkedChat(views->commentsMegagroupId)) {
  1065. return false;
  1066. }
  1067. const auto till = views->commentsInboxReadTillId;
  1068. if (views->commentsInboxReadTillId < 2 || views->commentsMaxId <= till) {
  1069. return false;
  1070. }
  1071. const auto group = views->commentsMegagroupId
  1072. ? _history->owner().historyLoaded(
  1073. peerFromChannel(views->commentsMegagroupId))
  1074. : _history.get();
  1075. return !group || (views->commentsMaxId > group->inboxReadTillId());
  1076. }
  1077. FullMsgId HistoryItem::commentsItemId() const {
  1078. if (const auto views = Get<HistoryMessageViews>()) {
  1079. return FullMsgId(
  1080. PeerId(views->commentsMegagroupId),
  1081. views->commentsRootId);
  1082. }
  1083. return FullMsgId();
  1084. }
  1085. void HistoryItem::setCommentsItemId(FullMsgId id) {
  1086. if (id.peer == _history->peer->id) {
  1087. if (id.msg != this->id) {
  1088. if (const auto reply = Get<HistoryMessageReply>()) {
  1089. reply->setTopMessageId(id.msg);
  1090. }
  1091. }
  1092. } else if (const auto views = Get<HistoryMessageViews>()) {
  1093. if (const auto channelId = peerToChannel(id.peer)) {
  1094. if (views->commentsMegagroupId != channelId) {
  1095. views->commentsMegagroupId = channelId;
  1096. _history->owner().requestItemResize(this);
  1097. }
  1098. views->commentsRootId = id.msg;
  1099. }
  1100. }
  1101. }
  1102. void HistoryItem::setServiceText(PreparedServiceText &&prepared) {
  1103. AddComponents(HistoryServiceData::Bit());
  1104. _flags &= ~MessageFlag::HasTextLinks;
  1105. const auto data = Get<HistoryServiceData>();
  1106. const auto had = !_text.empty();
  1107. _text = std::move(prepared.text);
  1108. data->textLinks = std::move(prepared.links);
  1109. if (had) {
  1110. _history->owner().requestItemTextRefresh(this);
  1111. }
  1112. }
  1113. void HistoryItem::updateServiceText(PreparedServiceText &&text) {
  1114. setServiceText(std::move(text));
  1115. _history->owner().requestItemResize(this);
  1116. invalidateChatListEntry();
  1117. _history->owner().updateDependentMessages(this);
  1118. }
  1119. void HistoryItem::updateStoryMentionText() {
  1120. setServiceText(prepareStoryMentionText());
  1121. }
  1122. HistoryMessageReplyMarkup *HistoryItem::inlineReplyMarkup() {
  1123. if (const auto markup = Get<HistoryMessageReplyMarkup>()) {
  1124. if (markup->data.flags & ReplyMarkupFlag::Inline) {
  1125. return markup;
  1126. }
  1127. }
  1128. return nullptr;
  1129. }
  1130. ReplyKeyboard *HistoryItem::inlineReplyKeyboard() {
  1131. if (const auto markup = inlineReplyMarkup()) {
  1132. return markup->inlineKeyboard.get();
  1133. }
  1134. return nullptr;
  1135. }
  1136. ChannelData *HistoryItem::discussionPostOriginalSender() const {
  1137. if (!_history->peer->isMegagroup()) {
  1138. return nullptr;
  1139. }
  1140. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  1141. const auto from = forwarded->savedFromPeer;
  1142. if (const auto result = from ? from->asChannel() : nullptr) {
  1143. return result;
  1144. }
  1145. }
  1146. return nullptr;
  1147. }
  1148. bool HistoryItem::isDiscussionPost() const {
  1149. return (discussionPostOriginalSender() != nullptr);
  1150. }
  1151. HistoryItem *HistoryItem::lookupDiscussionPostOriginal() const {
  1152. if (!_history->peer->isMegagroup()) {
  1153. return nullptr;
  1154. }
  1155. const auto forwarded = Get<HistoryMessageForwarded>();
  1156. if (!forwarded
  1157. || !forwarded->savedFromPeer
  1158. || !forwarded->savedFromMsgId) {
  1159. return nullptr;
  1160. }
  1161. return _history->owner().message(
  1162. forwarded->savedFromPeer->id,
  1163. forwarded->savedFromMsgId);
  1164. }
  1165. PeerData *HistoryItem::computeDisplayFrom() const {
  1166. if (const auto sender = discussionPostOriginalSender()) {
  1167. return sender;
  1168. } else if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  1169. if (showForwardsFromSender(forwarded)) {
  1170. return forwarded->forwardOfForward()
  1171. ? forwarded->savedFromSender
  1172. : forwarded->originalSender;
  1173. }
  1174. }
  1175. return author().get();
  1176. }
  1177. PeerData *HistoryItem::displayFrom() const {
  1178. if (_flags & MessageFlag::DisplayFromChecked) {
  1179. const auto showing = isPostShowingAuthor();
  1180. const auto flag = (_flags & MessageFlag::DisplayFromProfiles);
  1181. if (showing && !flag) {
  1182. _flags |= MessageFlag::DisplayFromProfiles;
  1183. } else if (!showing && flag) {
  1184. _flags &= ~MessageFlag::DisplayFromProfiles;
  1185. } else {
  1186. return _displayFrom;
  1187. }
  1188. }
  1189. _flags |= MessageFlag::DisplayFromChecked;
  1190. _displayFrom = computeDisplayFrom();
  1191. return _displayFrom;
  1192. }
  1193. uint8 HistoryItem::colorIndex() const {
  1194. if (const auto from = displayFrom()) {
  1195. return from->colorIndex();
  1196. } else if (const auto info = displayHiddenSenderInfo()) {
  1197. return info->colorIndex;
  1198. }
  1199. Unexpected("No displayFrom and no displayHiddenSenderInfo.");
  1200. }
  1201. PeerData *HistoryItem::contentColorsFrom() const {
  1202. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  1203. return forwarded->originalSender;
  1204. }
  1205. return displayFrom();
  1206. }
  1207. uint8 HistoryItem::contentColorIndex() const {
  1208. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  1209. return forwarded->originalSender
  1210. ? forwarded->originalSender->colorIndex()
  1211. : forwarded->originalHiddenSenderInfo->colorIndex;
  1212. }
  1213. return colorIndex();
  1214. }
  1215. std::unique_ptr<HistoryView::Element> HistoryItem::createView(
  1216. not_null<HistoryView::ElementDelegate*> delegate,
  1217. HistoryView::Element *replacing) {
  1218. if (isService()) {
  1219. return std::make_unique<HistoryView::Service>(
  1220. delegate,
  1221. this,
  1222. replacing);
  1223. }
  1224. return std::make_unique<HistoryView::Message>(delegate, this, replacing);
  1225. }
  1226. void HistoryItem::invalidateChatListEntry() {
  1227. _history->session().changes().messageUpdated(
  1228. this,
  1229. Data::MessageUpdate::Flag::DialogRowRefresh);
  1230. _history->lastItemDialogsView().itemInvalidated(this);
  1231. if (const auto topic = this->topic()) {
  1232. topic->lastItemDialogsView().itemInvalidated(this);
  1233. }
  1234. if (const auto sublist = savedSublist()) {
  1235. sublist->lastItemDialogsView().itemInvalidated(this);
  1236. }
  1237. }
  1238. void HistoryItem::customEmojiRepaint() {
  1239. if (!(_flags & MessageFlag::CustomEmojiRepainting)) {
  1240. _flags |= MessageFlag::CustomEmojiRepainting;
  1241. _history->owner().requestItemRepaint(this);
  1242. }
  1243. }
  1244. bool HistoryItem::needsUpdateForVideoQualities(const MTPMessage &data) {
  1245. // When video gets the converted alt-videos lists, we need to update
  1246. // the message data even without edit-message update.
  1247. return data.match([&](const MTPDmessage &data) {
  1248. const auto media = data.vmedia();
  1249. if (!media) {
  1250. return false;
  1251. }
  1252. return media->match([&](const MTPDmessageMediaDocument &data) {
  1253. const auto document = data.vdocument();
  1254. const auto alts = data.valt_documents();
  1255. if (!document || !alts || alts->v.isEmpty()) {
  1256. return false;
  1257. }
  1258. const auto id = document->match([](const auto &data) {
  1259. return DocumentId(data.vid().v);
  1260. });
  1261. const auto existingMedia = this->media();
  1262. const auto existingDocument = existingMedia
  1263. ? existingMedia->document()
  1264. : nullptr;
  1265. return !existingDocument
  1266. || (existingDocument->id != id)
  1267. || existingDocument->resolveQualities(this).empty();
  1268. }, [](const auto &) {
  1269. return false;
  1270. });
  1271. }, [](const auto &) {
  1272. return false;
  1273. });
  1274. }
  1275. void HistoryItem::finishEditionToEmpty() {
  1276. finishEdition(-1);
  1277. _history->itemVanished(this);
  1278. }
  1279. bool HistoryItem::hasUnreadMediaFlag() const {
  1280. if (_history->peer->isChannel()) {
  1281. const auto passed = base::unixtime::now() - date();
  1282. const auto &config = _history->session().serverConfig();
  1283. if (passed >= config.channelsReadMediaPeriod) {
  1284. return false;
  1285. }
  1286. }
  1287. return _flags & MessageFlag::MediaIsUnread;
  1288. }
  1289. bool HistoryItem::isUnreadMention() const {
  1290. return !out() && mentionsMe() && (_flags & MessageFlag::MediaIsUnread);
  1291. }
  1292. bool HistoryItem::hasUnreadReaction() const {
  1293. return (_flags & MessageFlag::HasUnreadReaction);
  1294. }
  1295. bool HistoryItem::hasUnwatchedEffect() const {
  1296. return effectId() && !(_flags & MessageFlag::EffectWatched);
  1297. }
  1298. bool HistoryItem::markEffectWatched() {
  1299. if (!hasUnwatchedEffect()) {
  1300. return false;
  1301. }
  1302. _flags |= MessageFlag::EffectWatched;
  1303. return true;
  1304. }
  1305. bool HistoryItem::mentionsMe() const {
  1306. if (Has<HistoryServicePinned>()
  1307. && !Core::App().settings().notifyAboutPinned()) {
  1308. return false;
  1309. }
  1310. return _flags & MessageFlag::MentionsMe;
  1311. }
  1312. bool HistoryItem::isUnreadMedia() const {
  1313. if (!hasUnreadMediaFlag()) {
  1314. return false;
  1315. } else if (const auto media = this->media()) {
  1316. if (const auto document = media->document()) {
  1317. if (document->isVoiceMessage() || document->isVideoMessage()) {
  1318. return (media->webpage() == nullptr);
  1319. }
  1320. }
  1321. }
  1322. return false;
  1323. }
  1324. bool HistoryItem::isIncomingUnreadMedia() const {
  1325. return !out() && isUnreadMedia();
  1326. }
  1327. void HistoryItem::markMediaAndMentionRead() {
  1328. _flags &= ~MessageFlag::MediaIsUnread;
  1329. if (mentionsMe()) {
  1330. _history->updateChatListEntry();
  1331. _history->unreadMentions().erase(id);
  1332. if (const auto topic = this->topic()) {
  1333. topic->updateChatListEntry();
  1334. topic->unreadMentions().erase(id);
  1335. }
  1336. }
  1337. if (const auto selfdestruct = Get<HistoryServiceSelfDestruct>()) {
  1338. if (selfdestruct->destructAt == crl::time()) {
  1339. const auto ttl = selfdestruct->timeToLive;
  1340. if (const auto maybeTime = std::get_if<crl::time>(&ttl)) {
  1341. const auto time = *maybeTime;
  1342. selfdestruct->destructAt = crl::now() + time;
  1343. _history->owner().selfDestructIn(this, time);
  1344. } else {
  1345. selfdestruct->destructAt = TimeToLiveSingleView();
  1346. }
  1347. }
  1348. }
  1349. }
  1350. void HistoryItem::markReactionsRead() {
  1351. if (_reactions) {
  1352. _reactions->markRead();
  1353. }
  1354. _flags &= ~MessageFlag::HasUnreadReaction;
  1355. _history->updateChatListEntry();
  1356. _history->unreadReactions().erase(id);
  1357. if (const auto topic = this->topic()) {
  1358. topic->updateChatListEntry();
  1359. topic->unreadReactions().erase(id);
  1360. }
  1361. }
  1362. bool HistoryItem::markContentsRead(bool fromThisClient) {
  1363. if (hasUnreadReaction()) {
  1364. if (fromThisClient) {
  1365. _history->owner().requestUnreadReactionsAnimation(this);
  1366. }
  1367. markReactionsRead();
  1368. return true;
  1369. } else if (isUnreadMention() || isIncomingUnreadMedia()) {
  1370. markMediaAndMentionRead();
  1371. return true;
  1372. }
  1373. return false;
  1374. }
  1375. void HistoryItem::setIsPinned(bool pinned) {
  1376. const auto changed = (isPinned() != pinned);
  1377. const auto guard = gsl::finally([&] {
  1378. if (changed) {
  1379. _history->owner().notifyItemDataChange(this);
  1380. }
  1381. });
  1382. if (pinned) {
  1383. _flags |= MessageFlag::Pinned;
  1384. if (_flags & MessageFlag::StoryItem) {
  1385. return;
  1386. }
  1387. auto &storage = _history->session().storage();
  1388. storage.add(Storage::SharedMediaAddExisting(
  1389. _history->peer->id,
  1390. MsgId(0), // topicRootId
  1391. Storage::SharedMediaType::Pinned,
  1392. id,
  1393. { id, id }));
  1394. _history->setHasPinnedMessages(true);
  1395. if (const auto topic = this->topic()) {
  1396. storage.add(Storage::SharedMediaAddExisting(
  1397. _history->peer->id,
  1398. topic->rootId(),
  1399. Storage::SharedMediaType::Pinned,
  1400. id,
  1401. { id, id }));
  1402. topic->setHasPinnedMessages(true);
  1403. }
  1404. } else {
  1405. _flags &= ~MessageFlag::Pinned;
  1406. if (_flags & MessageFlag::StoryItem) {
  1407. return;
  1408. }
  1409. _history->session().storage().remove(Storage::SharedMediaRemoveOne(
  1410. _history->peer->id,
  1411. Storage::SharedMediaType::Pinned,
  1412. id));
  1413. }
  1414. }
  1415. void HistoryItem::returnSavedMedia() {
  1416. if (!isEditingMedia()) {
  1417. return;
  1418. }
  1419. const auto wasGrouped = history()->owner().groups().isGrouped(this);
  1420. const auto data = Get<HistoryMessageSavedMediaData>();
  1421. _media = std::move(data->media);
  1422. setText(data->text);
  1423. clearSavedMedia();
  1424. if (wasGrouped) {
  1425. history()->owner().groups().refreshMessage(this, true);
  1426. } else {
  1427. history()->owner().requestItemViewRefresh(this);
  1428. history()->owner().updateDependentMessages(this);
  1429. }
  1430. }
  1431. void HistoryItem::savePreviousMedia() {
  1432. AddComponents(HistoryMessageSavedMediaData::Bit());
  1433. const auto data = Get<HistoryMessageSavedMediaData>();
  1434. data->text = originalText();
  1435. data->media = _media ? _media->clone(this) : nullptr;
  1436. }
  1437. bool HistoryItem::isEditingMedia() const {
  1438. return Has<HistoryMessageSavedMediaData>();
  1439. }
  1440. void HistoryItem::clearSavedMedia() {
  1441. RemoveComponents(HistoryMessageSavedMediaData::Bit());
  1442. }
  1443. bool HistoryItem::definesReplyKeyboard() const {
  1444. if (const auto markup = Get<HistoryMessageReplyMarkup>()) {
  1445. if (markup->data.flags & ReplyMarkupFlag::Inline) {
  1446. return false;
  1447. }
  1448. return true;
  1449. }
  1450. // optimization: don't create markup component for the case
  1451. // MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag
  1452. return (_flags & MessageFlag::HasReplyMarkup);
  1453. }
  1454. ReplyMarkupFlags HistoryItem::replyKeyboardFlags() const {
  1455. Expects(definesReplyKeyboard());
  1456. if (const auto markup = Get<HistoryMessageReplyMarkup>()) {
  1457. return markup->data.flags;
  1458. }
  1459. // optimization: don't create markup component for the case
  1460. // MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag
  1461. return ReplyMarkupFlag::None;
  1462. }
  1463. void HistoryItem::addLogEntryOriginal(
  1464. WebPageId localId,
  1465. const QString &label,
  1466. const TextWithEntities &content) {
  1467. Expects(isAdminLogEntry());
  1468. AddComponents(HistoryMessageLogEntryOriginal::Bit());
  1469. Get<HistoryMessageLogEntryOriginal>()->page = _history->owner().webpage(
  1470. localId,
  1471. label,
  1472. content);
  1473. }
  1474. void HistoryItem::setFactcheck(MessageFactcheck info) {
  1475. if (!info) {
  1476. if (Has<HistoryMessageFactcheck>()) {
  1477. RemoveComponents(HistoryMessageFactcheck::Bit());
  1478. history()->owner().requestItemResize(this);
  1479. }
  1480. } else {
  1481. AddComponents(HistoryMessageFactcheck::Bit());
  1482. const auto factcheck = Get<HistoryMessageFactcheck>();
  1483. const auto textChanged = (factcheck->data.text != info.text);
  1484. if (factcheck->data.hash == info.hash
  1485. && (info.needCheck || !factcheck->data.needCheck)) {
  1486. return;
  1487. } else if (textChanged
  1488. || factcheck->data.country != info.country
  1489. || factcheck->data.hash != info.hash) {
  1490. factcheck->data = std::move(info);
  1491. factcheck->requested = false;
  1492. if (textChanged) {
  1493. factcheck->page = nullptr;
  1494. }
  1495. history()->owner().requestItemResize(this);
  1496. }
  1497. }
  1498. }
  1499. bool HistoryItem::hasUnrequestedFactcheck() const {
  1500. const auto factcheck = Get<HistoryMessageFactcheck>();
  1501. return factcheck && factcheck->data.needCheck && !factcheck->requested;
  1502. }
  1503. TextWithEntities HistoryItem::factcheckText() const {
  1504. if (const auto factcheck = Get<HistoryMessageFactcheck>()) {
  1505. return factcheck->data.text;
  1506. }
  1507. return {};
  1508. }
  1509. PeerData *HistoryItem::specialNotificationPeer() const {
  1510. return (mentionsMe() && !_history->peer->isUser())
  1511. ? from().get()
  1512. : nullptr;
  1513. }
  1514. UserData *HistoryItem::viaBot() const {
  1515. if (const auto via = Get<HistoryMessageVia>()) {
  1516. return via->bot;
  1517. }
  1518. return nullptr;
  1519. }
  1520. UserData *HistoryItem::getMessageBot() const {
  1521. if (const auto bot = viaBot()) {
  1522. return bot;
  1523. }
  1524. auto bot = from()->asUser();
  1525. if (!bot) {
  1526. bot = _history->peer->asUser();
  1527. }
  1528. return (bot && bot->isBot()) ? bot : nullptr;
  1529. }
  1530. bool HistoryItem::isHistoryEntry() const {
  1531. return (_flags & MessageFlag::HistoryEntry);
  1532. }
  1533. bool HistoryItem::isAdminLogEntry() const {
  1534. return (_flags & MessageFlag::AdminLogEntry);
  1535. }
  1536. bool HistoryItem::isFromScheduled() const {
  1537. return isHistoryEntry()
  1538. && (_flags & MessageFlag::IsOrWasScheduled);
  1539. }
  1540. bool HistoryItem::isScheduled() const {
  1541. return !isHistoryEntry()
  1542. && !isAdminLogEntry()
  1543. && (_flags & MessageFlag::IsOrWasScheduled);
  1544. }
  1545. bool HistoryItem::isSponsored() const {
  1546. return _flags & MessageFlag::Sponsored;
  1547. }
  1548. bool HistoryItem::skipNotification() const {
  1549. if (isSilent() && (_flags & MessageFlag::IsContactSignUp)) {
  1550. return true;
  1551. } else if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  1552. if (forwarded->imported) {
  1553. return true;
  1554. }
  1555. }
  1556. return false;
  1557. }
  1558. bool HistoryItem::isUserpicSuggestion() const {
  1559. return (_flags & MessageFlag::IsUserpicSuggestion);
  1560. }
  1561. BusinessShortcutId HistoryItem::shortcutId() const {
  1562. return _shortcutId;
  1563. }
  1564. bool HistoryItem::isBusinessShortcut() const {
  1565. return _shortcutId != 0;
  1566. }
  1567. void HistoryItem::setRealShortcutId(BusinessShortcutId id) {
  1568. _shortcutId = id;
  1569. }
  1570. void HistoryItem::setCustomServiceLink(ClickHandlerPtr link) {
  1571. AddComponents(HistoryServiceCustomLink::Bit());
  1572. Get<HistoryServiceCustomLink>()->link = std::move(link);
  1573. }
  1574. void HistoryItem::destroy() {
  1575. _history->destroyMessage(this);
  1576. }
  1577. not_null<Data::Thread*> HistoryItem::notificationThread() const {
  1578. if (const auto rootId = topicRootId()) {
  1579. if (const auto forum = _history->asForum()) {
  1580. return forum->enforceTopicFor(rootId);
  1581. }
  1582. }
  1583. return _history;
  1584. }
  1585. Data::ForumTopic *HistoryItem::topic() const {
  1586. if (const auto rootId = topicRootId()) {
  1587. if (const auto forum = _history->asForum()) {
  1588. return forum->topicFor(rootId);
  1589. }
  1590. }
  1591. return nullptr;
  1592. }
  1593. void HistoryItem::refreshMainView() {
  1594. if (const auto view = mainView()) {
  1595. _history->owner().notifyHistoryChangeDelayed(_history);
  1596. view->refreshInBlock();
  1597. }
  1598. }
  1599. void HistoryItem::removeMainView() {
  1600. if (const auto view = mainView()) {
  1601. _history->owner().notifyHistoryChangeDelayed(_history);
  1602. view->removeFromBlock();
  1603. }
  1604. }
  1605. void HistoryItem::clearMainView() {
  1606. _mainView = nullptr;
  1607. }
  1608. void HistoryItem::applyEdition(HistoryMessageEdition &&edition) {
  1609. int keyboardTop = -1;
  1610. //if (!pendingResize()) {// #TODO edit bot message
  1611. // if (auto keyboard = inlineReplyKeyboard()) {
  1612. // int h = st::msgBotKbButton.margin + keyboard->naturalHeight();
  1613. // keyboardTop = _height - h + st::msgBotKbButton.margin - marginBottom();
  1614. // }
  1615. //}
  1616. const auto editingMedia = isEditingMedia();
  1617. const auto updatingSavedLocalEdit = !edition.savePreviousMedia
  1618. && editingMedia;
  1619. if (!editingMedia && edition.savePreviousMedia) {
  1620. savePreviousMedia();
  1621. }
  1622. Assert(!updatingSavedLocalEdit || !isLocalUpdateMedia());
  1623. if (edition.isEditHide) {
  1624. _flags |= MessageFlag::HideEdited;
  1625. } else {
  1626. _flags &= ~MessageFlag::HideEdited;
  1627. }
  1628. if (edition.invertMedia) {
  1629. _flags |= MessageFlag::InvertMedia;
  1630. } else {
  1631. _flags &= ~MessageFlag::InvertMedia;
  1632. }
  1633. if (edition.editDate != -1) {
  1634. //_flags |= MTPDmessage::Flag::f_edit_date;
  1635. if (!Has<HistoryMessageEdited>()) {
  1636. AddComponents(HistoryMessageEdited::Bit());
  1637. }
  1638. auto edited = Get<HistoryMessageEdited>();
  1639. edited->date = edition.editDate;
  1640. }
  1641. if (!edition.useSameMarkup) {
  1642. setReplyMarkup(base::take(edition.replyMarkup));
  1643. }
  1644. if (updatingSavedLocalEdit) {
  1645. Get<HistoryMessageSavedMediaData>()->media = edition.mtpMedia
  1646. ? CreateMedia(this, *edition.mtpMedia)
  1647. : nullptr;
  1648. } else {
  1649. removeFromSharedMediaIndex();
  1650. refreshMedia(edition.mtpMedia);
  1651. }
  1652. if (!edition.useSameReactions) {
  1653. updateReactions(edition.mtpReactions);
  1654. }
  1655. if (!edition.useSameViews) {
  1656. changeViewsCount(edition.views);
  1657. }
  1658. if (!edition.useSameForwards) {
  1659. setForwardsCount(edition.forwards);
  1660. }
  1661. const auto &checkedMedia = updatingSavedLocalEdit
  1662. ? Get<HistoryMessageSavedMediaData>()->media
  1663. : _media;
  1664. auto updatedText = checkedMedia
  1665. ? edition.textWithEntities
  1666. : EnsureNonEmpty(edition.textWithEntities);
  1667. if (updatingSavedLocalEdit) {
  1668. Get<HistoryMessageSavedMediaData>()->text = std::move(updatedText);
  1669. } else {
  1670. setText(std::move(updatedText));
  1671. addToSharedMediaIndex();
  1672. }
  1673. if (!edition.useSameReplies) {
  1674. if (!edition.replies.isNull) {
  1675. if (checkRepliesPts(edition.replies)) {
  1676. setReplies(base::take(edition.replies));
  1677. }
  1678. } else {
  1679. clearReplies();
  1680. }
  1681. }
  1682. applyTTL(edition.ttl);
  1683. setFactcheck(FromMTP(this, edition.mtpFactcheck));
  1684. finishEdition(keyboardTop);
  1685. }
  1686. void HistoryItem::applyChanges(not_null<Data::Story*> story) {
  1687. Expects(_flags & MessageFlag::StoryItem);
  1688. Expects(StoryIdFromMsgId(id) == story->id());
  1689. _media = nullptr;
  1690. setStoryFields(story);
  1691. finishEdition(-1);
  1692. }
  1693. void HistoryItem::setStoryFields(not_null<Data::Story*> story) {
  1694. if (const auto photo = story->photo()) {
  1695. const auto spoiler = false;
  1696. _media = std::make_unique<Data::MediaPhoto>(this, photo, spoiler);
  1697. } else if (const auto document = story->document()) {
  1698. using Args = Data::MediaFile::Args;
  1699. _media = std::make_unique<Data::MediaFile>(this, document, Args{});
  1700. }
  1701. setText(story->caption());
  1702. if (story->pinnedToTop()) {
  1703. _flags |= MessageFlag::Pinned;
  1704. } else {
  1705. _flags &= ~MessageFlag::Pinned;
  1706. }
  1707. }
  1708. void HistoryItem::applyEdition(const MTPDmessageService &message) {
  1709. const auto wasSublist = savedSublist();
  1710. if (message.vaction().type() == mtpc_messageActionHistoryClear) {
  1711. const auto wasGrouped = history()->owner().groups().isGrouped(this);
  1712. setReplyMarkup({});
  1713. removeFromSharedMediaIndex();
  1714. refreshMedia(nullptr);
  1715. setTextValue({});
  1716. changeViewsCount(-1);
  1717. setForwardsCount(-1);
  1718. if (wasGrouped) {
  1719. history()->owner().groups().unregisterMessage(this);
  1720. }
  1721. if (const auto reply = Get<HistoryMessageReply>()) {
  1722. reply->clearData(this);
  1723. }
  1724. clearDependencyMessage();
  1725. UpdateComponents(0);
  1726. createServiceFromMtp(message);
  1727. applyServiceDateEdition(message);
  1728. finishEditionToEmpty();
  1729. _flags &= ~MessageFlag::DisplayFromChecked;
  1730. } else if (isService()) {
  1731. if (const auto reply = Get<HistoryMessageReply>()) {
  1732. reply->clearData(this);
  1733. }
  1734. clearDependencyMessage();
  1735. UpdateComponents(0);
  1736. createServiceFromMtp(message);
  1737. applyServiceDateEdition(message);
  1738. finishEdition(-1);
  1739. _flags &= ~MessageFlag::DisplayFromChecked;
  1740. }
  1741. const auto nowSublist = savedSublist();
  1742. if (wasSublist && nowSublist != wasSublist) {
  1743. wasSublist->removeOne(this);
  1744. nowSublist->applyMaybeLast(this);
  1745. }
  1746. }
  1747. void HistoryItem::applyEdition(
  1748. const QVector<MTPMessageExtendedMedia> &media) {
  1749. if (const auto existing = this->media()) {
  1750. if (existing->updateExtendedMedia(this, media)) {
  1751. checkBuyButton();
  1752. finishEdition(-1);
  1753. }
  1754. }
  1755. }
  1756. void HistoryItem::applySentMessage(const MTPDmessage &data) {
  1757. if (data.is_invert_media()) {
  1758. _flags |= MessageFlag::InvertMedia;
  1759. } else {
  1760. _flags &= ~MessageFlag::InvertMedia;
  1761. }
  1762. updateSentContent({
  1763. qs(data.vmessage()),
  1764. Api::EntitiesFromMTP(
  1765. &_history->session(),
  1766. data.ventities().value_or_empty())
  1767. }, data.vmedia());
  1768. updateReplyMarkup(HistoryMessageMarkupData(data.vreply_markup()));
  1769. updateForwardedInfo(data.vfwd_from());
  1770. changeViewsCount(data.vviews().value_or(-1));
  1771. if (const auto replies = data.vreplies()) {
  1772. setReplies(HistoryMessageRepliesData(replies));
  1773. } else {
  1774. clearReplies();
  1775. }
  1776. setForwardsCount(data.vforwards().value_or(-1));
  1777. if (const auto reply = data.vreply_to()) {
  1778. reply->match([&](const MTPDmessageReplyHeader &data) {
  1779. const auto replyToPeer = data.vreply_to_peer_id()
  1780. ? peerFromMTP(*data.vreply_to_peer_id())
  1781. : PeerId();
  1782. if (!replyToPeer || replyToPeer == history()->peer->id) {
  1783. if (const auto replyToId = data.vreply_to_msg_id()) {
  1784. setReplyFields(
  1785. replyToId->v,
  1786. data.vreply_to_top_id().value_or(replyToId->v),
  1787. data.is_forum_topic());
  1788. }
  1789. }
  1790. }, [](const MTPDmessageReplyStoryHeader &data) {
  1791. });
  1792. }
  1793. setPostAuthor(data.vpost_author().value_or_empty());
  1794. setIsPinned(data.is_pinned());
  1795. contributeToSlowmode(data.vdate().v);
  1796. addToSharedMediaIndex();
  1797. addToMessagesIndex();
  1798. invalidateChatListEntry();
  1799. if (const auto period = data.vttl_period(); period && period->v > 0) {
  1800. applyTTL(data.vdate().v + period->v);
  1801. } else {
  1802. applyTTL(0);
  1803. }
  1804. _history->owner().notifyItemDataChange(this);
  1805. _history->owner().requestItemTextRefresh(this);
  1806. _history->owner().updateDependentMessages(this);
  1807. }
  1808. void HistoryItem::applySentMessage(
  1809. const QString &text,
  1810. const MTPDupdateShortSentMessage &data,
  1811. bool wasAlready) {
  1812. updateSentContent({
  1813. text,
  1814. Api::EntitiesFromMTP(
  1815. &_history->session(),
  1816. data.ventities().value_or_empty())
  1817. }, data.vmedia());
  1818. contributeToSlowmode(data.vdate().v);
  1819. if (!wasAlready) {
  1820. addToSharedMediaIndex();
  1821. addToMessagesIndex();
  1822. }
  1823. invalidateChatListEntry();
  1824. if (const auto period = data.vttl_period(); period && period->v > 0) {
  1825. applyTTL(data.vdate().v + period->v);
  1826. } else {
  1827. applyTTL(0);
  1828. }
  1829. }
  1830. void HistoryItem::updateSentContent(
  1831. const TextWithEntities &textWithEntities,
  1832. const MTPMessageMedia *media) {
  1833. if (isEditingMedia()) {
  1834. return;
  1835. }
  1836. setText(textWithEntities);
  1837. if (_flags & MessageFlag::FromInlineBot) {
  1838. if (!media || !_media || !_media->updateInlineResultMedia(*media)) {
  1839. refreshSentMedia(media);
  1840. }
  1841. _flags &= ~MessageFlag::FromInlineBot;
  1842. } else if (media || _media) {
  1843. if (!media || !_media || !_media->updateSentMedia(*media)) {
  1844. refreshSentMedia(media);
  1845. }
  1846. }
  1847. history()->owner().requestItemResize(this);
  1848. }
  1849. void HistoryItem::updateForwardedInfo(const MTPMessageFwdHeader *fwd) {
  1850. const auto forwarded = Get<HistoryMessageForwarded>();
  1851. if (!fwd) {
  1852. if (forwarded) {
  1853. LOG(("API Error: Server removed forwarded information."));
  1854. }
  1855. return;
  1856. } else if (!forwarded) {
  1857. LOG(("API Error: Server added forwarded information."));
  1858. return;
  1859. }
  1860. fwd->match([&](const MTPDmessageFwdHeader &data) {
  1861. auto config = CreateConfig();
  1862. FillForwardedInfo(config, data);
  1863. setupForwardedComponent(config);
  1864. history()->owner().requestItemResize(this);
  1865. });
  1866. }
  1867. void HistoryItem::applyEditionToHistoryCleared() {
  1868. applyEdition(
  1869. MTP_messageService(
  1870. MTP_flags(0),
  1871. MTP_int(id),
  1872. peerToMTP(PeerId(0)), // from_id
  1873. peerToMTP(_history->peer->id),
  1874. MTPMessageReplyHeader(),
  1875. MTP_int(date()),
  1876. MTP_messageActionHistoryClear(),
  1877. MTPMessageReactions(),
  1878. MTPint() // ttl_period
  1879. ).c_messageService());
  1880. }
  1881. void HistoryItem::updateReplyMarkup(HistoryMessageMarkupData &&markup) {
  1882. setReplyMarkup(std::move(markup));
  1883. }
  1884. void HistoryItem::contributeToSlowmode(TimeId realDate) {
  1885. if (const auto channel = history()->peer->asChannel()) {
  1886. if (out() && isRegular() && !isService()) {
  1887. channel->growSlowmodeLastMessage(realDate ? realDate : date());
  1888. }
  1889. }
  1890. }
  1891. void HistoryItem::addToUnreadThings(HistoryUnreadThings::AddType type) {
  1892. if (!isRegular()) {
  1893. return;
  1894. }
  1895. const auto mention = isUnreadMention();
  1896. const auto reaction = hasUnreadReaction();
  1897. if (!mention && !reaction) {
  1898. return;
  1899. }
  1900. const auto topic = this->topic();
  1901. const auto history = this->history();
  1902. const auto changes = &history->session().changes();
  1903. if (mention) {
  1904. if (history->unreadMentions().add(id, type)) {
  1905. changes->historyUpdated(
  1906. history,
  1907. Data::HistoryUpdate::Flag::UnreadMentions);
  1908. }
  1909. if (topic && topic->unreadMentions().add(id, type)) {
  1910. changes->topicUpdated(
  1911. topic,
  1912. Data::TopicUpdate::Flag::UnreadMentions);
  1913. }
  1914. }
  1915. if (reaction) {
  1916. const auto toHistory = history->unreadReactions().add(id, type);
  1917. const auto toTopic = topic && topic->unreadReactions().add(id, type);
  1918. if (toHistory || toTopic) {
  1919. if (type == HistoryUnreadThings::AddType::New) {
  1920. changes->messageUpdated(
  1921. this,
  1922. Data::MessageUpdate::Flag::NewUnreadReaction);
  1923. }
  1924. if (hasUnreadReaction()) {
  1925. if (toHistory) {
  1926. changes->historyUpdated(
  1927. history,
  1928. Data::HistoryUpdate::Flag::UnreadReactions);
  1929. }
  1930. if (toTopic) {
  1931. changes->topicUpdated(
  1932. topic,
  1933. Data::TopicUpdate::Flag::UnreadReactions);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. }
  1939. void HistoryItem::destroyHistoryEntry() {
  1940. if (isUnreadMention()) {
  1941. history()->unreadMentions().erase(id);
  1942. if (const auto topic = this->topic()) {
  1943. topic->unreadMentions().erase(id);
  1944. }
  1945. }
  1946. if (hasUnreadReaction()) {
  1947. history()->unreadReactions().erase(id);
  1948. if (const auto topic = this->topic()) {
  1949. topic->unreadReactions().erase(id);
  1950. }
  1951. }
  1952. if (isRegular() && _history->peer->isMegagroup()) {
  1953. if (const auto reply = Get<HistoryMessageReply>()) {
  1954. changeReplyToTopCounter(reply, -1);
  1955. }
  1956. }
  1957. }
  1958. Storage::SharedMediaTypesMask HistoryItem::sharedMediaTypes() const {
  1959. auto result = Storage::SharedMediaTypesMask{};
  1960. const auto saved = Get<HistoryMessageSavedMediaData>();
  1961. const auto media = saved ? saved->media.get() : _media.get();
  1962. if (media) {
  1963. result.set(media->sharedMediaTypes());
  1964. }
  1965. if (hasTextLinks()) {
  1966. result.set(Storage::SharedMediaType::Link);
  1967. }
  1968. if (isPinned()) {
  1969. result.set(Storage::SharedMediaType::Pinned);
  1970. }
  1971. return result;
  1972. }
  1973. void HistoryItem::indexAsNewItem() {
  1974. if (isRegular()) {
  1975. addToUnreadThings(HistoryUnreadThings::AddType::New);
  1976. }
  1977. addToSharedMediaIndex();
  1978. }
  1979. void HistoryItem::addToSharedMediaIndex() {
  1980. if (isRegular()) {
  1981. if (const auto types = sharedMediaTypes()) {
  1982. _history->session().storage().add(Storage::SharedMediaAddNew(
  1983. _history->peer->id,
  1984. topicRootId(),
  1985. types,
  1986. id));
  1987. if (types.test(Storage::SharedMediaType::Pinned)) {
  1988. _history->setHasPinnedMessages(true);
  1989. if (const auto topic = this->topic()) {
  1990. topic->setHasPinnedMessages(true);
  1991. }
  1992. }
  1993. }
  1994. }
  1995. }
  1996. void HistoryItem::removeFromSharedMediaIndex() {
  1997. if (isRegular()) {
  1998. if (const auto types = sharedMediaTypes()) {
  1999. _history->session().storage().remove(
  2000. Storage::SharedMediaRemoveOne(
  2001. _history->peer->id,
  2002. types,
  2003. id));
  2004. }
  2005. }
  2006. }
  2007. void HistoryItem::addToMessagesIndex() {
  2008. if (isRegular()) {
  2009. if (const auto messages = _history->maybeMessages()) {
  2010. messages->addNew(id);
  2011. }
  2012. }
  2013. }
  2014. void HistoryItem::incrementReplyToTopCounter() {
  2015. if (isRegular() && _history->peer->isMegagroup()) {
  2016. _history->session().changes().messageUpdated(
  2017. this,
  2018. Data::MessageUpdate::Flag::ReplyToTopAdded);
  2019. if (const auto reply = Get<HistoryMessageReply>()) {
  2020. changeReplyToTopCounter(reply, 1);
  2021. }
  2022. }
  2023. }
  2024. void HistoryItem::changeReplyToTopCounter(
  2025. not_null<HistoryMessageReply*> reply,
  2026. int delta) {
  2027. const auto topId = reply->topMessageId();
  2028. if (!topId) {
  2029. return;
  2030. }
  2031. const auto top = _history->owner().message(_history->peer->id, topId);
  2032. if (!top) {
  2033. return;
  2034. }
  2035. const auto from = displayFrom();
  2036. const auto replier = from ? from->id : PeerId();
  2037. top->changeRepliesCount(delta, replier);
  2038. if (const auto original = top->lookupDiscussionPostOriginal()) {
  2039. original->changeRepliesCount(delta, replier);
  2040. }
  2041. }
  2042. QString HistoryItem::notificationHeader() const {
  2043. if (isService()) {
  2044. return QString();
  2045. } else if (out() && isFromScheduled() && !_history->peer->isSelf()) {
  2046. return tr::lng_from_you(tr::now);
  2047. } else if (!_history->peer->isUser() && !isPostHidingAuthor()) {
  2048. return from()->name();
  2049. }
  2050. return QString();
  2051. }
  2052. void HistoryItem::setRealId(MsgId newId) {
  2053. Expects(_flags & MessageFlag::BeingSent);
  2054. Expects(IsClientMsgId(id));
  2055. const auto oldId = std::exchange(id, newId);
  2056. _flags &= ~(MessageFlag::BeingSent | MessageFlag::Local);
  2057. if (isBusinessShortcut()) {
  2058. _date = 0;
  2059. }
  2060. if (isRegular()) {
  2061. _history->unregisterClientSideMessage(this);
  2062. }
  2063. _history->owner().notifyItemIdChange({ fullId(), oldId });
  2064. // We don't fire MessageUpdate::Flag::ReplyMarkup and update keyboard
  2065. // in history widget, because it can't exist for an outgoing message.
  2066. // Only inline keyboards can be in outgoing messages.
  2067. if (const auto markup = inlineReplyMarkup()) {
  2068. if (markup->inlineKeyboard) {
  2069. markup->inlineKeyboard->updateMessageId();
  2070. }
  2071. }
  2072. _history->owner().notifyItemDataChange(this);
  2073. _history->owner().groups().refreshMessage(this);
  2074. _history->owner().requestItemResize(this);
  2075. if (const auto reply = Get<HistoryMessageReply>()) {
  2076. incrementReplyToTopCounter();
  2077. }
  2078. if (out() && starsPaid()) {
  2079. _history->session().credits().load(true);
  2080. }
  2081. }
  2082. bool HistoryItem::canPin() const {
  2083. if (!isRegular() || isService()) {
  2084. return false;
  2085. } else if (const auto m = media(); m && m->call()) {
  2086. return false;
  2087. }
  2088. return _history->peer->canPinMessages();
  2089. }
  2090. bool HistoryItem::allowsSendNow() const {
  2091. return !isService()
  2092. && isScheduled()
  2093. && !isSending()
  2094. && !hasFailed()
  2095. && !isEditingMedia();
  2096. }
  2097. bool HistoryItem::allowsReschedule() const {
  2098. return allowsSendNow() && !awaitingVideoProcessing();
  2099. }
  2100. bool HistoryItem::allowsForward() const {
  2101. return !isService()
  2102. && isRegular()
  2103. && !forbidsForward()
  2104. && history()->peer->allowsForwarding()
  2105. && (!_media || _media->allowsForward());
  2106. }
  2107. bool HistoryItem::isTooOldForEdit(TimeId now) const {
  2108. return !_history->peer->canEditMessagesIndefinitely()
  2109. && !isScheduled()
  2110. && (now - date() >= _history->session().serverConfig().editTimeLimit);
  2111. }
  2112. bool HistoryItem::allowsEdit(TimeId now) const {
  2113. return !isService()
  2114. && canBeEdited()
  2115. && !isTooOldForEdit(now)
  2116. && (!_media || _media->allowsEdit())
  2117. && !isLegacyMessage()
  2118. && !isEditingMedia();
  2119. }
  2120. bool HistoryItem::allowsEditMedia() const {
  2121. return !awaitingVideoProcessing()
  2122. && (!_media || _media->allowsEditMedia() || _media->webpage());
  2123. }
  2124. bool HistoryItem::canBeEdited() const {
  2125. if ((!isRegular() && !isScheduled() && !isBusinessShortcut())
  2126. || Has<HistoryMessageVia>()
  2127. || Has<HistoryMessageForwarded>()) {
  2128. return false;
  2129. }
  2130. const auto peer = _history->peer;
  2131. if (peer->isSelf()) {
  2132. return true;
  2133. } else if (const auto channel = peer->asChannel()) {
  2134. if (isPost() && channel->canEditMessages()) {
  2135. return true;
  2136. } else if (out()) {
  2137. if (isPost()) {
  2138. return channel->canPostMessages();
  2139. } else if (const auto topic = this->topic()) {
  2140. return Data::CanSendAnything(topic);
  2141. } else {
  2142. return Data::CanSendAnything(channel);
  2143. }
  2144. } else {
  2145. return false;
  2146. }
  2147. }
  2148. return out();
  2149. }
  2150. bool HistoryItem::canStopPoll() const {
  2151. return canBeEdited() && isRegular();
  2152. }
  2153. bool HistoryItem::forbidsForward() const {
  2154. return (_flags & MessageFlag::NoForwards);
  2155. }
  2156. bool HistoryItem::forbidsSaving() const {
  2157. if (forbidsForward()) {
  2158. return true;
  2159. } else if (const auto invoice = _media ? _media->invoice() : nullptr) {
  2160. return HasExtendedMedia(*invoice);
  2161. }
  2162. return false;
  2163. }
  2164. bool HistoryItem::canDelete() const {
  2165. if (isSponsored()) {
  2166. return false;
  2167. } else if (IsStoryMsgId(id)) {
  2168. return false;
  2169. } else if (isService() && !isRegular()) {
  2170. return false;
  2171. } else if (topicRootId() == id) {
  2172. return false;
  2173. } else if (!isHistoryEntry()
  2174. && !isScheduled()
  2175. && !isBusinessShortcut()) {
  2176. return false;
  2177. }
  2178. auto channel = _history->peer->asChannel();
  2179. if (!channel) {
  2180. return !isGroupMigrate();
  2181. }
  2182. if (id == 1) {
  2183. return false;
  2184. }
  2185. if (channel->canDeleteMessages()) {
  2186. return true;
  2187. } else if (out() && !isService()) {
  2188. return isPost() ? channel->canPostMessages() : true;
  2189. }
  2190. return false;
  2191. }
  2192. bool HistoryItem::canDeleteForEveryone(TimeId now) const {
  2193. const auto peer = _history->peer;
  2194. const auto &config = _history->session().serverConfig();
  2195. const auto messageToMyself = peer->isSelf();
  2196. const auto messageTooOld = messageToMyself
  2197. ? false
  2198. : peer->isUser()
  2199. ? (now - date() >= config.revokePrivateTimeLimit)
  2200. : (now - date() >= config.revokeTimeLimit);
  2201. if (!isRegular() || messageToMyself || messageTooOld || isPost()) {
  2202. return false;
  2203. }
  2204. if (peer->isChannel()) {
  2205. return false;
  2206. } else if (const auto user = peer->asUser()) {
  2207. // Bots receive all messages and there is no sense in revoking them.
  2208. // See https://github.com/telegramdesktop/tdesktop/issues/3818
  2209. if ((user->isBot() && !user->isSupport())
  2210. || user->isInaccessible()) {
  2211. return false;
  2212. }
  2213. }
  2214. if (const auto media = this->media()) {
  2215. if (!media->allowsRevoke(now)) {
  2216. return false;
  2217. }
  2218. }
  2219. if (!out()) {
  2220. if (const auto chat = peer->asChat()) {
  2221. if (!chat->canDeleteMessages()) {
  2222. return false;
  2223. }
  2224. } else if (peer->isUser()) {
  2225. return config.revokePrivateInbox;
  2226. } else {
  2227. return false;
  2228. }
  2229. }
  2230. return true;
  2231. }
  2232. bool HistoryItem::suggestReport() const {
  2233. if (out() || isService() || !isRegular()) {
  2234. return false;
  2235. } else if (const auto channel = _history->peer->asChannel()) {
  2236. return true;
  2237. } else if (const auto user = _history->peer->asUser()) {
  2238. return user->isBot();
  2239. }
  2240. return false;
  2241. }
  2242. bool HistoryItem::suggestBanReport() const {
  2243. const auto channel = _history->peer->asChannel();
  2244. if (!channel || !channel->canRestrictParticipant(from())) {
  2245. return false;
  2246. }
  2247. return !isPost() && !out();
  2248. }
  2249. bool HistoryItem::suggestDeleteAllReport() const {
  2250. auto channel = _history->peer->asChannel();
  2251. if (!channel || !channel->canDeleteMessages()) {
  2252. return false;
  2253. }
  2254. return !isPost() && !out();
  2255. }
  2256. ChatRestriction HistoryItem::requiredSendRight() const {
  2257. const auto media = this->media();
  2258. if (media && media->game()) {
  2259. return ChatRestriction::SendGames;
  2260. }
  2261. const auto photo = (media && !media->webpage())
  2262. ? media->photo()
  2263. : nullptr;
  2264. const auto document = (media && !media->webpage())
  2265. ? media->document()
  2266. : nullptr;
  2267. if (photo) {
  2268. return ChatRestriction::SendPhotos;
  2269. } else if (document) {
  2270. return document->requiredSendRight();
  2271. } else if (media && media->poll()) {
  2272. return ChatRestriction::SendPolls;
  2273. }
  2274. return ChatRestriction::SendOther;
  2275. }
  2276. bool HistoryItem::requiresSendInlineRight() const {
  2277. return Has<HistoryMessageVia>();
  2278. }
  2279. Data::SendError HistoryItem::errorTextForForward(
  2280. not_null<Data::Thread*> to) const {
  2281. const auto requiredRight = requiredSendRight();
  2282. const auto requiresInline = requiresSendInlineRight();
  2283. const auto peer = to->peer();
  2284. constexpr auto kInline = ChatRestriction::SendInline;
  2285. if (const auto error = Data::RestrictionError(peer, requiredRight)) {
  2286. return error;
  2287. } else if (requiresInline && !Data::CanSend(to, kInline)) {
  2288. const auto forInline = Data::RestrictionError(peer, kInline);
  2289. return forInline ? forInline : tr::lng_forward_cant(tr::now);
  2290. } else if (_media
  2291. && _media->poll()
  2292. && _media->poll()->publicVotes()
  2293. && peer->isBroadcast()) {
  2294. return tr::lng_restricted_send_public_polls(tr::now);
  2295. } else if (_media
  2296. && _media->invoice()
  2297. && _media->invoice()->isPaidMedia
  2298. && peer->isBroadcast()
  2299. && peer->isFullLoaded()
  2300. && !peer->asBroadcast()->canPostPaidMedia()) {
  2301. return tr::lng_restricted_send_paid_media(tr::now);
  2302. } else if (!Data::CanSend(to, requiredRight, false)) {
  2303. return tr::lng_forward_cant(tr::now);
  2304. }
  2305. return {};
  2306. }
  2307. const HistoryMessageTranslation *HistoryItem::translation() const {
  2308. return Get<HistoryMessageTranslation>();
  2309. }
  2310. bool HistoryItem::translationShowRequiresCheck(LanguageId to) const {
  2311. // Check if a call to translationShowRequiresRequest(to) is not a no-op.
  2312. if (!to) {
  2313. if (const auto translation = Get<HistoryMessageTranslation>()) {
  2314. return (!translation->failed && translation->text.empty())
  2315. || translation->used;
  2316. }
  2317. return false;
  2318. } else if (const auto translation = Get<HistoryMessageTranslation>()) {
  2319. if (translation->to == to) {
  2320. return !translation->used && !translation->text.empty();
  2321. }
  2322. return true;
  2323. } else {
  2324. return true;
  2325. }
  2326. }
  2327. bool HistoryItem::translationShowRequiresRequest(LanguageId to) {
  2328. // When changing be sure to reflect in translationShowRequiresCheck(to).
  2329. if (!to) {
  2330. if (const auto translation = Get<HistoryMessageTranslation>()) {
  2331. if (!translation->failed && translation->text.empty()) {
  2332. Assert(!translation->used);
  2333. RemoveComponents(HistoryMessageTranslation::Bit());
  2334. } else {
  2335. translationToggle(translation, false);
  2336. }
  2337. }
  2338. return false;
  2339. } else if (const auto translation = Get<HistoryMessageTranslation>()) {
  2340. if (translation->to == to) {
  2341. translationToggle(translation, true);
  2342. return false;
  2343. }
  2344. translationToggle(translation, false);
  2345. translation->to = to;
  2346. translation->requested = true;
  2347. translation->failed = false;
  2348. translation->text = {};
  2349. return true;
  2350. } else {
  2351. AddComponents(HistoryMessageTranslation::Bit());
  2352. const auto added = Get<HistoryMessageTranslation>();
  2353. added->to = to;
  2354. added->requested = true;
  2355. return true;
  2356. }
  2357. }
  2358. void HistoryItem::translationToggle(
  2359. not_null<HistoryMessageTranslation*> translation,
  2360. bool used) {
  2361. if (translation->used != used && !translation->text.empty()) {
  2362. translation->used = used;
  2363. _history->owner().requestItemTextRefresh(this);
  2364. _history->owner().updateDependentMessages(this);
  2365. }
  2366. }
  2367. void HistoryItem::translationDone(LanguageId to, TextWithEntities result) {
  2368. const auto set = [&](not_null<HistoryMessageTranslation*> translation) {
  2369. if (result.empty()) {
  2370. translation->failed = true;
  2371. } else {
  2372. translation->text = std::move(result);
  2373. if (_history->translatedTo() == to) {
  2374. translationToggle(translation, true);
  2375. }
  2376. }
  2377. };
  2378. if (const auto translation = Get<HistoryMessageTranslation>()) {
  2379. if (translation->to == to && translation->text.empty()) {
  2380. translation->requested = false;
  2381. set(translation);
  2382. }
  2383. } else {
  2384. AddComponents(HistoryMessageTranslation::Bit());
  2385. const auto added = Get<HistoryMessageTranslation>();
  2386. added->to = to;
  2387. set(added);
  2388. }
  2389. }
  2390. bool HistoryItem::canReact() const {
  2391. if (!isRegular()) {
  2392. return false;
  2393. } else if (isService()) {
  2394. return (_flags & MessageFlag::ReactionsAllowed);
  2395. } else if (const auto media = this->media()) {
  2396. if (media->call()) {
  2397. return (_flags & MessageFlag::ReactionsAllowed);
  2398. }
  2399. }
  2400. return true;
  2401. }
  2402. void HistoryItem::addPaidReaction(
  2403. int count,
  2404. std::optional<PeerId> shownPeer) {
  2405. Expects(count >= 0);
  2406. Expects(_history->peer->isBroadcast() || isDiscussionPost());
  2407. if (!_reactions) {
  2408. _reactions = std::make_unique<Data::MessageReactions>(this);
  2409. }
  2410. _reactions->scheduleSendPaid(count, shownPeer);
  2411. if (count > 0) {
  2412. _history->owner().notifyItemDataChange(this);
  2413. }
  2414. }
  2415. void HistoryItem::cancelScheduledPaidReaction() {
  2416. if (_reactions) {
  2417. _reactions->cancelScheduledPaid();
  2418. _history->owner().notifyItemDataChange(this);
  2419. }
  2420. }
  2421. Data::PaidReactionSend HistoryItem::startPaidReactionSending() {
  2422. return _reactions
  2423. ? _reactions->startPaidSending()
  2424. : Data::PaidReactionSend();
  2425. }
  2426. void HistoryItem::finishPaidReactionSending(
  2427. Data::PaidReactionSend send,
  2428. bool success) {
  2429. Expects(_reactions != nullptr);
  2430. _reactions->finishPaidSending(send, success);
  2431. _history->owner().notifyItemDataChange(this);
  2432. }
  2433. void HistoryItem::toggleReaction(
  2434. const Data::ReactionId &reaction,
  2435. HistoryReactionSource source) {
  2436. Expects(!reaction.paid());
  2437. const auto addToRecent = (source == HistoryReactionSource::Selector);
  2438. if (!_reactions) {
  2439. _reactions = std::make_unique<Data::MessageReactions>(this);
  2440. const auto canViewReactions = !isDiscussionPost()
  2441. && (_history->peer->isChat() || _history->peer->isMegagroup());
  2442. if (canViewReactions) {
  2443. _flags |= MessageFlag::CanViewReactions;
  2444. }
  2445. _reactions->add(reaction, addToRecent);
  2446. } else if (ranges::contains(_reactions->chosen(), reaction)) {
  2447. _reactions->remove(reaction);
  2448. if (_reactions->empty() && !_reactions->localPaidData()) {
  2449. _reactions = nullptr;
  2450. _flags &= ~MessageFlag::CanViewReactions;
  2451. }
  2452. } else {
  2453. _reactions->add(reaction, addToRecent);
  2454. }
  2455. _history->owner().notifyItemDataChange(this);
  2456. }
  2457. void HistoryItem::updateReactionsUnknown() {
  2458. _reactionsLastRefreshed = 1;
  2459. }
  2460. const std::vector<Data::MessageReaction> &HistoryItem::reactions() const {
  2461. static const auto kEmpty = std::vector<Data::MessageReaction>();
  2462. return _reactions ? _reactions->list() : kEmpty;
  2463. }
  2464. std::vector<Data::MessageReaction> HistoryItem::reactionsWithLocal() const {
  2465. if (!_reactions) {
  2466. return {};
  2467. }
  2468. auto result = _reactions->list();
  2469. const auto i = ranges::find(
  2470. result,
  2471. Data::ReactionId::Paid(),
  2472. &Data::MessageReaction::id);
  2473. if (const auto local = _reactions->localPaidCount()) {
  2474. if (i != end(result)) {
  2475. i->my = true;
  2476. i->count += local;
  2477. if (i != begin(result)) {
  2478. std::rotate(begin(result), i, i + 1);
  2479. }
  2480. } else {
  2481. result.insert(begin(result), Data::MessageReaction{
  2482. .id = Data::ReactionId::Paid(),
  2483. .count = local,
  2484. .my = true,
  2485. });
  2486. }
  2487. } else if (i != end(result) && i != begin(result)) {
  2488. std::rotate(begin(result), i, i + 1);
  2489. }
  2490. return result;
  2491. }
  2492. int HistoryItem::reactionsPaidScheduled() const {
  2493. return _reactions ? _reactions->scheduledPaid() : 0;
  2494. }
  2495. PeerId HistoryItem::reactionsLocalShownPeer() const {
  2496. return _reactions
  2497. ? _reactions->localPaidShownPeer()
  2498. : _history->session().userPeerId();
  2499. }
  2500. bool HistoryItem::reactionsAreTags() const {
  2501. return _flags & MessageFlag::ReactionsAreTags;
  2502. }
  2503. auto HistoryItem::recentReactions() const
  2504. -> const base::flat_map<
  2505. Data::ReactionId,
  2506. std::vector<Data::RecentReaction>> & {
  2507. static const auto kEmpty = base::flat_map<
  2508. Data::ReactionId,
  2509. std::vector<Data::RecentReaction>>();
  2510. return _reactions ? _reactions->recent() : kEmpty;
  2511. }
  2512. auto HistoryItem::topPaidReactionsWithLocal() const
  2513. -> std::vector<Data::MessageReactionsTopPaid> {
  2514. if (!_reactions) {
  2515. return {};
  2516. }
  2517. using TopPaid = Data::MessageReactionsTopPaid;
  2518. auto result = _reactions->topPaid();
  2519. const auto i = ranges::find_if(
  2520. result,
  2521. [](const TopPaid &entry) { return entry.my != 0; });
  2522. const auto peerForMine = [&] {
  2523. const auto peerId = _reactions->localPaidShownPeer();
  2524. return peerId ? history()->owner().peer(peerId).get() : nullptr;
  2525. };
  2526. if (const auto local = _reactions->localPaidCount()) {
  2527. const auto top = [&](int mine) {
  2528. return ranges::count_if(result, [&](const TopPaid &entry) {
  2529. return !entry.my && entry.count >= mine;
  2530. }) < 3;
  2531. };
  2532. if (i != end(result)) {
  2533. i->count += local;
  2534. i->peer = peerForMine();
  2535. i->top = top(i->count) ? 1 : 0;
  2536. } else {
  2537. result.push_back({
  2538. .peer = peerForMine(),
  2539. .count = uint32(local),
  2540. .top = uint32(top(local) ? 1 : 0),
  2541. .my = uint32(1),
  2542. });
  2543. }
  2544. } else if (i != end(result)) {
  2545. i->peer = peerForMine();
  2546. }
  2547. return result;
  2548. }
  2549. bool HistoryItem::canViewReactions() const {
  2550. return (_flags & MessageFlag::CanViewReactions)
  2551. && _reactions
  2552. && !_reactions->list().empty();
  2553. }
  2554. std::vector<Data::ReactionId> HistoryItem::chosenReactions() const {
  2555. return _reactions
  2556. ? _reactions->chosen()
  2557. : std::vector<Data::ReactionId>();
  2558. }
  2559. Data::ReactionId HistoryItem::lookupUnreadReaction(
  2560. not_null<UserData*> from) const {
  2561. if (!_reactions) {
  2562. return {};
  2563. }
  2564. const auto recent = _reactions->recent();
  2565. for (const auto &[id, list] : _reactions->recent()) {
  2566. const auto i = ranges::find(
  2567. list,
  2568. from,
  2569. &Data::RecentReaction::peer);
  2570. if (i != end(list) && i->unread) {
  2571. return id;
  2572. }
  2573. }
  2574. return {};
  2575. }
  2576. crl::time HistoryItem::lastReactionsRefreshTime() const {
  2577. return _reactionsLastRefreshed;
  2578. }
  2579. bool HistoryItem::hasDirectLink() const {
  2580. return isRegular() && _history->peer->isChannel();
  2581. }
  2582. bool HistoryItem::changesWallPaper() const {
  2583. if (const auto media = _media.get()) {
  2584. return media->paper() != nullptr;
  2585. }
  2586. return Has<HistoryServiceSameBackground>();
  2587. }
  2588. FullMsgId HistoryItem::fullId() const {
  2589. return FullMsgId(_history->peer->id, id);
  2590. }
  2591. GlobalMsgId HistoryItem::globalId() const {
  2592. return { fullId(), _history->session().uniqueId() };
  2593. }
  2594. Data::MessagePosition HistoryItem::position() const {
  2595. return { .fullId = fullId(), .date = date() };
  2596. }
  2597. bool HistoryItem::computeDropForwardedInfo() const {
  2598. const auto media = this->media();
  2599. return (media && media->dropForwardedInfo())
  2600. || (_history->peer->isSelf()
  2601. && !Has<HistoryMessageForwarded>()
  2602. && (!media || !media->forceForwardedInfo()));
  2603. }
  2604. bool HistoryItem::inThread(MsgId rootId) const {
  2605. return (replyToTop() == rootId)
  2606. || (topicRootId() == rootId);
  2607. }
  2608. not_null<PeerData*> HistoryItem::author() const {
  2609. return (isPostHidingAuthor() && !isSponsored())
  2610. ? _history->peer
  2611. : from();
  2612. }
  2613. TimeId HistoryItem::originalDate() const {
  2614. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2615. return forwarded->originalDate;
  2616. }
  2617. return date();
  2618. }
  2619. PeerData *HistoryItem::originalSender() const {
  2620. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2621. return forwarded->originalSender;
  2622. }
  2623. const auto peer = _history->peer;
  2624. return peer->isBroadcast() ? peer : from();
  2625. }
  2626. const HiddenSenderInfo *HistoryItem::originalHiddenSenderInfo() const {
  2627. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2628. return forwarded->originalHiddenSenderInfo.get();
  2629. }
  2630. return nullptr;
  2631. }
  2632. const HiddenSenderInfo *HistoryItem::displayHiddenSenderInfo() const {
  2633. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2634. return forwarded->savedFromHiddenSenderInfo
  2635. ? forwarded->savedFromHiddenSenderInfo.get()
  2636. : forwarded->originalHiddenSenderInfo.get();
  2637. }
  2638. return nullptr;
  2639. }
  2640. bool HistoryItem::showForwardsFromSender(
  2641. not_null<const HistoryMessageForwarded*> forwarded) const {
  2642. const auto peer = history()->peer;
  2643. return !forwarded->story
  2644. && (peer->isSelf()
  2645. || peer->isRepliesChat()
  2646. || peer->isVerifyCodes()
  2647. || forwarded->imported);
  2648. }
  2649. not_null<PeerData*> HistoryItem::fromOriginal() const {
  2650. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2651. if (forwarded->originalSender) {
  2652. if (const auto user = forwarded->originalSender->asUser()) {
  2653. return user;
  2654. }
  2655. }
  2656. }
  2657. return from();
  2658. }
  2659. QString HistoryItem::originalPostAuthor() const {
  2660. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2661. return forwarded->originalPostAuthor;
  2662. } else if (const auto msgsigned = Get<HistoryMessageSigned>()) {
  2663. if (!msgsigned->isAnonymousRank && !msgsigned->viaBusinessBot) {
  2664. return msgsigned->author;
  2665. }
  2666. }
  2667. return QString();
  2668. }
  2669. MsgId HistoryItem::originalId() const {
  2670. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2671. return forwarded->originalId;
  2672. }
  2673. return id;
  2674. }
  2675. const TextWithEntities &HistoryItem::originalText() const {
  2676. static const auto kEmpty = TextWithEntities();
  2677. return isService() ? kEmpty : _text;
  2678. }
  2679. const TextWithEntities &HistoryItem::translatedText() const {
  2680. if (isService()) {
  2681. static const auto kEmpty = TextWithEntities();
  2682. return kEmpty;
  2683. } else if (const auto translation = this->translation()
  2684. ; translation
  2685. && translation->used
  2686. && (translation->to == history()->translatedTo())) {
  2687. return translation->text;
  2688. } else {
  2689. return originalText();
  2690. }
  2691. }
  2692. TextWithEntities HistoryItem::translatedTextWithLocalEntities() const {
  2693. if (isService()) {
  2694. return {};
  2695. } else {
  2696. return withLocalEntities(translatedText());
  2697. }
  2698. }
  2699. TextForMimeData HistoryItem::clipboardText() const {
  2700. return isService()
  2701. ? TextForMimeData()
  2702. : TextForMimeData::WithExpandedLinks(translatedText());
  2703. }
  2704. bool HistoryItem::changeViewsCount(int count) {
  2705. const auto views = Get<HistoryMessageViews>();
  2706. if (!views
  2707. || views->views.count == count
  2708. || (count >= 0 && views->views.count > count)) {
  2709. return false;
  2710. }
  2711. views->views.count = count;
  2712. return true;
  2713. }
  2714. void HistoryItem::setForwardsCount(int count) {
  2715. const auto views = Get<HistoryMessageViews>();
  2716. if (!views
  2717. || views->forwardsCount == count
  2718. || (count >= 0 && views->forwardsCount > count)) {
  2719. return;
  2720. }
  2721. views->forwardsCount = count;
  2722. history()->owner().notifyItemDataChange(this);
  2723. }
  2724. void HistoryItem::setPostAuthor(const QString &postAuthor) {
  2725. auto msgsigned = Get<HistoryMessageSigned>();
  2726. if (msgsigned && msgsigned->viaBusinessBot) {
  2727. return;
  2728. } else if (postAuthor.isEmpty()) {
  2729. if (!msgsigned) {
  2730. return;
  2731. }
  2732. RemoveComponents(HistoryMessageSigned::Bit());
  2733. history()->owner().requestItemResize(this);
  2734. return;
  2735. }
  2736. if (!msgsigned) {
  2737. AddComponents(HistoryMessageSigned::Bit());
  2738. msgsigned = Get<HistoryMessageSigned>();
  2739. } else if (msgsigned->author == postAuthor) {
  2740. return;
  2741. }
  2742. msgsigned->author = postAuthor;
  2743. msgsigned->isAnonymousRank = !isDiscussionPost()
  2744. && this->author()->isMegagroup();
  2745. history()->owner().requestItemResize(this);
  2746. }
  2747. void HistoryItem::setReplies(HistoryMessageRepliesData &&data) {
  2748. if (data.isNull) {
  2749. return;
  2750. }
  2751. auto views = Get<HistoryMessageViews>();
  2752. if (!views) {
  2753. AddComponents(HistoryMessageViews::Bit());
  2754. views = Get<HistoryMessageViews>();
  2755. }
  2756. const auto &repliers = data.recentRepliers;
  2757. const auto count = data.repliesCount;
  2758. const auto channelId = data.channelId;
  2759. const auto readTillId = data.readMaxId
  2760. ? std::max({
  2761. views->commentsInboxReadTillId.bare,
  2762. data.readMaxId.bare,
  2763. int64(1),
  2764. })
  2765. : views->commentsInboxReadTillId;
  2766. const auto maxId = data.maxId ? data.maxId : views->commentsMaxId;
  2767. const auto countsChanged = (views->replies.count != count)
  2768. || (views->commentsInboxReadTillId != readTillId)
  2769. || (views->commentsMaxId != maxId);
  2770. const auto megagroupChanged = (views->commentsMegagroupId != channelId);
  2771. const auto recentChanged = (views->recentRepliers != repliers);
  2772. if (!countsChanged && !megagroupChanged && !recentChanged) {
  2773. return;
  2774. }
  2775. views->replies.count = count;
  2776. if (recentChanged) {
  2777. views->recentRepliers = repliers;
  2778. }
  2779. const auto wasUnread = areCommentsUnread();
  2780. views->commentsMegagroupId = channelId;
  2781. views->commentsInboxReadTillId = readTillId;
  2782. views->commentsMaxId = maxId;
  2783. if (wasUnread != areCommentsUnread()) {
  2784. history()->owner().requestItemRepaint(this);
  2785. }
  2786. refreshRepliesText(views, megagroupChanged);
  2787. }
  2788. void HistoryItem::clearReplies() {
  2789. auto views = Get<HistoryMessageViews>();
  2790. if (!views) {
  2791. return;
  2792. }
  2793. const auto viewsPart = views->views;
  2794. if (viewsPart.count < 0) {
  2795. RemoveComponents(HistoryMessageViews::Bit());
  2796. } else {
  2797. *views = HistoryMessageViews();
  2798. views->views = viewsPart;
  2799. }
  2800. history()->owner().requestItemResize(this);
  2801. }
  2802. void HistoryItem::refreshRepliesText(
  2803. not_null<HistoryMessageViews*> views,
  2804. bool forceResize) {
  2805. if (views->commentsMegagroupId) {
  2806. views->replies.text = (views->replies.count > 0)
  2807. ? tr::lng_comments_open_count(
  2808. tr::now,
  2809. lt_count_short,
  2810. views->replies.count)
  2811. : tr::lng_comments_open_none(tr::now);
  2812. views->replies.textWidth = st::semiboldFont->width(
  2813. views->replies.text);
  2814. views->repliesSmall.text = (views->replies.count > 0)
  2815. ? Lang::FormatCountToShort(views->replies.count).string
  2816. : QString();
  2817. const auto hadText = (views->repliesSmall.textWidth > 0);
  2818. views->repliesSmall.textWidth = (views->replies.count > 0)
  2819. ? st::semiboldFont->width(views->repliesSmall.text)
  2820. : 0;
  2821. const auto hasText = (views->repliesSmall.textWidth > 0);
  2822. if (hasText != hadText) {
  2823. forceResize = true;
  2824. }
  2825. }
  2826. if (forceResize) {
  2827. history()->owner().requestItemResize(this);
  2828. } else {
  2829. history()->owner().requestItemRepaint(this);
  2830. }
  2831. }
  2832. void HistoryItem::changeRepliesCount(int delta, PeerId replier) {
  2833. const auto views = Get<HistoryMessageViews>();
  2834. const auto limit = HistoryMessageViews::kMaxRecentRepliers;
  2835. if (!views) {
  2836. return;
  2837. }
  2838. // Update full count.
  2839. if (views->replies.count < 0) {
  2840. return;
  2841. }
  2842. views->replies.count = std::max(views->replies.count + delta, 0);
  2843. if (replier && views->commentsMegagroupId) {
  2844. if (delta < 0) {
  2845. views->recentRepliers.erase(
  2846. ranges::remove(views->recentRepliers, replier),
  2847. end(views->recentRepliers));
  2848. } else if (!ranges::contains(views->recentRepliers, replier)) {
  2849. views->recentRepliers.insert(views->recentRepliers.begin(), replier);
  2850. while (views->recentRepliers.size() > limit) {
  2851. views->recentRepliers.pop_back();
  2852. }
  2853. }
  2854. }
  2855. refreshRepliesText(views);
  2856. history()->owner().notifyItemDataChange(this);
  2857. }
  2858. void HistoryItem::setReplyFields(
  2859. MsgId replyTo,
  2860. MsgId replyToTop,
  2861. bool isForumPost) {
  2862. if (isScheduled()) {
  2863. return;
  2864. } else if (const auto data = GetServiceDependentData()) {
  2865. if ((data->topId != replyToTop) && !IsServerMsgId(data->topId)) {
  2866. data->topId = replyToTop;
  2867. if (isForumPost) {
  2868. data->topicPost = true;
  2869. }
  2870. }
  2871. } else if (const auto reply = Get<HistoryMessageReply>()) {
  2872. const auto increment = (reply->topMessageId() != replyToTop)
  2873. && !IsServerMsgId(reply->topMessageId());
  2874. reply->updateFields(this, replyTo, replyToTop, isForumPost);
  2875. if (increment) {
  2876. incrementReplyToTopCounter();
  2877. }
  2878. }
  2879. if (const auto topic = this->topic()) {
  2880. topic->maybeSetLastMessage(this);
  2881. }
  2882. }
  2883. void HistoryItem::updateDate(TimeId newDate) {
  2884. if (canUpdateDate() && _date != newDate) {
  2885. _date = newDate;
  2886. _history->owner().requestItemViewRefresh(this);
  2887. }
  2888. }
  2889. bool HistoryItem::canUpdateDate() const {
  2890. return isScheduled();
  2891. }
  2892. void HistoryItem::applyTTL(TimeId destroyAt) {
  2893. const auto previousDestroyAt = std::exchange(_ttlDestroyAt, destroyAt);
  2894. if (previousDestroyAt) {
  2895. _history->owner().unregisterMessageTTL(previousDestroyAt, this);
  2896. }
  2897. if (!_ttlDestroyAt) {
  2898. return;
  2899. } else if (base::unixtime::now() >= _ttlDestroyAt) {
  2900. const auto session = &_history->session();
  2901. crl::on_main(session, [session, id = fullId()]{
  2902. if (const auto item = session->data().message(id)) {
  2903. item->destroy();
  2904. }
  2905. });
  2906. } else {
  2907. _history->owner().registerMessageTTL(_ttlDestroyAt, this);
  2908. }
  2909. }
  2910. void HistoryItem::replaceBuyWithReceiptInMarkup() {
  2911. if (const auto markup = inlineReplyMarkup()) {
  2912. for (auto &row : markup->data.rows) {
  2913. for (auto &button : row) {
  2914. if (button.type == HistoryMessageMarkupButton::Type::Buy) {
  2915. const auto receipt = tr::lng_payments_receipt_button(tr::now);
  2916. if (button.text != receipt) {
  2917. button.text = receipt;
  2918. if (markup->inlineKeyboard) {
  2919. markup->inlineKeyboard = nullptr;
  2920. _history->owner().requestItemResize(this);
  2921. }
  2922. }
  2923. }
  2924. }
  2925. }
  2926. }
  2927. }
  2928. bool HistoryItem::isUploading() const {
  2929. return _media && _media->uploading();
  2930. }
  2931. bool HistoryItem::hasRealFromId() const {
  2932. return !isPost() || (_flags & MessageFlag::HasFromId);
  2933. }
  2934. bool HistoryItem::isPostHidingAuthor() const {
  2935. if (!isPost()) {
  2936. return false;
  2937. } else if (const auto channel = _history->peer->asBroadcast()) {
  2938. return !channel->signatureProfiles();
  2939. }
  2940. return false; // Should not happen, I guess.
  2941. }
  2942. bool HistoryItem::isPostShowingAuthor() const {
  2943. return isPost() && !isPostHidingAuthor();
  2944. }
  2945. bool HistoryItem::isRegular() const {
  2946. return isHistoryEntry() && !isLocal();
  2947. }
  2948. int HistoryItem::viewsCount() const {
  2949. if (const auto views = Get<HistoryMessageViews>()) {
  2950. return std::max(views->views.count, 0);
  2951. }
  2952. return hasViews() ? 1 : -1;
  2953. }
  2954. int HistoryItem::repliesCount() const {
  2955. if (const auto views = Get<HistoryMessageViews>()) {
  2956. if (!checkCommentsLinkedChat(views->commentsMegagroupId)) {
  2957. return 0;
  2958. }
  2959. return std::max(views->replies.count, 0);
  2960. }
  2961. return 0;
  2962. }
  2963. bool HistoryItem::repliesAreComments() const {
  2964. if (const auto views = Get<HistoryMessageViews>()) {
  2965. return (views->commentsMegagroupId != 0)
  2966. && checkCommentsLinkedChat(views->commentsMegagroupId);
  2967. }
  2968. return false;
  2969. }
  2970. bool HistoryItem::externalReply() const {
  2971. if (!_history->peer->isRepliesChat()) {
  2972. return false;
  2973. } else if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  2974. return forwarded->savedFromPeer && forwarded->savedFromMsgId;
  2975. }
  2976. return false;
  2977. }
  2978. bool HistoryItem::hasUnpaidContent() const {
  2979. if (const auto media = _media.get()) {
  2980. if (const auto invoice = media->invoice()) {
  2981. return HasUnpaidMedia(*invoice);
  2982. }
  2983. }
  2984. return false;
  2985. }
  2986. void HistoryItem::sendFailed() {
  2987. Expects(_flags & MessageFlag::BeingSent);
  2988. Expects(!(_flags & MessageFlag::SendingFailed));
  2989. _flags = (_flags | MessageFlag::SendingFailed) & ~MessageFlag::BeingSent;
  2990. _history->owner().notifyItemDataChange(this);
  2991. _history->session().changes().historyUpdated(
  2992. _history,
  2993. Data::HistoryUpdate::Flag::ClientSideMessages);
  2994. }
  2995. bool HistoryItem::needCheck() const {
  2996. return (out() && !isEmpty())
  2997. || (!isRegular() && _history->peer->isSelf());
  2998. }
  2999. bool HistoryItem::isService() const {
  3000. return Has<HistoryServiceData>();
  3001. }
  3002. bool HistoryItem::unread(not_null<Data::Thread*> thread) const {
  3003. // Messages from myself are always read, unless scheduled.
  3004. if (_history->peer->isSelf() && !isFromScheduled()) {
  3005. return false;
  3006. }
  3007. // All messages in converted chats are always read.
  3008. if (_history->peer->migrateTo()) {
  3009. return false;
  3010. }
  3011. if (isRegular()) {
  3012. if (!thread->isServerSideUnread(this)) {
  3013. return false;
  3014. }
  3015. if (out()) {
  3016. if (const auto user = _history->peer->asUser()) {
  3017. if (user->isBot() && !user->isSupport()) {
  3018. return false;
  3019. }
  3020. } else if (const auto channel = _history->peer->asChannel()) {
  3021. if (!channel->isMegagroup()) {
  3022. return false;
  3023. }
  3024. }
  3025. }
  3026. return true;
  3027. }
  3028. return out() || (_flags & MessageFlag::ClientSideUnread);
  3029. }
  3030. MsgId HistoryItem::replyToId() const {
  3031. if (const auto reply = Get<HistoryMessageReply>()) {
  3032. return reply->messageId();
  3033. }
  3034. return 0;
  3035. }
  3036. FullMsgId HistoryItem::replyToFullId() const {
  3037. if (const auto reply = Get<HistoryMessageReply>()) {
  3038. const auto peer = reply->externalPeerId();
  3039. return { peer ? peer : history()->peer->id, reply->messageId() };
  3040. }
  3041. return {};
  3042. }
  3043. MsgId HistoryItem::replyToTop() const {
  3044. if (const auto reply = Get<HistoryMessageReply>()) {
  3045. return reply->topMessageId();
  3046. } else if (const auto data = GetServiceDependentData()) {
  3047. return data->topId;
  3048. }
  3049. return 0;
  3050. }
  3051. MsgId HistoryItem::topicRootId() const {
  3052. if (const auto reply = Get<HistoryMessageReply>()
  3053. ; reply && reply->topicPost()) {
  3054. return reply->topMessageId();
  3055. } else if (const auto data = GetServiceDependentData()
  3056. ; data && data->topicPost && data->topId) {
  3057. return data->topId;
  3058. } else if (const auto info = Get<HistoryServiceTopicInfo>()) {
  3059. if (info->created()) {
  3060. return id;
  3061. }
  3062. }
  3063. return Data::ForumTopic::kGeneralId;
  3064. }
  3065. FullStoryId HistoryItem::replyToStory() const {
  3066. if (const auto reply = Get<HistoryMessageReply>()) {
  3067. if (reply->storyId()) {
  3068. const auto peerId = reply->externalPeerId()
  3069. ? reply->externalPeerId()
  3070. : _history->peer->id;
  3071. return { .peer = peerId, .story = reply->storyId() };
  3072. }
  3073. }
  3074. return {};
  3075. }
  3076. FullReplyTo HistoryItem::replyTo() const {
  3077. auto result = FullReplyTo{
  3078. .topicRootId = topicRootId(),
  3079. };
  3080. if (const auto reply = Get<HistoryMessageReply>()) {
  3081. const auto &fields = reply->fields();
  3082. const auto peer = fields.externalPeerId;
  3083. const auto replyToPeer = peer ? peer : _history->peer->id;
  3084. if (const auto id = fields.messageId) {
  3085. result.messageId = { replyToPeer, id };
  3086. result.quote = fields.quote;
  3087. result.quoteOffset = fields.quoteOffset;
  3088. }
  3089. if (const auto id = fields.storyId) {
  3090. result.storyId = { replyToPeer, id };
  3091. }
  3092. }
  3093. return result;
  3094. }
  3095. void HistoryItem::setText(const TextWithEntities &textWithEntities) {
  3096. for (const auto &entity : textWithEntities.entities) {
  3097. auto type = entity.type();
  3098. if (type == EntityType::Url
  3099. || type == EntityType::CustomUrl
  3100. || type == EntityType::Phone
  3101. || type == EntityType::Email) {
  3102. _flags |= MessageFlag::HasTextLinks;
  3103. break;
  3104. }
  3105. }
  3106. setTextValue((_media && _media->consumeMessageText(textWithEntities))
  3107. ? TextWithEntities()
  3108. : std::move(textWithEntities));
  3109. }
  3110. void HistoryItem::setTextValue(TextWithEntities text, bool force) {
  3111. if (const auto processId = Spellchecker::TryHighlightSyntax(text)) {
  3112. _flags |= MessageFlag::InHighlightProcess;
  3113. history()->owner().registerHighlightProcess(processId, this);
  3114. }
  3115. const auto had = !_text.empty();
  3116. _text = std::move(text);
  3117. RemoveComponents(HistoryMessageTranslation::Bit());
  3118. if (had || force) {
  3119. history()->owner().requestItemTextRefresh(this);
  3120. }
  3121. }
  3122. bool HistoryItem::inHighlightProcess() const {
  3123. return _flags & MessageFlag::InHighlightProcess;
  3124. }
  3125. void HistoryItem::highlightProcessDone() {
  3126. Expects(inHighlightProcess());
  3127. _flags &= ~MessageFlag::InHighlightProcess;
  3128. if (!_text.empty()) {
  3129. setTextValue(base::take(_text), true);
  3130. }
  3131. }
  3132. bool HistoryItem::showNotification() const {
  3133. const auto channel = _history->peer->asChannel();
  3134. if (channel && !channel->amIn()) {
  3135. return false;
  3136. }
  3137. return (out() || _history->peer->isSelf())
  3138. ? isFromScheduled()
  3139. : unread(notificationThread());
  3140. }
  3141. void HistoryItem::markClientSideAsRead() {
  3142. _flags &= ~MessageFlag::ClientSideUnread;
  3143. }
  3144. MessageGroupId HistoryItem::groupId() const {
  3145. return _groupId;
  3146. }
  3147. EffectId HistoryItem::effectId() const {
  3148. return _effectId;
  3149. }
  3150. QString HistoryItem::computeUnavailableReason() const {
  3151. if (const auto restrictions = Get<HistoryMessageRestrictions>()) {
  3152. _flags |= MessageFlag::HasRestrictions;
  3153. _history->owner().registerRestricted(this, restrictions->reasons);
  3154. return Data::UnavailableReason::Compute(
  3155. &history()->session(),
  3156. restrictions->reasons);
  3157. }
  3158. return QString();
  3159. }
  3160. bool HistoryItem::isMediaSensitive() const {
  3161. if (!(_flags & MessageFlag::SensitiveContent)
  3162. && !_history->peer->hasSensitiveContent()) {
  3163. return false;
  3164. }
  3165. _flags |= MessageFlag::HasRestrictions;
  3166. _history->owner().registerRestricted(this, u"sensitive"_q);
  3167. return !Data::UnavailableReason::IgnoreSensitiveMark(
  3168. &_history->session());
  3169. }
  3170. bool HistoryItem::hasPossibleRestrictions() const {
  3171. return _flags & MessageFlag::HasRestrictions;
  3172. }
  3173. bool HistoryItem::isEmpty() const {
  3174. return _text.empty()
  3175. && !_media
  3176. && (!Has<HistoryMessageFactcheck>()
  3177. || Get<HistoryMessageFactcheck>()->data.text.empty())
  3178. && !Has<HistoryMessageLogEntryOriginal>();
  3179. }
  3180. Data::SavedSublist *HistoryItem::savedSublist() const {
  3181. if (const auto saved = Get<HistoryMessageSaved>()) {
  3182. return saved->sublist;
  3183. } else if (_history->peer->isSelf()) {
  3184. const auto sublist = _history->owner().savedMessages().sublist(
  3185. _history->peer);
  3186. const auto that = const_cast<HistoryItem*>(this);
  3187. that->AddComponents(HistoryMessageSaved::Bit());
  3188. that->Get<HistoryMessageSaved>()->sublist = sublist;
  3189. return sublist;
  3190. }
  3191. return nullptr;
  3192. }
  3193. PeerData *HistoryItem::savedSublistPeer() const {
  3194. if (const auto sublist = savedSublist()) {
  3195. return sublist->peer();
  3196. }
  3197. return nullptr;
  3198. }
  3199. PeerData *HistoryItem::savedFromSender() const {
  3200. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  3201. return forwarded->savedFromSender;
  3202. }
  3203. return nullptr;
  3204. }
  3205. const HiddenSenderInfo *HistoryItem::savedFromHiddenSenderInfo() const {
  3206. if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  3207. return forwarded->savedFromHiddenSenderInfo.get();
  3208. }
  3209. return nullptr;
  3210. }
  3211. TextWithEntities HistoryItem::notificationText(
  3212. NotificationTextOptions options) const {
  3213. auto result = [&] {
  3214. if (_media && !isService()) {
  3215. return _media->notificationText();
  3216. } else if (!emptyText()) {
  3217. return _text;
  3218. }
  3219. return TextWithEntities();
  3220. }();
  3221. if (options.spoilerLoginCode
  3222. && !out()
  3223. && (history()->peer->isNotificationsUser()
  3224. || history()->peer->isVerifyCodes())) {
  3225. result = SpoilerLoginCode(std::move(result));
  3226. }
  3227. if (result.text.size() <= kNotificationTextLimit) {
  3228. return result;
  3229. }
  3230. return Ui::Text::Mid(result, 0, kNotificationTextLimit).append(
  3231. Ui::kQEllipsis);
  3232. }
  3233. ItemPreview HistoryItem::toPreview(ToPreviewOptions options) const {
  3234. if (isService()) {
  3235. const_cast<HistoryItem*>(this)->resolveDependent();
  3236. // Don't show small media for service messages (chat photo changed).
  3237. // Because larger version is shown exactly to the left of the small.
  3238. //auto media = _media ? _media->toPreview(options) : ItemPreview();
  3239. return {
  3240. .text = Ui::Text::Colorized(notificationText()),
  3241. //.images = std::move(media.images),
  3242. //.loadingContext = std::move(media.loadingContext),
  3243. };
  3244. }
  3245. auto result = [&]() -> ItemPreview {
  3246. if (_media) {
  3247. return _media->toPreview(options);
  3248. } else if (!emptyText()) {
  3249. return {
  3250. // wrap_rtl "adds" a newline in case text starts with quote.
  3251. // So we remove those by DialogsPreviewText call.
  3252. .text = st::wrap_rtl(Dialogs::Ui::DialogsPreviewText(
  3253. options.translated ? translatedText() : _text))
  3254. };
  3255. }
  3256. return {};
  3257. }();
  3258. if (options.spoilerLoginCode
  3259. && !out()
  3260. && (history()->peer->isNotificationsUser()
  3261. || history()->peer->isVerifyCodes())) {
  3262. result.text = SpoilerLoginCode(std::move(result.text));
  3263. }
  3264. const auto fromSender = [](not_null<PeerData*> sender) {
  3265. return sender->isSelf()
  3266. ? tr::lng_from_you(tr::now)
  3267. : sender->shortName();
  3268. };
  3269. const auto forwarded = Get<HistoryMessageForwarded>();
  3270. const auto forwardFromSender = forwarded
  3271. && showForwardsFromSender(forwarded);
  3272. result.icon = (forwarded
  3273. && (!forwardFromSender || forwarded->forwardOfForward()))
  3274. ? ItemPreview::Icon::ForwardedMessage
  3275. : replyToStory().valid()
  3276. ? ItemPreview::Icon::ReplyToStory
  3277. : ItemPreview::Icon::None;
  3278. const auto fromForwarded = [&]() -> std::optional<QString> {
  3279. if (forwarded) {
  3280. const auto sender = forwarded->forwardOfForward()
  3281. ? forwarded->savedFromSender
  3282. : forwarded->originalSender;
  3283. return sender
  3284. ? fromSender(sender)
  3285. : forwarded->savedFromHiddenSenderInfo
  3286. ? forwarded->savedFromHiddenSenderInfo->name
  3287. : forwarded->originalHiddenSenderInfo->name;
  3288. }
  3289. return {};
  3290. };
  3291. const auto sender = [&]() -> std::optional<QString> {
  3292. if (options.hideSender || isPostHidingAuthor() || isEmpty()) {
  3293. return {};
  3294. } else if (!_history->peer->isUser()) {
  3295. if (const auto from = displayFrom()) {
  3296. return fromSender(from);
  3297. }
  3298. return fromForwarded();
  3299. } else if (_history->peer->isSelf()
  3300. || _history->peer->isVerifyCodes()) {
  3301. return fromForwarded();
  3302. }
  3303. return {};
  3304. }();
  3305. if (!sender) {
  3306. return result;
  3307. }
  3308. const auto topic = options.ignoreTopic ? nullptr : this->topic();
  3309. return Dialogs::Ui::PreviewWithSender(
  3310. std::move(result),
  3311. *sender,
  3312. topic ? topic->titleWithIcon() : TextWithEntities());
  3313. }
  3314. TextWithEntities HistoryItem::inReplyText() const {
  3315. if (!isService()) {
  3316. return toPreview({
  3317. .hideSender = true,
  3318. .generateImages = false,
  3319. .translated = true,
  3320. }).text;
  3321. }
  3322. auto result = notificationText();
  3323. const auto &name = author()->name();
  3324. TextUtilities::Trim(result);
  3325. if (result.text.startsWith(name)) {
  3326. result = Ui::Text::Mid(result, name.size());
  3327. TextUtilities::Trim(result);
  3328. }
  3329. return Ui::Text::Colorized(result);
  3330. }
  3331. const std::vector<ClickHandlerPtr> &HistoryItem::customTextLinks() const {
  3332. static const auto kEmpty = std::vector<ClickHandlerPtr>();
  3333. const auto service = Get<HistoryServiceData>();
  3334. return service ? service->textLinks : kEmpty;
  3335. }
  3336. void HistoryItem::createComponents(CreateConfig &&config) {
  3337. uint64 mask = 0;
  3338. if (config.reply.messageId
  3339. || config.reply.externalSenderId
  3340. || !config.reply.externalSenderName.isEmpty()
  3341. || config.reply.storyId) {
  3342. mask |= HistoryMessageReply::Bit();
  3343. }
  3344. if (config.viaBotId) {
  3345. mask |= HistoryMessageVia::Bit();
  3346. }
  3347. if (config.viewsCount >= 0 || !config.replies.isNull) {
  3348. mask |= HistoryMessageViews::Bit();
  3349. }
  3350. if (!config.postAuthor.isEmpty() || config.viaBusinessBotId) {
  3351. mask |= HistoryMessageSigned::Bit();
  3352. } else if (_history->peer->isMegagroup() // Discussion posts signatures.
  3353. && config.savedFromPeer
  3354. && !config.originalPostAuthor.isEmpty()) {
  3355. const auto savedFrom = _history->owner().peerLoaded(
  3356. config.savedFromPeer);
  3357. if (savedFrom && savedFrom->isChannel()) {
  3358. mask |= HistoryMessageSigned::Bit();
  3359. }
  3360. } else if (!config.originalPostAuthor.isEmpty()
  3361. && (_history->peer->isSelf()
  3362. || _history->peer->isRepliesChat()
  3363. || _history->peer->isVerifyCodes())) {
  3364. mask |= HistoryMessageSigned::Bit();
  3365. }
  3366. if (config.editDate != TimeId(0)) {
  3367. mask |= HistoryMessageEdited::Bit();
  3368. }
  3369. if (config.originalDate != 0) {
  3370. mask |= HistoryMessageForwarded::Bit();
  3371. }
  3372. if (!config.markup.isTrivial()) {
  3373. mask |= HistoryMessageReplyMarkup::Bit();
  3374. } else if (config.inlineMarkup) {
  3375. mask |= HistoryMessageReplyMarkup::Bit();
  3376. }
  3377. if (_history->peer->isSelf()) {
  3378. mask |= HistoryMessageSaved::Bit();
  3379. }
  3380. if (!config.restrictions.empty()) {
  3381. if (config.restrictions.size() > 1
  3382. || !config.restrictions.front().sensitive()) {
  3383. mask |= HistoryMessageRestrictions::Bit();
  3384. }
  3385. }
  3386. UpdateComponents(mask);
  3387. if (const auto saved = Get<HistoryMessageSaved>()) {
  3388. if (!config.savedSublistPeer) {
  3389. if (config.savedFromPeer) {
  3390. config.savedSublistPeer = config.savedFromPeer;
  3391. } else if (config.originalSenderId) {
  3392. config.savedSublistPeer = config.originalSenderId;
  3393. } else if (!config.originalSenderName.isEmpty()) {
  3394. config.savedSublistPeer = PeerData::kSavedHiddenAuthorId;
  3395. } else {
  3396. config.savedSublistPeer = _history->session().userPeerId();
  3397. }
  3398. }
  3399. const auto peer = _history->owner().peer(config.savedSublistPeer);
  3400. saved->sublist = _history->owner().savedMessages().sublist(peer);
  3401. }
  3402. if (const auto reply = Get<HistoryMessageReply>()) {
  3403. reply->set(std::move(config.reply));
  3404. reply->updateData(this);
  3405. }
  3406. if (const auto via = Get<HistoryMessageVia>()) {
  3407. via->create(&_history->owner(), config.viaBotId);
  3408. }
  3409. if (const auto views = Get<HistoryMessageViews>()) {
  3410. changeViewsCount(config.viewsCount);
  3411. if (config.replies.isNull
  3412. && isSending()
  3413. && config.markup.isNull()) {
  3414. if (const auto broadcast = _history->peer->asBroadcast()) {
  3415. if (const auto linked = broadcast->linkedChat()) {
  3416. config.replies.isNull = false;
  3417. config.replies.channelId = peerToChannel(linked->id);
  3418. }
  3419. }
  3420. }
  3421. setForwardsCount(config.forwardsCount);
  3422. setReplies(std::move(config.replies));
  3423. }
  3424. if (const auto edited = Get<HistoryMessageEdited>()) {
  3425. edited->date = config.editDate;
  3426. }
  3427. if (const auto msgsigned = Get<HistoryMessageSigned>()) {
  3428. if (config.viaBusinessBotId) {
  3429. msgsigned->viaBusinessBot = _history->owner().user(
  3430. config.viaBusinessBotId);
  3431. msgsigned->author = msgsigned->viaBusinessBot->name();
  3432. } else {
  3433. msgsigned->author = config.postAuthor.isEmpty()
  3434. ? config.originalPostAuthor
  3435. : config.postAuthor;
  3436. msgsigned->isAnonymousRank = !isDiscussionPost()
  3437. && author()->isMegagroup();
  3438. }
  3439. }
  3440. setupForwardedComponent(config);
  3441. if (const auto markup = Get<HistoryMessageReplyMarkup>()) {
  3442. if (!config.markup.isTrivial()) {
  3443. markup->updateData(std::move(config.markup));
  3444. } else if (config.inlineMarkup) {
  3445. markup->createForwarded(*config.inlineMarkup);
  3446. }
  3447. if (markup->data.flags & ReplyMarkupFlag::HasSwitchInlineButton) {
  3448. _flags |= MessageFlag::HasSwitchInlineButton;
  3449. }
  3450. } else if (!config.markup.isNull()) {
  3451. _flags |= MessageFlag::HasReplyMarkup;
  3452. } else {
  3453. _flags &= ~MessageFlag::HasReplyMarkup;
  3454. }
  3455. if (const auto restrictions = Get<HistoryMessageRestrictions>()) {
  3456. restrictions->reasons = std::move(config.restrictions);
  3457. const auto i = ranges::find(
  3458. restrictions->reasons,
  3459. true,
  3460. &Data::UnavailableReason::sensitive);
  3461. if (i != end(restrictions->reasons)) {
  3462. restrictions->reasons.erase(i);
  3463. flagSensitiveContent();
  3464. }
  3465. } else if (!config.restrictions.empty()) {
  3466. flagSensitiveContent();
  3467. }
  3468. if (out() && isSending()) {
  3469. if (const auto channel = _history->peer->asMegagroup()) {
  3470. _boostsApplied = channel->mgInfo->boostsApplied;
  3471. }
  3472. }
  3473. }
  3474. void HistoryItem::flagSensitiveContent() {
  3475. _flags |= MessageFlag::SensitiveContent;
  3476. _history->session().api().sensitiveContent().preload();
  3477. }
  3478. bool HistoryItem::checkRepliesPts(
  3479. const HistoryMessageRepliesData &data) const {
  3480. const auto channel = _history->peer->asChannel();
  3481. const auto pts = channel
  3482. ? channel->pts()
  3483. : _history->session().updates().pts();
  3484. return (data.pts >= pts);
  3485. }
  3486. void HistoryItem::setupForwardedComponent(const CreateConfig &config) {
  3487. const auto forwarded = Get<HistoryMessageForwarded>();
  3488. if (!forwarded) {
  3489. return;
  3490. }
  3491. forwarded->originalDate = config.originalDate;
  3492. const auto originalSender = config.originalSenderId
  3493. ? config.originalSenderId
  3494. : !config.originalSenderName.isEmpty()
  3495. ? PeerId()
  3496. : from()->id;
  3497. forwarded->originalSender = originalSender
  3498. ? _history->owner().peer(originalSender).get()
  3499. : nullptr;
  3500. if (!forwarded->originalSender) {
  3501. forwarded->originalHiddenSenderInfo
  3502. = std::make_unique<HiddenSenderInfo>(
  3503. config.originalSenderName,
  3504. config.imported);
  3505. }
  3506. forwarded->originalId = config.originalId;
  3507. forwarded->originalPostAuthor = config.originalPostAuthor;
  3508. forwarded->psaType = config.forwardPsaType;
  3509. forwarded->savedFromPeer = _history->owner().peerLoaded(
  3510. config.savedFromPeer);
  3511. forwarded->savedFromMsgId = config.savedFromMsgId;
  3512. forwarded->savedFromSender = _history->owner().peerLoaded(
  3513. config.savedFromSenderId);
  3514. if (forwarded->savedFromPeer
  3515. && !forwarded->savedFromPeer->isFullLoaded()
  3516. && forwarded->savedFromPeer->isChannel()) {
  3517. _history->session().api().requestFullPeer(forwarded->savedFromPeer);
  3518. } else if (config.savedFromPeer) {
  3519. _history->session().api().requestFullPeer(
  3520. _history->owner().peer(config.savedFromPeer));
  3521. }
  3522. forwarded->savedFromOutgoing = config.savedFromOutgoing;
  3523. if (!forwarded->savedFromSender
  3524. && !config.savedFromSenderName.isEmpty()) {
  3525. forwarded->savedFromHiddenSenderInfo
  3526. = std::make_unique<HiddenSenderInfo>(config.savedFromSenderName, false);
  3527. }
  3528. forwarded->imported = config.imported;
  3529. }
  3530. void HistoryItem::applyInitialEffectWatched() {
  3531. if (!effectId()) {
  3532. return;
  3533. } else if (out()) {
  3534. // If this message came from the server, not generated on send.
  3535. _flags |= MessageFlag::EffectWatched;
  3536. } else if (_history->inboxReadTillId() && !unread(_history)) {
  3537. _flags |= MessageFlag::EffectWatched;
  3538. }
  3539. }
  3540. void HistoryItem::applyEffectWatchedOnUnreadKnown() {
  3541. if (effectId() && !out() && !unread(_history)) {
  3542. _flags |= MessageFlag::EffectWatched;
  3543. }
  3544. }
  3545. bool HistoryItem::generateLocalEntitiesByReply() const {
  3546. using namespace HistoryView;
  3547. if (!_media) {
  3548. return true;
  3549. } else if (const auto document = _media->document()) {
  3550. return !DurationForTimestampLinks(document);
  3551. } else if (const auto webpage = _media->webpage()) {
  3552. return (webpage->type != WebPageType::Video)
  3553. && !DurationForTimestampLinks(webpage);
  3554. }
  3555. return true;
  3556. }
  3557. TextWithEntities HistoryItem::withLocalEntities(
  3558. const TextWithEntities &textWithEntities) const {
  3559. using namespace HistoryView;
  3560. if (!generateLocalEntitiesByReply()) {
  3561. if (!_media) {
  3562. } else if (const auto document = _media->document()) {
  3563. if (const auto duration = DurationForTimestampLinks(document)) {
  3564. return AddTimestampLinks(
  3565. textWithEntities,
  3566. duration,
  3567. TimestampLinkBase(document, fullId()));
  3568. }
  3569. } else if (const auto webpage = _media->webpage()) {
  3570. if (const auto duration = DurationForTimestampLinks(webpage)) {
  3571. return AddTimestampLinks(
  3572. textWithEntities,
  3573. duration,
  3574. TimestampLinkBase(webpage, fullId()));
  3575. }
  3576. }
  3577. return textWithEntities;
  3578. }
  3579. if (const auto reply = Get<HistoryMessageReply>()) {
  3580. const auto document = reply->replyToDocumentId
  3581. ? _history->owner().document(reply->replyToDocumentId).get()
  3582. : nullptr;
  3583. const auto webpage = reply->replyToWebPageId
  3584. ? _history->owner().webpage(reply->replyToWebPageId).get()
  3585. : nullptr;
  3586. if (document) {
  3587. if (const auto duration = DurationForTimestampLinks(document)) {
  3588. const auto context = reply->resolvedMessage->fullId();
  3589. return AddTimestampLinks(
  3590. textWithEntities,
  3591. duration,
  3592. TimestampLinkBase(document, context));
  3593. }
  3594. } else if (webpage) {
  3595. if (const auto duration = DurationForTimestampLinks(webpage)) {
  3596. const auto context = reply->resolvedMessage->fullId();
  3597. return AddTimestampLinks(
  3598. textWithEntities,
  3599. duration,
  3600. TimestampLinkBase(webpage, context));
  3601. }
  3602. }
  3603. }
  3604. return textWithEntities;
  3605. }
  3606. void HistoryItem::createComponentsHelper(HistoryItemCommonFields &&fields) {
  3607. const auto &replyTo = fields.replyTo;
  3608. auto config = CreateConfig();
  3609. config.viaBotId = fields.viaBotId;
  3610. if (fields.flags & MessageFlag::HasReplyInfo) {
  3611. config.reply.messageId = replyTo.messageId.msg;
  3612. config.reply.storyId = replyTo.storyId.story;
  3613. config.reply.externalPeerId = replyTo.storyId
  3614. ? replyTo.storyId.peer
  3615. : (replyTo.messageId && replyTo.messageId.peer
  3616. != history()->peer->id)
  3617. ? replyTo.messageId.peer
  3618. : PeerId();
  3619. const auto to = LookupReplyTo(_history, replyTo.messageId);
  3620. const auto replyToTop = replyTo.topicRootId
  3621. ? replyTo.topicRootId
  3622. : LookupReplyToTop(_history, to);
  3623. config.reply.topMessageId = replyToTop
  3624. ? replyToTop
  3625. : (replyTo.messageId.peer == history()->peer->id)
  3626. ? replyTo.messageId.msg
  3627. : MsgId();
  3628. const auto forum = _history->asForum();
  3629. const auto topic = forum
  3630. ? forum->topicFor(replyTo.topicRootId)
  3631. : nullptr;
  3632. if (!config.reply.externalPeerId
  3633. && topic
  3634. && to
  3635. && topic->rootId() != to->topicRootId()) {
  3636. config.reply.externalPeerId = replyTo.messageId.peer;
  3637. }
  3638. const auto topicPost = config.reply.externalPeerId
  3639. ? (replyTo.topicRootId
  3640. && (replyTo.topicRootId != Data::ForumTopic::kGeneralId))
  3641. : (topic
  3642. || LookupReplyIsTopicPost(to)
  3643. || (to && to->Has<HistoryServiceTopicInfo>())
  3644. || (forum && forum->creating(config.reply.topMessageId)));
  3645. config.reply.topicPost = topicPost ? 1 : 0;
  3646. config.reply.manualQuote = replyTo.quote.empty() ? 0 : 1;
  3647. config.reply.quoteOffset = replyTo.quoteOffset;
  3648. config.reply.quote = std::move(replyTo.quote);
  3649. }
  3650. config.markup = std::move(fields.markup);
  3651. if (fields.flags & MessageFlag::HasPostAuthor) {
  3652. config.postAuthor = fields.postAuthor;
  3653. }
  3654. if (fields.flags & MessageFlag::HasViews) {
  3655. config.viewsCount = 1;
  3656. }
  3657. createComponents(std::move(config));
  3658. }
  3659. void HistoryItem::setReactions(const MTPMessageReactions *reactions) {
  3660. Expects(!_reactions);
  3661. if (changeReactions(reactions) && _reactions->hasUnread()) {
  3662. _flags |= MessageFlag::HasUnreadReaction;
  3663. }
  3664. }
  3665. void HistoryItem::updateReactions(const MTPMessageReactions *reactions) {
  3666. const auto wasRecentUsers = LookupRecentUnreadReactedUsers(this);
  3667. const auto hadUnread = hasUnreadReaction();
  3668. const auto changed = changeReactions(reactions);
  3669. if (!changed) {
  3670. return;
  3671. }
  3672. const auto hasUnread = _reactions && _reactions->hasUnread();
  3673. if (hasUnread && !hadUnread) {
  3674. _flags |= MessageFlag::HasUnreadReaction;
  3675. addToUnreadThings(HistoryUnreadThings::AddType::New);
  3676. } else if (!hasUnread && hadUnread) {
  3677. markReactionsRead();
  3678. }
  3679. CheckReactionNotificationSchedule(this, wasRecentUsers);
  3680. _history->owner().notifyItemDataChange(this);
  3681. }
  3682. bool HistoryItem::changeReactions(const MTPMessageReactions *reactions) {
  3683. if (reactions || _reactionsLastRefreshed) {
  3684. _reactionsLastRefreshed = crl::now();
  3685. }
  3686. const auto changeToEmpty = [&] {
  3687. if (!_reactions) {
  3688. return false;
  3689. } else if (!_reactions->localPaidData()) {
  3690. _reactions = nullptr;
  3691. return true;
  3692. }
  3693. return _reactions->clearCloudData();
  3694. };
  3695. if (!reactions) {
  3696. _flags &= ~MessageFlag::CanViewReactions;
  3697. if (_history->peer->isSelf()) {
  3698. _flags |= MessageFlag::ReactionsAreTags;
  3699. }
  3700. return changeToEmpty();
  3701. }
  3702. const auto &data = reactions->data();
  3703. const auto empty = data.vresults().v.isEmpty();
  3704. if (data.is_reactions_as_tags()
  3705. || (empty && _history->peer->isSelf())) {
  3706. _flags |= MessageFlag::ReactionsAreTags;
  3707. } else {
  3708. _flags &= ~MessageFlag::ReactionsAreTags;
  3709. }
  3710. if (data.is_can_see_list()) {
  3711. _flags |= MessageFlag::CanViewReactions;
  3712. } else {
  3713. _flags &= ~MessageFlag::CanViewReactions;
  3714. }
  3715. if (empty) {
  3716. return changeToEmpty();
  3717. } else if (!_reactions) {
  3718. _reactions = std::make_unique<Data::MessageReactions>(this);
  3719. }
  3720. const auto min = data.is_min();
  3721. const auto &list = data.vresults().v;
  3722. const auto &recent = data.vrecent_reactions().value_or_empty();
  3723. const auto &top = data.vtop_reactors().value_or_empty();
  3724. if (min && hasUnreadReaction()) {
  3725. // We can't update reactions from min if we have unread.
  3726. if (_reactions->checkIfChanged(list, recent, min)) {
  3727. updateReactionsUnknown();
  3728. }
  3729. return false;
  3730. }
  3731. return _reactions->change(list, recent, top, min);
  3732. }
  3733. void HistoryItem::applyTTL(const MTPDmessage &data) {
  3734. if (const auto period = data.vttl_period()) {
  3735. if (period->v > 0) {
  3736. applyTTL(data.vdate().v + period->v);
  3737. }
  3738. }
  3739. }
  3740. void HistoryItem::applyTTL(const MTPDmessageService &data) {
  3741. if (const auto period = data.vttl_period()) {
  3742. if (period->v > 0) {
  3743. applyTTL(data.vdate().v + period->v);
  3744. }
  3745. }
  3746. }
  3747. void HistoryItem::createComponents(const MTPDmessage &data) {
  3748. auto config = CreateConfig();
  3749. config.savedSublistPeer = data.vsaved_peer_id()
  3750. ? peerFromMTP(*data.vsaved_peer_id())
  3751. : PeerId();
  3752. if (const auto forwarded = data.vfwd_from()) {
  3753. forwarded->match([&](const MTPDmessageFwdHeader &data) {
  3754. FillForwardedInfo(config, data);
  3755. });
  3756. }
  3757. if (const auto reply = data.vreply_to()) {
  3758. config.reply = ReplyFieldsFromMTP(this, *reply);
  3759. }
  3760. config.viaBotId = data.vvia_bot_id().value_or_empty();
  3761. config.viaBusinessBotId = data.vvia_business_bot_id().value_or_empty();
  3762. config.viewsCount = data.vviews().value_or(-1);
  3763. config.forwardsCount = data.vforwards().value_or(-1);
  3764. config.replies = isScheduled()
  3765. ? HistoryMessageRepliesData()
  3766. : HistoryMessageRepliesData(data.vreplies());
  3767. config.markup = HistoryMessageMarkupData(data.vreply_markup());
  3768. config.editDate = data.vedit_date().value_or_empty();
  3769. config.postAuthor = qs(data.vpost_author().value_or_empty());
  3770. config.restrictions = Data::UnavailableReason::Extract(
  3771. data.vrestriction_reason());
  3772. createComponents(std::move(config));
  3773. }
  3774. void HistoryItem::refreshMedia(const MTPMessageMedia *media) {
  3775. const auto was = (_media != nullptr);
  3776. if (const auto invoice = was ? _media->invoice() : nullptr) {
  3777. if (HasExtendedMedia(*invoice)) {
  3778. return;
  3779. }
  3780. }
  3781. _media = nullptr;
  3782. if (media) {
  3783. setMedia(*media);
  3784. }
  3785. if (was || _media) {
  3786. if (const auto views = Get<HistoryMessageViews>()) {
  3787. refreshRepliesText(views);
  3788. }
  3789. }
  3790. }
  3791. void HistoryItem::refreshSentMedia(const MTPMessageMedia *media) {
  3792. const auto wasGrouped = history()->owner().groups().isGrouped(this);
  3793. refreshMedia(media);
  3794. if (wasGrouped) {
  3795. history()->owner().groups().refreshMessage(this);
  3796. } else {
  3797. history()->owner().requestItemViewRefresh(this);
  3798. }
  3799. }
  3800. void HistoryItem::createServiceFromMtp(const MTPDmessage &message) {
  3801. AddComponents(HistoryServiceData::Bit());
  3802. const auto unread = message.is_media_unread();
  3803. const auto media = message.vmedia();
  3804. Assert(media != nullptr);
  3805. media->match([&](const MTPDmessageMediaPhoto &data) {
  3806. if (unread) {
  3807. const auto ttl = data.vttl_seconds();
  3808. Assert(ttl != nullptr);
  3809. setSelfDestruct(HistoryServiceSelfDestruct::Type::Photo, *ttl);
  3810. if (out()) {
  3811. setServiceText({
  3812. tr::lng_ttl_photo_sent(tr::now, Ui::Text::WithEntities)
  3813. });
  3814. } else {
  3815. auto result = PreparedServiceText();
  3816. result.links.push_back(fromLink());
  3817. result.text = tr::lng_ttl_photo_received(
  3818. tr::now,
  3819. lt_from,
  3820. fromLinkText(), // Link 1.
  3821. Ui::Text::WithEntities);
  3822. setServiceText(std::move(result));
  3823. }
  3824. } else {
  3825. setServiceText({
  3826. tr::lng_ttl_photo_expired(tr::now, Ui::Text::WithEntities)
  3827. });
  3828. }
  3829. }, [&](const MTPDmessageMediaDocument &data) {
  3830. if (unread) {
  3831. const auto ttl = data.vttl_seconds();
  3832. Assert(ttl != nullptr);
  3833. if (data.is_video()) {
  3834. setSelfDestruct(
  3835. HistoryServiceSelfDestruct::Type::Video,
  3836. *ttl);
  3837. if (out()) {
  3838. setServiceText({
  3839. tr::lng_ttl_video_sent(
  3840. tr::now,
  3841. Ui::Text::WithEntities)
  3842. });
  3843. } else {
  3844. auto result = PreparedServiceText();
  3845. result.links.push_back(fromLink());
  3846. result.text = tr::lng_ttl_video_received(
  3847. tr::now,
  3848. lt_from,
  3849. fromLinkText(), // Link 1.
  3850. Ui::Text::WithEntities);
  3851. setServiceText(std::move(result));
  3852. }
  3853. } else if (out()) {
  3854. auto text = (data.is_voice()
  3855. ? tr::lng_ttl_voice_sent
  3856. : data.is_round()
  3857. ? tr::lng_ttl_round_sent
  3858. : tr::lng_message_empty)(tr::now, Ui::Text::WithEntities);
  3859. setServiceText({ std::move(text) });
  3860. }
  3861. } else {
  3862. auto text = (data.is_video()
  3863. ? tr::lng_ttl_video_expired
  3864. : data.is_voice()
  3865. ? tr::lng_ttl_voice_expired
  3866. : data.is_round()
  3867. ? tr::lng_ttl_round_expired
  3868. : tr::lng_message_empty)(tr::now, Ui::Text::WithEntities);
  3869. setServiceText({ std::move(text) });
  3870. }
  3871. }, [&](const MTPDmessageMediaStory &data) {
  3872. setServiceText(prepareStoryMentionText());
  3873. }, [](const auto &) {
  3874. Unexpected("Media type in HistoryItem::createServiceFromMtp()");
  3875. });
  3876. if (const auto reactions = message.vreactions()) {
  3877. updateReactions(reactions);
  3878. }
  3879. }
  3880. void HistoryItem::createServiceFromMtp(const MTPDmessageService &message) {
  3881. AddComponents(HistoryServiceData::Bit());
  3882. const auto &action = message.vaction();
  3883. const auto type = action.type();
  3884. if (type == mtpc_messageActionPinMessage) {
  3885. UpdateComponents(HistoryServicePinned::Bit());
  3886. } else if (type == mtpc_messageActionTopicCreate
  3887. || type == mtpc_messageActionTopicEdit) {
  3888. UpdateComponents(HistoryServiceTopicInfo::Bit());
  3889. const auto info = Get<HistoryServiceTopicInfo>();
  3890. info->topicPost = true;
  3891. if (type == mtpc_messageActionTopicEdit) {
  3892. const auto &data = action.c_messageActionTopicEdit();
  3893. if (const auto title = data.vtitle()) {
  3894. info->title = qs(*title);
  3895. info->renamed = true;
  3896. }
  3897. if (const auto icon = data.vicon_emoji_id()) {
  3898. info->iconId = icon->v;
  3899. info->reiconed = true;
  3900. }
  3901. if (const auto closed = data.vclosed()) {
  3902. info->closed = mtpIsTrue(*closed);
  3903. info->reopened = !info->closed;
  3904. }
  3905. if (const auto hidden = data.vhidden()) {
  3906. info->hidden = mtpIsTrue(*hidden);
  3907. info->unhidden = !info->hidden;
  3908. }
  3909. } else {
  3910. const auto &data = action.c_messageActionTopicCreate();
  3911. info->title = qs(data.vtitle());
  3912. info->iconId = data.vicon_emoji_id().value_or_empty();
  3913. }
  3914. } else if (type == mtpc_messageActionSetChatTheme) {
  3915. setupChatThemeChange();
  3916. } else if (type == mtpc_messageActionSetMessagesTTL) {
  3917. setupTTLChange();
  3918. } else if (type == mtpc_messageActionGameScore) {
  3919. const auto &data = action.c_messageActionGameScore();
  3920. UpdateComponents(HistoryServiceGameScore::Bit());
  3921. Get<HistoryServiceGameScore>()->score = data.vscore().v;
  3922. } else if (type == mtpc_messageActionPaymentSent) {
  3923. const auto &data = action.c_messageActionPaymentSent();
  3924. UpdateComponents(HistoryServicePayment::Bit());
  3925. const auto amount = data.vtotal_amount().v;
  3926. const auto currency = qs(data.vcurrency());
  3927. const auto payment = Get<HistoryServicePayment>();
  3928. const auto id = fullId();
  3929. const auto owner = &_history->owner();
  3930. payment->slug = data.vinvoice_slug().value_or_empty();
  3931. payment->recurringInit = data.is_recurring_init();
  3932. payment->recurringUsed = data.is_recurring_used();
  3933. payment->isCreditsCurrency = (currency == Ui::kCreditsCurrency);
  3934. payment->amount = AmountAndStarCurrency(
  3935. &_history->session(),
  3936. amount,
  3937. currency);
  3938. payment->invoiceLink = std::make_shared<LambdaClickHandler>([=](
  3939. ClickContext context) {
  3940. using namespace Payments;
  3941. const auto my = context.other.value<ClickHandlerContext>();
  3942. const auto weak = my.sessionWindow;
  3943. if (const auto item = owner->message(id)) {
  3944. CheckoutProcess::Start(
  3945. item,
  3946. Mode::Receipt,
  3947. crl::guard(weak, [=](auto) { weak->window().activate(); }),
  3948. Payments::ProcessNonPanelPaymentFormFactory(
  3949. weak.get(),
  3950. item));
  3951. }
  3952. });
  3953. } else if (type == mtpc_messageActionGroupCall
  3954. || type == mtpc_messageActionGroupCallScheduled) {
  3955. const auto started = (type == mtpc_messageActionGroupCall);
  3956. const auto &callData = started
  3957. ? action.c_messageActionGroupCall().vcall()
  3958. : action.c_messageActionGroupCallScheduled().vcall();
  3959. const auto duration = started
  3960. ? action.c_messageActionGroupCall().vduration()
  3961. : tl::conditional<MTPint>();
  3962. if (duration) {
  3963. RemoveComponents(HistoryServiceOngoingCall::Bit());
  3964. } else {
  3965. UpdateComponents(HistoryServiceOngoingCall::Bit());
  3966. const auto call = Get<HistoryServiceOngoingCall>();
  3967. call->id = CallIdFromInput(callData);
  3968. call->link = GroupCallClickHandler(_history->peer, call->id);
  3969. }
  3970. } else if (type == mtpc_messageActionInviteToGroupCall) {
  3971. const auto &data = action.c_messageActionInviteToGroupCall();
  3972. const auto id = CallIdFromInput(data.vcall());
  3973. const auto peer = _history->peer;
  3974. const auto has = PeerHasThisCall(peer, id);
  3975. auto hasLink = !has.has_value()
  3976. ? PeerHasThisCallValue(peer, id)
  3977. : (*has)
  3978. ? PeerHasThisCallValue(
  3979. peer,
  3980. id) | rpl::skip(1) | rpl::type_erased()
  3981. : rpl::producer<bool>();
  3982. if (!hasLink) {
  3983. RemoveComponents(HistoryServiceOngoingCall::Bit());
  3984. } else {
  3985. UpdateComponents(HistoryServiceOngoingCall::Bit());
  3986. const auto call = Get<HistoryServiceOngoingCall>();
  3987. call->id = id;
  3988. call->lifetime.destroy();
  3989. const auto users = data.vusers().v;
  3990. std::move(hasLink) | rpl::start_with_next([=](bool has) {
  3991. updateServiceText(
  3992. prepareInvitedToCallText(
  3993. ParseInvitedToCallUsers(this, users),
  3994. has ? id : 0));
  3995. if (!has) {
  3996. RemoveComponents(HistoryServiceOngoingCall::Bit());
  3997. }
  3998. }, call->lifetime);
  3999. }
  4000. } else if (type == mtpc_messageActionSetChatWallPaper) {
  4001. if (action.c_messageActionSetChatWallPaper().is_same()) {
  4002. UpdateComponents(HistoryServiceSameBackground::Bit());
  4003. } else {
  4004. RemoveComponents(HistoryServiceSameBackground::Bit());
  4005. }
  4006. } else if (type == mtpc_messageActionGiveawayResults) {
  4007. UpdateComponents(HistoryServiceGiveawayResults::Bit());
  4008. } else if (type == mtpc_messageActionPaymentRefunded) {
  4009. const auto &data = action.c_messageActionPaymentRefunded();
  4010. UpdateComponents(HistoryServicePaymentRefund::Bit());
  4011. const auto refund = Get<HistoryServicePaymentRefund>();
  4012. refund->peer = _history->owner().peer(peerFromMTP(data.vpeer()));
  4013. refund->amount = data.vtotal_amount().v;
  4014. refund->currency = qs(data.vcurrency());
  4015. refund->transactionId = qs(data.vcharge().data().vid());
  4016. const auto id = fullId();
  4017. refund->link = std::make_shared<LambdaClickHandler>([=](
  4018. ClickContext context) {
  4019. const auto my = context.other.value<ClickHandlerContext>();
  4020. if (const auto window = my.sessionWindow.get()) {
  4021. Settings::ShowRefundInfoBox(window, id);
  4022. }
  4023. });
  4024. }
  4025. if (const auto replyTo = message.vreply_to()) {
  4026. replyTo->match([&](const MTPDmessageReplyHeader &data) {
  4027. const auto peerId = data.vreply_to_peer_id()
  4028. ? peerFromMTP(*data.vreply_to_peer_id())
  4029. : _history->peer->id;
  4030. if (const auto dependent = GetServiceDependentData()) {
  4031. const auto id = data.vreply_to_msg_id().value_or_empty();
  4032. if (id) {
  4033. dependent->peerId = (peerId != _history->peer->id)
  4034. ? peerId
  4035. : 0;
  4036. dependent->msgId = id;
  4037. dependent->topId = data.vreply_to_top_id().value_or(id);
  4038. dependent->topicPost = data.is_forum_topic()
  4039. || Has<HistoryServiceTopicInfo>();
  4040. updateServiceDependent();
  4041. }
  4042. }
  4043. }, [](const MTPDmessageReplyStoryHeader &data) {
  4044. });
  4045. }
  4046. setServiceMessageByAction(action);
  4047. }
  4048. void HistoryItem::setMedia(const MTPMessageMedia &media) {
  4049. _media = CreateMedia(this, media);
  4050. checkStoryForwardInfo();
  4051. checkBuyButton();
  4052. }
  4053. void HistoryItem::checkStoryForwardInfo() {
  4054. if (const auto storyId = _media ? _media->storyId() : FullStoryId()) {
  4055. const auto adding = !Has<HistoryMessageForwarded>();
  4056. if (adding) {
  4057. AddComponents(HistoryMessageForwarded::Bit());
  4058. }
  4059. const auto forwarded = Get<HistoryMessageForwarded>();
  4060. if (forwarded->story || adding) {
  4061. const auto peer = history()->owner().peer(storyId.peer);
  4062. forwarded->story = true;
  4063. forwarded->originalSender = peer;
  4064. }
  4065. } else if (const auto forwarded = Get<HistoryMessageForwarded>()) {
  4066. if (forwarded->story) {
  4067. RemoveComponents(HistoryMessageForwarded::Bit());
  4068. }
  4069. }
  4070. }
  4071. void HistoryItem::applyServiceDateEdition(const MTPDmessageService &data) {
  4072. const auto date = data.vdate().v;
  4073. if (_date == date) {
  4074. return;
  4075. }
  4076. _date = date;
  4077. }
  4078. void HistoryItem::setServiceMessageByAction(const MTPmessageAction &action) {
  4079. auto prepareChatAddUserText = [this](const MTPDmessageActionChatAddUser &action) {
  4080. auto result = PreparedServiceText();
  4081. auto &users = action.vusers().v;
  4082. if (users.size() == 1) {
  4083. auto u = _history->owner().user(users[0].v);
  4084. if (u == _from) {
  4085. result.links.push_back(fromLink());
  4086. result.text = tr::lng_action_user_joined(
  4087. tr::now,
  4088. lt_from,
  4089. fromLinkText(), // Link 1.
  4090. Ui::Text::WithEntities);
  4091. } else {
  4092. result.links.push_back(fromLink());
  4093. result.links.push_back(u->createOpenLink());
  4094. result.text = tr::lng_action_add_user(
  4095. tr::now,
  4096. lt_from,
  4097. fromLinkText(), // Link 1.
  4098. lt_user,
  4099. Ui::Text::Link(u->name(), 2), // Link 2.
  4100. Ui::Text::WithEntities);
  4101. }
  4102. } else if (users.isEmpty()) {
  4103. result.links.push_back(fromLink());
  4104. result.text = tr::lng_action_add_user(
  4105. tr::now,
  4106. lt_from,
  4107. fromLinkText(), // Link 1.
  4108. lt_user,
  4109. { .text = u"somebody"_q },
  4110. Ui::Text::WithEntities);
  4111. } else {
  4112. result.links.push_back(fromLink());
  4113. for (auto i = 0, l = int(users.size()); i != l; ++i) {
  4114. auto user = _history->owner().user(users[i].v);
  4115. result.links.push_back(user->createOpenLink());
  4116. auto linkText = Ui::Text::Link(user->name(), 2 + i);
  4117. if (i == 0) {
  4118. result.text = linkText;
  4119. } else if (i + 1 == l) {
  4120. result.text = tr::lng_action_add_users_and_last(
  4121. tr::now,
  4122. lt_accumulated,
  4123. result.text,
  4124. lt_user,
  4125. linkText,
  4126. Ui::Text::WithEntities);
  4127. } else {
  4128. result.text = tr::lng_action_add_users_and_one(
  4129. tr::now,
  4130. lt_accumulated,
  4131. result.text,
  4132. lt_user,
  4133. linkText,
  4134. Ui::Text::WithEntities);
  4135. }
  4136. }
  4137. result.text = tr::lng_action_add_users_many(
  4138. tr::now,
  4139. lt_from,
  4140. fromLinkText(), // Link 1.
  4141. lt_users,
  4142. result.text,
  4143. Ui::Text::WithEntities);
  4144. }
  4145. return result;
  4146. };
  4147. auto prepareChatJoinedByLink = [this](const MTPDmessageActionChatJoinedByLink &action) {
  4148. auto result = PreparedServiceText();
  4149. result.links.push_back(fromLink());
  4150. result.text = tr::lng_action_user_joined_by_link(
  4151. tr::now,
  4152. lt_from,
  4153. fromLinkText(), // Link 1.
  4154. Ui::Text::WithEntities);
  4155. return result;
  4156. };
  4157. auto prepareChatCreate = [this](const MTPDmessageActionChatCreate &action) {
  4158. auto result = PreparedServiceText();
  4159. result.links.push_back(fromLink());
  4160. result.text = tr::lng_action_created_chat(
  4161. tr::now,
  4162. lt_from,
  4163. fromLinkText(), // Link 1.
  4164. lt_title,
  4165. { .text = qs(action.vtitle()) },
  4166. Ui::Text::WithEntities);
  4167. return result;
  4168. };
  4169. auto prepareChannelCreate = [this](const MTPDmessageActionChannelCreate &action) {
  4170. auto result = PreparedServiceText();
  4171. if (isPost()) {
  4172. result.text = tr::lng_action_created_channel(
  4173. tr::now,
  4174. Ui::Text::WithEntities);
  4175. } else {
  4176. result.links.push_back(fromLink());
  4177. result.text = tr::lng_action_created_chat(
  4178. tr::now,
  4179. lt_from,
  4180. fromLinkText(), // Link 1.
  4181. lt_title,
  4182. { .text = qs(action.vtitle()) },
  4183. Ui::Text::WithEntities);
  4184. }
  4185. return result;
  4186. };
  4187. auto prepareChatDeletePhoto = [&](const MTPDmessageActionChatDeletePhoto &action) {
  4188. auto result = PreparedServiceText();
  4189. if (isPost()) {
  4190. result.text = tr::lng_action_removed_photo_channel(
  4191. tr::now,
  4192. Ui::Text::WithEntities);
  4193. } else {
  4194. result.links.push_back(fromLink());
  4195. result.text = tr::lng_action_removed_photo(
  4196. tr::now,
  4197. lt_from,
  4198. fromLinkText(), // Link 1.
  4199. Ui::Text::WithEntities);
  4200. }
  4201. return result;
  4202. };
  4203. auto prepareChatDeleteUser = [this](const MTPDmessageActionChatDeleteUser &action) {
  4204. auto result = PreparedServiceText();
  4205. if (peerFromUser(action.vuser_id()) == _from->id) {
  4206. result.links.push_back(fromLink());
  4207. result.text = tr::lng_action_user_left(
  4208. tr::now,
  4209. lt_from,
  4210. fromLinkText(), // Link 1.
  4211. Ui::Text::WithEntities);
  4212. } else {
  4213. auto user = _history->owner().user(action.vuser_id().v);
  4214. result.links.push_back(fromLink());
  4215. result.links.push_back(user->createOpenLink());
  4216. result.text = tr::lng_action_kick_user(
  4217. tr::now,
  4218. lt_from,
  4219. fromLinkText(), // Link 1.
  4220. lt_user,
  4221. Ui::Text::Link(user->name(), 2), // Link 2.
  4222. Ui::Text::WithEntities);
  4223. }
  4224. return result;
  4225. };
  4226. auto prepareChatEditPhoto = [this](const MTPDmessageActionChatEditPhoto &action) {
  4227. auto result = PreparedServiceText();
  4228. if (isPost()) {
  4229. result.text = tr::lng_action_changed_photo_channel(
  4230. tr::now,
  4231. Ui::Text::WithEntities);
  4232. } else {
  4233. result.links.push_back(fromLink());
  4234. result.text = tr::lng_action_changed_photo(
  4235. tr::now,
  4236. lt_from,
  4237. fromLinkText(), // Link 1.
  4238. Ui::Text::WithEntities);
  4239. }
  4240. return result;
  4241. };
  4242. auto prepareChatEditTitle = [this](const MTPDmessageActionChatEditTitle &action) {
  4243. auto result = PreparedServiceText();
  4244. if (isPost()) {
  4245. result.text = tr::lng_action_changed_title_channel(
  4246. tr::now,
  4247. lt_title,
  4248. { .text = (qs(action.vtitle())) },
  4249. Ui::Text::WithEntities);
  4250. } else {
  4251. result.links.push_back(fromLink());
  4252. result.text = tr::lng_action_changed_title(
  4253. tr::now,
  4254. lt_from,
  4255. fromLinkText(), // Link 1.
  4256. lt_title,
  4257. { .text = qs(action.vtitle()) },
  4258. Ui::Text::WithEntities);
  4259. }
  4260. return result;
  4261. };
  4262. auto preparePinMessage = [&](const MTPDmessageActionPinMessage &) {
  4263. return preparePinnedText();
  4264. };
  4265. auto prepareGameScore = [&](const MTPDmessageActionGameScore &) {
  4266. return prepareGameScoreText();
  4267. };
  4268. auto preparePhoneCall = [&](const MTPDmessageActionPhoneCall &) -> PreparedServiceText {
  4269. Unexpected("PhoneCall type in setServiceMessageFromMtp.");
  4270. };
  4271. auto preparePaymentSent = [&](const MTPDmessageActionPaymentSent &) {
  4272. return preparePaymentSentText();
  4273. };
  4274. auto preparePaymentSentMe = [&](const MTPDmessageActionPaymentSentMe &data) {
  4275. auto result = PreparedServiceText();
  4276. result.text = (data.is_recurring_used()
  4277. ? tr::lng_action_payment_bot_recurring
  4278. : tr::lng_action_payment_bot_done)(
  4279. tr::now,
  4280. lt_amount,
  4281. AmountAndStarCurrency(
  4282. &_history->session(),
  4283. data.vtotal_amount().v,
  4284. qs(data.vcurrency())),
  4285. Ui::Text::WithEntities);
  4286. return result;
  4287. };
  4288. auto prepareScreenshotTaken = [this](const MTPDmessageActionScreenshotTaken &) {
  4289. auto result = PreparedServiceText();
  4290. if (out()) {
  4291. result.text = tr::lng_action_you_took_screenshot(
  4292. tr::now,
  4293. Ui::Text::WithEntities);
  4294. } else {
  4295. result.links.push_back(fromLink());
  4296. result.text = tr::lng_action_took_screenshot(
  4297. tr::now,
  4298. lt_from,
  4299. fromLinkText(), // Link 1.
  4300. Ui::Text::WithEntities);
  4301. }
  4302. return result;
  4303. };
  4304. auto prepareCustomAction = [&](const MTPDmessageActionCustomAction &action) {
  4305. auto result = PreparedServiceText();
  4306. result.text = { .text = qs(action.vmessage()) };
  4307. return result;
  4308. };
  4309. auto prepareBotAllowed = [&](const MTPDmessageActionBotAllowed &action) {
  4310. auto result = PreparedServiceText();
  4311. if (action.is_attach_menu()) {
  4312. result.text = {
  4313. tr::lng_action_attach_menu_bot_allowed(tr::now)
  4314. };
  4315. } else if (action.is_from_request()) {
  4316. result.text = {
  4317. tr::lng_action_webapp_bot_allowed(tr::now)
  4318. };
  4319. } else if (const auto app = action.vapp()) {
  4320. const auto bot = history()->peer->asUser();
  4321. const auto botId = bot ? bot->id : PeerId();
  4322. const auto info = history()->owner().processBotApp(botId, *app);
  4323. const auto url = (bot && info)
  4324. ? history()->session().createInternalLinkFull(
  4325. bot->username() + '/' + info->shortName)
  4326. : QString();
  4327. result.text = tr::lng_action_bot_allowed_from_app(
  4328. tr::now,
  4329. lt_app,
  4330. (url.isEmpty()
  4331. ? TextWithEntities{ u"App"_q }
  4332. : Ui::Text::Link(info->title, url)),
  4333. Ui::Text::WithEntities);
  4334. } else {
  4335. const auto domain = qs(action.vdomain().value_or_empty());
  4336. result.text = tr::lng_action_bot_allowed_from_domain(
  4337. tr::now,
  4338. lt_domain,
  4339. Ui::Text::Link(domain, u"http://"_q + domain),
  4340. Ui::Text::WithEntities);
  4341. }
  4342. return result;
  4343. };
  4344. auto prepareSecureValuesSent = [&](const MTPDmessageActionSecureValuesSent &action) {
  4345. auto result = PreparedServiceText();
  4346. auto documents = QStringList();
  4347. for (const auto &type : action.vtypes().v) {
  4348. documents.push_back([&] {
  4349. switch (type.type()) {
  4350. case mtpc_secureValueTypePersonalDetails:
  4351. return tr::lng_action_secure_personal_details(tr::now);
  4352. case mtpc_secureValueTypePassport:
  4353. case mtpc_secureValueTypeDriverLicense:
  4354. case mtpc_secureValueTypeIdentityCard:
  4355. case mtpc_secureValueTypeInternalPassport:
  4356. return tr::lng_action_secure_proof_of_identity(tr::now);
  4357. case mtpc_secureValueTypeAddress:
  4358. return tr::lng_action_secure_address(tr::now);
  4359. case mtpc_secureValueTypeUtilityBill:
  4360. case mtpc_secureValueTypeBankStatement:
  4361. case mtpc_secureValueTypeRentalAgreement:
  4362. case mtpc_secureValueTypePassportRegistration:
  4363. case mtpc_secureValueTypeTemporaryRegistration:
  4364. return tr::lng_action_secure_proof_of_address(tr::now);
  4365. case mtpc_secureValueTypePhone:
  4366. return tr::lng_action_secure_phone(tr::now);
  4367. case mtpc_secureValueTypeEmail:
  4368. return tr::lng_action_secure_email(tr::now);
  4369. }
  4370. Unexpected("Type in prepareSecureValuesSent.");
  4371. }());
  4372. };
  4373. result.links.push_back(_history->peer->createOpenLink());
  4374. result.text = tr::lng_action_secure_values_sent(
  4375. tr::now,
  4376. lt_user,
  4377. Ui::Text::Link(_history->peer->name(), QString()), // Link 1.
  4378. lt_documents,
  4379. { .text = documents.join(", ") },
  4380. Ui::Text::WithEntities);
  4381. return result;
  4382. };
  4383. auto prepareContactSignUp = [this](const MTPDmessageActionContactSignUp &data) {
  4384. auto result = PreparedServiceText();
  4385. result.links.push_back(fromLink());
  4386. result.text = tr::lng_action_user_registered(
  4387. tr::now,
  4388. lt_from,
  4389. fromLinkText(), // Link 1.
  4390. Ui::Text::WithEntities);
  4391. return result;
  4392. };
  4393. auto prepareProximityReached = [this](const MTPDmessageActionGeoProximityReached &action) {
  4394. auto result = PreparedServiceText();
  4395. const auto fromId = peerFromMTP(action.vfrom_id());
  4396. const auto fromPeer = _history->owner().peer(fromId);
  4397. const auto toId = peerFromMTP(action.vto_id());
  4398. const auto toPeer = _history->owner().peer(toId);
  4399. const auto selfId = _from->session().userPeerId();
  4400. const auto distanceMeters = action.vdistance().v;
  4401. const auto distance = [&] {
  4402. if (distanceMeters >= 1000) {
  4403. const auto km = (10 * (distanceMeters / 10)) / 1000.;
  4404. return tr::lng_action_proximity_distance_km(
  4405. tr::now,
  4406. lt_count,
  4407. km);
  4408. } else {
  4409. return tr::lng_action_proximity_distance_m(
  4410. tr::now,
  4411. lt_count,
  4412. distanceMeters);
  4413. }
  4414. }();
  4415. result.text = [&] {
  4416. if (fromId == selfId) {
  4417. result.links.push_back(toPeer->createOpenLink());
  4418. return tr::lng_action_you_proximity_reached(
  4419. tr::now,
  4420. lt_distance,
  4421. { .text = distance },
  4422. lt_user,
  4423. Ui::Text::Link(toPeer->name(), QString()), // Link 1.
  4424. Ui::Text::WithEntities);
  4425. } else if (toId == selfId) {
  4426. result.links.push_back(fromPeer->createOpenLink());
  4427. return tr::lng_action_proximity_reached_you(
  4428. tr::now,
  4429. lt_from,
  4430. Ui::Text::Link(fromPeer->name(), QString()), // Link 1.
  4431. lt_distance,
  4432. { .text = distance },
  4433. Ui::Text::WithEntities);
  4434. } else {
  4435. result.links.push_back(fromPeer->createOpenLink());
  4436. result.links.push_back(toPeer->createOpenLink());
  4437. return tr::lng_action_proximity_reached(
  4438. tr::now,
  4439. lt_from,
  4440. Ui::Text::Link(fromPeer->name(), 1), // Link 1.
  4441. lt_distance,
  4442. { .text = distance },
  4443. lt_user,
  4444. Ui::Text::Link(toPeer->name(), 2), // Link 2.
  4445. Ui::Text::WithEntities);
  4446. }
  4447. }();
  4448. return result;
  4449. };
  4450. auto prepareGroupCall = [this](const MTPDmessageActionGroupCall &action) {
  4451. auto result = PreparedServiceText();
  4452. if (const auto duration = action.vduration()) {
  4453. const auto seconds = duration->v;
  4454. const auto days = seconds / 86400;
  4455. const auto hours = seconds / 3600;
  4456. const auto minutes = seconds / 60;
  4457. auto text = (days > 1)
  4458. ? tr::lng_days(tr::now, lt_count, days)
  4459. : (hours > 1)
  4460. ? tr::lng_hours(tr::now, lt_count, hours)
  4461. : (minutes > 1)
  4462. ? tr::lng_minutes(tr::now, lt_count, minutes)
  4463. : tr::lng_seconds(tr::now, lt_count, seconds);
  4464. if (_history->peer->isBroadcast()) {
  4465. result.text = tr::lng_action_group_call_finished(
  4466. tr::now,
  4467. lt_duration,
  4468. { .text = text },
  4469. Ui::Text::WithEntities);
  4470. } else {
  4471. result.links.push_back(fromLink());
  4472. result.text = tr::lng_action_group_call_finished_group(
  4473. tr::now,
  4474. lt_from,
  4475. fromLinkText(), // Link 1.
  4476. lt_duration,
  4477. { .text = text },
  4478. Ui::Text::WithEntities);
  4479. }
  4480. return result;
  4481. }
  4482. if (_history->peer->isBroadcast()) {
  4483. result.text = tr::lng_action_group_call_started_channel(
  4484. tr::now,
  4485. Ui::Text::WithEntities);
  4486. } else {
  4487. result.links.push_back(fromLink());
  4488. result.text = tr::lng_action_group_call_started_group(
  4489. tr::now,
  4490. lt_from,
  4491. fromLinkText(), // Link 1.
  4492. Ui::Text::WithEntities);
  4493. }
  4494. return result;
  4495. };
  4496. auto prepareInviteToGroupCall = [this](const MTPDmessageActionInviteToGroupCall &action) {
  4497. const auto callId = CallIdFromInput(action.vcall());
  4498. const auto owner = &_history->owner();
  4499. const auto peer = _history->peer;
  4500. for (const auto &id : action.vusers().v) {
  4501. const auto user = owner->user(id.v);
  4502. if (callId) {
  4503. owner->registerInvitedToCallUser(callId, peer, user);
  4504. }
  4505. };
  4506. const auto linkCallId = PeerHasThisCall(peer, callId).value_or(false)
  4507. ? callId
  4508. : 0;
  4509. return prepareInvitedToCallText(
  4510. ParseInvitedToCallUsers(this, action.vusers().v),
  4511. linkCallId);
  4512. };
  4513. auto prepareSetMessagesTTL = [this](const MTPDmessageActionSetMessagesTTL &action) {
  4514. auto result = PreparedServiceText();
  4515. const auto period = action.vperiod().v;
  4516. const auto duration = (period == 5)
  4517. ? u"5 seconds"_q
  4518. : Ui::FormatTTL(period);
  4519. if (const auto from = action.vauto_setting_from(); from && period) {
  4520. if (const auto peer = _from->owner().peer(peerFromUser(*from))) {
  4521. result.text = (peer->id == peer->session().userPeerId())
  4522. ? tr::lng_action_ttl_global_me(
  4523. tr::now,
  4524. lt_duration,
  4525. { .text = duration },
  4526. Ui::Text::WithEntities)
  4527. : tr::lng_action_ttl_global(
  4528. tr::now,
  4529. lt_from,
  4530. Ui::Text::Link(peer->name(), 1), // Link 1.
  4531. lt_duration,
  4532. { .text = duration },
  4533. Ui::Text::WithEntities);
  4534. return result;
  4535. }
  4536. }
  4537. if (isPost()) {
  4538. if (!period) {
  4539. result.text = tr::lng_action_ttl_removed_channel(
  4540. tr::now,
  4541. Ui::Text::WithEntities);
  4542. } else {
  4543. result.text = tr::lng_action_ttl_changed_channel(
  4544. tr::now,
  4545. lt_duration,
  4546. { .text = duration },
  4547. Ui::Text::WithEntities);
  4548. }
  4549. } else if (_from->isSelf()) {
  4550. if (!period) {
  4551. result.text = tr::lng_action_ttl_removed_you(
  4552. tr::now,
  4553. Ui::Text::WithEntities);
  4554. } else {
  4555. result.text = tr::lng_action_ttl_changed_you(
  4556. tr::now,
  4557. lt_duration,
  4558. { .text = duration },
  4559. Ui::Text::WithEntities);
  4560. }
  4561. } else {
  4562. result.links.push_back(fromLink());
  4563. if (!period) {
  4564. result.text = tr::lng_action_ttl_removed(
  4565. tr::now,
  4566. lt_from,
  4567. fromLinkText(), // Link 1.
  4568. Ui::Text::WithEntities);
  4569. } else {
  4570. result.text = tr::lng_action_ttl_changed(
  4571. tr::now,
  4572. lt_from,
  4573. fromLinkText(), // Link 1.
  4574. lt_duration,
  4575. { .text = duration },
  4576. Ui::Text::WithEntities);
  4577. }
  4578. }
  4579. return result;
  4580. };
  4581. auto prepareGroupCallScheduled = [&](const MTPDmessageActionGroupCallScheduled &data) {
  4582. return prepareCallScheduledText(data.vschedule_date().v);
  4583. };
  4584. auto prepareSetChatTheme = [this](const MTPDmessageActionSetChatTheme &action) {
  4585. auto result = PreparedServiceText();
  4586. const auto text = qs(action.vemoticon());
  4587. if (!text.isEmpty()) {
  4588. if (_from->isSelf()) {
  4589. result.text = tr::lng_action_you_theme_changed(
  4590. tr::now,
  4591. lt_emoji,
  4592. { .text = text },
  4593. Ui::Text::WithEntities);
  4594. } else {
  4595. result.links.push_back(fromLink());
  4596. result.text = tr::lng_action_theme_changed(
  4597. tr::now,
  4598. lt_from,
  4599. fromLinkText(), // Link 1.
  4600. lt_emoji,
  4601. { .text = text },
  4602. Ui::Text::WithEntities);
  4603. }
  4604. } else {
  4605. if (_from->isSelf()) {
  4606. result.text = tr::lng_action_you_theme_disabled(
  4607. tr::now,
  4608. Ui::Text::WithEntities);
  4609. } else {
  4610. result.links.push_back(fromLink());
  4611. result.text = tr::lng_action_theme_disabled(
  4612. tr::now,
  4613. lt_from,
  4614. fromLinkText(), // Link 1.
  4615. Ui::Text::WithEntities);
  4616. }
  4617. }
  4618. return result;
  4619. };
  4620. auto prepareChatJoinedByRequest = [this](const MTPDmessageActionChatJoinedByRequest &action) {
  4621. auto result = PreparedServiceText();
  4622. result.links.push_back(fromLink());
  4623. result.text = tr::lng_action_user_joined_by_request(
  4624. tr::now,
  4625. lt_from,
  4626. fromLinkText(), // Link 1.
  4627. Ui::Text::WithEntities);
  4628. return result;
  4629. };
  4630. auto prepareWebViewDataSent = [](const MTPDmessageActionWebViewDataSent &action) {
  4631. auto result = PreparedServiceText();
  4632. result.text = tr::lng_action_webview_data_done(
  4633. tr::now,
  4634. lt_text,
  4635. { .text = qs(action.vtext()) },
  4636. Ui::Text::WithEntities);
  4637. return result;
  4638. };
  4639. auto prepareGiftPremium = [&](
  4640. const MTPDmessageActionGiftPremium &action) {
  4641. auto result = PreparedServiceText();
  4642. const auto session = &_history->session();
  4643. const auto isSelf = _from->isSelf();
  4644. const auto peer = isSelf ? _history->peer : _from;
  4645. session->giftBoxStickersPacks().load();
  4646. const auto amount = action.vamount().v;
  4647. const auto currency = qs(action.vcurrency());
  4648. const auto cost = AmountAndStarCurrency(session, amount, currency);
  4649. const auto anonymous = _from->isServiceUser();
  4650. if (anonymous) {
  4651. result.text = tr::lng_action_gift_received_anonymous(
  4652. tr::now,
  4653. lt_cost,
  4654. cost,
  4655. Ui::Text::WithEntities);
  4656. } else {
  4657. result.links.push_back(peer->createOpenLink());
  4658. result.text = isSelf
  4659. ? tr::lng_action_gift_sent(tr::now,
  4660. lt_cost,
  4661. cost,
  4662. Ui::Text::WithEntities)
  4663. : tr::lng_action_gift_received(
  4664. tr::now,
  4665. lt_user,
  4666. Ui::Text::Link(peer->shortName(), 1), // Link 1.
  4667. lt_cost,
  4668. cost,
  4669. Ui::Text::WithEntities);
  4670. }
  4671. return result;
  4672. };
  4673. auto prepareTopicCreate = [&](const MTPDmessageActionTopicCreate &action) {
  4674. auto result = PreparedServiceText();
  4675. const auto topicUrl = u"internal:url:https://t.me/c/%1/%2"_q
  4676. .arg(peerToChannel(_history->peer->id).bare)
  4677. .arg(id.bare);
  4678. result.text = tr::lng_action_topic_created(
  4679. tr::now,
  4680. lt_topic,
  4681. Ui::Text::Link(
  4682. Data::ForumTopicIconWithTitle(
  4683. id,
  4684. action.vicon_emoji_id().value_or_empty(),
  4685. qs(action.vtitle())),
  4686. topicUrl),
  4687. Ui::Text::WithEntities);
  4688. return result;
  4689. };
  4690. auto prepareTopicEdit = [&](const MTPDmessageActionTopicEdit &action) {
  4691. auto result = PreparedServiceText();
  4692. if (const auto closed = action.vclosed()) {
  4693. result.text = { mtpIsTrue(*closed)
  4694. ? tr::lng_action_topic_closed_inside(tr::now)
  4695. : tr::lng_action_topic_reopened_inside(tr::now) };
  4696. } else if (const auto hidden = action.vhidden()) {
  4697. result.text = { mtpIsTrue(*hidden)
  4698. ? tr::lng_action_topic_hidden_inside(tr::now)
  4699. : tr::lng_action_topic_unhidden_inside(tr::now) };
  4700. } else if (!action.vtitle()) {
  4701. if (const auto icon = action.vicon_emoji_id()) {
  4702. if (const auto iconId = icon->v) {
  4703. result.links.push_back(fromLink());
  4704. result.text = tr::lng_action_topic_icon_changed(
  4705. tr::now,
  4706. lt_from,
  4707. fromLinkText(), // Link 1.
  4708. lt_link,
  4709. { tr::lng_action_topic_placeholder(tr::now) },
  4710. lt_emoji,
  4711. Data::SingleCustomEmoji(iconId),
  4712. Ui::Text::WithEntities);
  4713. } else {
  4714. result.links.push_back(fromLink());
  4715. result.text = tr::lng_action_topic_icon_removed(
  4716. tr::now,
  4717. lt_from,
  4718. fromLinkText(), // Link 1.
  4719. lt_link,
  4720. { tr::lng_action_topic_placeholder(tr::now) },
  4721. Ui::Text::WithEntities);
  4722. }
  4723. }
  4724. } else {
  4725. result.links.push_back(fromLink());
  4726. result.text = tr::lng_action_topic_renamed(
  4727. tr::now,
  4728. lt_from,
  4729. fromLinkText(), // Link 1.
  4730. lt_link,
  4731. { tr::lng_action_topic_placeholder(tr::now) },
  4732. lt_title,
  4733. Data::ForumTopicIconWithTitle(
  4734. topicRootId(),
  4735. action.vicon_emoji_id().value_or_empty(),
  4736. qs(*action.vtitle())),
  4737. Ui::Text::WithEntities);
  4738. }
  4739. if (result.text.empty()) {
  4740. result.text = { tr::lng_message_empty(tr::now) };
  4741. }
  4742. return result;
  4743. };
  4744. auto prepareSuggestProfilePhoto = [this](const MTPDmessageActionSuggestProfilePhoto &action) {
  4745. auto result = PreparedServiceText{};
  4746. const auto isSelf = (_from->id == _from->session().userPeerId());
  4747. const auto isVideo = action.vphoto().match([&](const MTPDphoto &data) {
  4748. return data.vvideo_sizes().has_value()
  4749. && !data.vvideo_sizes()->v.isEmpty();
  4750. }, [](const MTPDphotoEmpty &) {
  4751. return false;
  4752. });
  4753. const auto peer = isSelf ? history()->peer : _from;
  4754. const auto user = peer->asUser();
  4755. const auto name = (user && !user->firstName.isEmpty())
  4756. ? user->firstName
  4757. : peer->name();
  4758. result.links.push_back(peer->createOpenLink());
  4759. result.text = (isSelf
  4760. ? (isVideo
  4761. ? tr::lng_action_suggested_video_me
  4762. : tr::lng_action_suggested_photo_me)
  4763. : (isVideo
  4764. ? tr::lng_action_suggested_video
  4765. : tr::lng_action_suggested_photo))(
  4766. tr::now,
  4767. lt_user,
  4768. Ui::Text::Link(name, 1), // Link 1.
  4769. Ui::Text::WithEntities);
  4770. return result;
  4771. };
  4772. auto prepareRequestedPeer = [&](
  4773. const MTPDmessageActionRequestedPeer &action) {
  4774. auto result = PreparedServiceText{};
  4775. result.links.push_back(history()->peer->createOpenLink());
  4776. const auto &list = action.vpeers().v;
  4777. for (auto i = 0, count = int(list.size()); i != count; ++i) {
  4778. const auto id = peerFromMTP(list[i]);
  4779. auto user = _history->owner().peer(id);
  4780. result.links.push_back(user->createOpenLink());
  4781. auto linkText = Ui::Text::Link(user->name(), 2 + i);
  4782. if (i == 0) {
  4783. result.text = linkText;
  4784. } else if (i + 1 == count) {
  4785. result.text = tr::lng_action_add_users_and_last(
  4786. tr::now,
  4787. lt_accumulated,
  4788. result.text,
  4789. lt_user,
  4790. linkText,
  4791. Ui::Text::WithEntities);
  4792. } else {
  4793. result.text = tr::lng_action_add_users_and_one(
  4794. tr::now,
  4795. lt_accumulated,
  4796. result.text,
  4797. lt_user,
  4798. linkText,
  4799. Ui::Text::WithEntities);
  4800. }
  4801. }
  4802. result.text = tr::lng_action_shared_chat_with_bot(
  4803. tr::now,
  4804. lt_chat,
  4805. result.text,
  4806. lt_bot,
  4807. Ui::Text::Link(history()->peer->name(), 1),
  4808. Ui::Text::WithEntities);
  4809. return result;
  4810. };
  4811. auto prepareSetChatWallPaper = [&](
  4812. const MTPDmessageActionSetChatWallPaper &action) {
  4813. const auto isSelf = (_from->id == _from->session().userPeerId());
  4814. const auto same = action.is_same();
  4815. const auto both = action.is_for_both();
  4816. const auto peer = isSelf ? history()->peer : _from;
  4817. const auto user = peer->asUser();
  4818. const auto name = (user && !user->firstName.isEmpty())
  4819. ? user->firstName
  4820. : peer->name();
  4821. auto result = PreparedServiceText{};
  4822. if (!isSelf) {
  4823. result.links.push_back(peer->createOpenLink());
  4824. }
  4825. result.text = isSelf
  4826. ? ((!same && both)
  4827. ? tr::lng_action_set_wallpaper_both_me(
  4828. tr::now,
  4829. lt_user,
  4830. Ui::Text::Link(Ui::Text::Bold(name), 1),
  4831. Ui::Text::WithEntities)
  4832. : (same
  4833. ? tr::lng_action_set_same_wallpaper_me
  4834. : tr::lng_action_set_wallpaper_me)(
  4835. tr::now,
  4836. Ui::Text::WithEntities))
  4837. : (same
  4838. ? tr::lng_action_set_same_wallpaper
  4839. : tr::lng_action_set_wallpaper)(
  4840. tr::now,
  4841. lt_user,
  4842. Ui::Text::Link(Ui::Text::Bold(name), 1),
  4843. Ui::Text::WithEntities);
  4844. return result;
  4845. };
  4846. auto prepareGiftCode = [&](const MTPDmessageActionGiftCode &action) {
  4847. auto result = PreparedServiceText();
  4848. _history->session().giftBoxStickersPacks().load();
  4849. if (const auto boosted = action.vboost_peer()) {
  4850. result.text = {
  4851. (action.is_unclaimed()
  4852. ? tr::lng_prize_unclaimed_about
  4853. : action.is_via_giveaway()
  4854. ? tr::lng_prize_about
  4855. : tr::lng_prize_gift_about)(
  4856. tr::now,
  4857. lt_channel,
  4858. _from->owner().peer(
  4859. peerFromMTP(*action.vboost_peer()))->name()),
  4860. };
  4861. } else {
  4862. const auto isSelf = (_from->id == _from->session().userPeerId());
  4863. const auto peer = isSelf ? _history->peer : _from;
  4864. const auto cost = AmountAndStarCurrency(
  4865. &_history->session(),
  4866. action.vamount().value_or_empty(),
  4867. qs(action.vcurrency().value_or_empty()));
  4868. result.links.push_back(peer->createOpenLink());
  4869. result.text = isSelf
  4870. ? tr::lng_action_gift_sent(tr::now,
  4871. lt_cost,
  4872. cost,
  4873. Ui::Text::WithEntities)
  4874. : tr::lng_action_gift_received(
  4875. tr::now,
  4876. lt_user,
  4877. Ui::Text::Link(peer->shortName(), 1), // Link 1.
  4878. lt_cost,
  4879. cost,
  4880. Ui::Text::WithEntities);
  4881. }
  4882. return result;
  4883. };
  4884. auto prepareGiveawayLaunch = [&](const MTPDmessageActionGiveawayLaunch &action) {
  4885. const auto credits = action.vstars().value_or_empty();
  4886. auto result = PreparedServiceText();
  4887. result.links.push_back(fromLink());
  4888. result.text = credits
  4889. ? (_history->peer->isMegagroup()
  4890. ? tr::lng_action_giveaway_credits_started_group
  4891. : tr::lng_action_giveaway_credits_started)(
  4892. tr::now,
  4893. lt_from,
  4894. fromLinkText(), // Link 1.
  4895. lt_amount,
  4896. tr::lng_action_giveaway_credits_started_amount(
  4897. tr::now,
  4898. lt_count_decimal,
  4899. float64(credits),
  4900. Ui::Text::Bold),
  4901. Ui::Text::WithEntities)
  4902. : (_history->peer->isMegagroup()
  4903. ? tr::lng_action_giveaway_started_group
  4904. : tr::lng_action_giveaway_started)(
  4905. tr::now,
  4906. lt_from,
  4907. fromLinkText(), // Link 1.
  4908. Ui::Text::WithEntities);
  4909. return result;
  4910. };
  4911. auto prepareGiveawayResults = [&](const MTPDmessageActionGiveawayResults &action) {
  4912. auto result = PreparedServiceText();
  4913. const auto winners = action.vwinners_count().v;
  4914. const auto unclaimed = action.vunclaimed_count().v;
  4915. const auto credits = action.is_stars();
  4916. result.text = {
  4917. (!winners
  4918. ? tr::lng_action_giveaway_results_none(tr::now)
  4919. : (credits && unclaimed)
  4920. ? tr::lng_action_giveaway_results_credits_some(tr::now)
  4921. : (!credits && unclaimed)
  4922. ? tr::lng_action_giveaway_results_some(tr::now)
  4923. : (credits && !unclaimed)
  4924. ? tr::lng_action_giveaway_results_credits(
  4925. tr::now,
  4926. lt_count,
  4927. winners)
  4928. : tr::lng_action_giveaway_results(tr::now, lt_count, winners))
  4929. };
  4930. return result;
  4931. };
  4932. auto prepareBoostApply = [&](const MTPDmessageActionBoostApply &action) {
  4933. auto result = PreparedServiceText();
  4934. const auto boosts = action.vboosts().v;
  4935. const auto isSelf = (_from->id == _from->session().userPeerId());
  4936. result.links.push_back(fromLink());
  4937. result.text = isSelf
  4938. ? tr::lng_action_boost_apply_me(tr::now, Ui::Text::WithEntities)
  4939. : tr::lng_action_boost_apply(
  4940. tr::now,
  4941. lt_count,
  4942. boosts,
  4943. lt_from,
  4944. fromLinkText(), // Link 1.
  4945. Ui::Text::WithEntities);
  4946. const auto channel = _history->peer->asChannel();
  4947. setCustomServiceLink(std::make_shared<LambdaClickHandler>([=](
  4948. ClickContext context) {
  4949. const auto my = context.other.value<ClickHandlerContext>();
  4950. const auto weak = my.sessionWindow;
  4951. if (const auto strong = channel ? weak.get() : nullptr) {
  4952. strong->resolveBoostState(channel);
  4953. }
  4954. }));
  4955. return result;
  4956. };
  4957. auto preparePaymentRefunded = [&](const MTPDmessageActionPaymentRefunded &action) {
  4958. auto result = PreparedServiceText();
  4959. const auto refund = Get<HistoryServicePaymentRefund>();
  4960. Assert(refund != nullptr);
  4961. Assert(refund->peer != nullptr);
  4962. const auto amount = refund->amount;
  4963. const auto currency = refund->currency;
  4964. result.links.push_back(refund->peer->createOpenLink());
  4965. result.text = tr::lng_action_payment_refunded(
  4966. tr::now,
  4967. lt_peer,
  4968. Ui::Text::Link(refund->peer->name(), 1), // Link 1.
  4969. lt_amount,
  4970. AmountAndStarCurrency(&_history->session(), amount, currency),
  4971. Ui::Text::WithEntities);
  4972. return result;
  4973. };
  4974. auto prepareGiftStars = [&](
  4975. const MTPDmessageActionGiftStars &action) {
  4976. auto result = PreparedServiceText();
  4977. const auto isSelf = (_from->id == _from->session().userPeerId());
  4978. const auto peer = isSelf ? _history->peer : _from;
  4979. _history->session().giftBoxStickersPacks().load();
  4980. const auto amount = action.vamount().v;
  4981. const auto currency = qs(action.vcurrency());
  4982. const auto cost = AmountAndStarCurrency(
  4983. &_history->session(),
  4984. amount,
  4985. currency);
  4986. const auto anonymous = _from->isServiceUser();
  4987. if (anonymous) {
  4988. result.text = tr::lng_action_gift_received_anonymous(
  4989. tr::now,
  4990. lt_cost,
  4991. cost,
  4992. Ui::Text::WithEntities);
  4993. } else {
  4994. result.links.push_back(peer->createOpenLink());
  4995. result.text = isSelf
  4996. ? tr::lng_action_gift_sent(tr::now,
  4997. lt_cost,
  4998. cost,
  4999. Ui::Text::WithEntities)
  5000. : tr::lng_action_gift_received(
  5001. tr::now,
  5002. lt_user,
  5003. Ui::Text::Link(peer->shortName(), 1), // Link 1.
  5004. lt_cost,
  5005. cost,
  5006. Ui::Text::WithEntities);
  5007. }
  5008. return result;
  5009. };
  5010. auto prepareGiftPrize = [&](
  5011. const MTPDmessageActionPrizeStars &action) {
  5012. auto result = PreparedServiceText();
  5013. _history->session().giftBoxStickersPacks().load();
  5014. result.text = {
  5015. (action.is_unclaimed()
  5016. ? tr::lng_prize_unclaimed_about
  5017. : tr::lng_prize_about)(
  5018. tr::now,
  5019. lt_channel,
  5020. _from->owner().peer(
  5021. peerFromMTP(action.vboost_peer()))->name()),
  5022. };
  5023. return result;
  5024. };
  5025. auto prepareStarGift = [&](
  5026. const MTPDmessageActionStarGift &action) {
  5027. auto result = PreparedServiceText();
  5028. const auto isSelf = _from->isSelf();
  5029. const auto peer = isSelf ? _history->peer : _from;
  5030. const auto stars = action.vgift().match([&](
  5031. const MTPDstarGift &data) {
  5032. return uint64(data.vstars().v)
  5033. + uint64(action.vupgrade_stars().value_or_empty());
  5034. }, [](const MTPDstarGiftUnique &) {
  5035. return uint64();
  5036. });
  5037. if (!stars) {
  5038. if (!isSelf) {
  5039. result.links.push_back(peer->createOpenLink());
  5040. }
  5041. result.text = isSelf
  5042. ? tr::lng_action_gift_unique_sent(
  5043. tr::now,
  5044. Ui::Text::WithEntities)
  5045. : tr::lng_action_gift_unique_received(
  5046. tr::now,
  5047. lt_user,
  5048. Ui::Text::Link(peer->shortName(), 1), // Link 1.
  5049. Ui::Text::WithEntities);
  5050. return result;
  5051. }
  5052. const auto cost = TextWithEntities{
  5053. tr::lng_action_gift_for_stars(tr::now, lt_count, stars),
  5054. };
  5055. const auto giftPeer = action.vpeer()
  5056. ? peerFromMTP(*action.vpeer())
  5057. : PeerId();
  5058. const auto service = _from->isServiceUser();
  5059. const auto toChannel = service && peerIsChannel(giftPeer);
  5060. const auto anonymous = service && !toChannel;
  5061. if (toChannel) {
  5062. const auto fromId = action.vfrom_id()
  5063. ? peerFromMTP(*action.vfrom_id())
  5064. : PeerId();
  5065. const auto from = fromId ? peer->owner().peer(fromId) : peer;
  5066. const auto channel = peer->owner().channel(
  5067. peerToChannel(giftPeer));
  5068. if (from->isSelf()) {
  5069. result.links.push_back(channel->createOpenLink());
  5070. result.text = tr::lng_action_gift_sent_self_channel(
  5071. tr::now,
  5072. lt_name,
  5073. Ui::Text::Link(channel->name(), 1),
  5074. lt_cost,
  5075. cost,
  5076. Ui::Text::WithEntities);
  5077. } else {
  5078. result.links.push_back(from->createOpenLink());
  5079. result.links.push_back(channel->createOpenLink());
  5080. result.text = tr::lng_action_gift_sent_channel(
  5081. tr::now,
  5082. lt_user,
  5083. Ui::Text::Link(from->shortName(), 1),
  5084. lt_name,
  5085. Ui::Text::Link(channel->name(), 2),
  5086. lt_cost,
  5087. cost,
  5088. Ui::Text::WithEntities);
  5089. }
  5090. } else if (anonymous || _history->peer->isSelf()) {
  5091. result.text = (anonymous
  5092. ? tr::lng_action_gift_received_anonymous
  5093. : tr::lng_action_gift_self_bought)(
  5094. tr::now,
  5095. lt_cost,
  5096. cost,
  5097. Ui::Text::WithEntities);
  5098. } else {
  5099. if (!isSelf) {
  5100. result.links.push_back(peer->createOpenLink());
  5101. }
  5102. result.text = isSelf
  5103. ? tr::lng_action_gift_sent(tr::now,
  5104. lt_cost,
  5105. cost,
  5106. Ui::Text::WithEntities)
  5107. : tr::lng_action_gift_received(
  5108. tr::now,
  5109. lt_user,
  5110. Ui::Text::Link(peer->shortName(), 1), // Link 1.
  5111. lt_cost,
  5112. cost,
  5113. Ui::Text::WithEntities);
  5114. }
  5115. return result;
  5116. };
  5117. auto prepareStarGiftUnique = [&](
  5118. const MTPDmessageActionStarGiftUnique &action) {
  5119. auto result = PreparedServiceText();
  5120. const auto isSelf = _from->isSelf();
  5121. const auto giftPeer = action.vpeer()
  5122. ? peerFromMTP(*action.vpeer())
  5123. : PeerId();
  5124. const auto service = _from->isServiceUser();
  5125. const auto toChannel = service && peerIsChannel(giftPeer);
  5126. const auto peer = isSelf ? _history->peer : _from;
  5127. const auto fromId = action.vfrom_id()
  5128. ? peerFromMTP(*action.vfrom_id())
  5129. : PeerId();
  5130. const auto from = fromId ? peer->owner().peer(fromId) : peer;
  5131. if (toChannel) {
  5132. const auto channel = peer->owner().channel(
  5133. peerToChannel(giftPeer));
  5134. if (!from->isServiceUser() && !from->isSelf()) {
  5135. result.links.push_back(from->createOpenLink());
  5136. result.text = (action.is_upgrade()
  5137. ? tr::lng_action_gift_upgraded_channel
  5138. : tr::lng_action_gift_transferred_channel)(
  5139. tr::now,
  5140. lt_user,
  5141. Ui::Text::Link(from->shortName(), 1),
  5142. lt_channel,
  5143. Ui::Text::Link(channel->name(), 2),
  5144. Ui::Text::WithEntities);
  5145. } else {
  5146. result.text = (from->isServiceUser()
  5147. ? tr::lng_action_gift_transferred_unknown_channel
  5148. : action.is_upgrade()
  5149. ? tr::lng_action_gift_upgraded_self_channel
  5150. : tr::lng_action_gift_transferred_self_channel)(
  5151. tr::now,
  5152. lt_channel,
  5153. Ui::Text::Link(channel->name(), 1),
  5154. Ui::Text::WithEntities);
  5155. }
  5156. result.links.push_back(channel->createOpenLink());
  5157. } else {
  5158. if (!from->isServiceUser() && !_history->peer->isSelf()) {
  5159. result.links.push_back(from->createOpenLink());
  5160. result.text = (action.is_upgrade()
  5161. ? (isSelf
  5162. ? tr::lng_action_gift_upgraded_mine
  5163. : tr::lng_action_gift_upgraded)
  5164. : (isSelf
  5165. ? tr::lng_action_gift_transferred_mine
  5166. : tr::lng_action_gift_transferred))(
  5167. tr::now,
  5168. lt_user,
  5169. Ui::Text::Link(from->shortName(), 1), // Link 1.
  5170. Ui::Text::WithEntities);
  5171. } else {
  5172. result.text = (from->isServiceUser()
  5173. ? tr::lng_action_gift_transferred_unknown
  5174. : action.is_upgrade()
  5175. ? tr::lng_action_gift_upgraded_self
  5176. : tr::lng_action_gift_transferred_self)(
  5177. tr::now,
  5178. Ui::Text::WithEntities);
  5179. }
  5180. }
  5181. return result;
  5182. };
  5183. setServiceText(action.match(
  5184. prepareChatAddUserText,
  5185. prepareChatJoinedByLink,
  5186. prepareChatCreate,
  5187. PrepareEmptyText<MTPDmessageActionChatMigrateTo>,
  5188. PrepareEmptyText<MTPDmessageActionChannelMigrateFrom>,
  5189. PrepareEmptyText<MTPDmessageActionHistoryClear>,
  5190. prepareChannelCreate,
  5191. prepareChatDeletePhoto,
  5192. prepareChatDeleteUser,
  5193. prepareChatEditPhoto,
  5194. prepareChatEditTitle,
  5195. preparePinMessage,
  5196. prepareGameScore,
  5197. preparePhoneCall,
  5198. preparePaymentSent,
  5199. prepareScreenshotTaken,
  5200. prepareCustomAction,
  5201. prepareBotAllowed,
  5202. prepareSecureValuesSent,
  5203. prepareContactSignUp,
  5204. prepareProximityReached,
  5205. preparePaymentSentMe,
  5206. PrepareErrorText<MTPDmessageActionSecureValuesSentMe>,
  5207. prepareGroupCall,
  5208. prepareInviteToGroupCall,
  5209. prepareSetMessagesTTL,
  5210. prepareGroupCallScheduled,
  5211. prepareSetChatTheme,
  5212. prepareChatJoinedByRequest,
  5213. prepareWebViewDataSent,
  5214. prepareGiftPremium,
  5215. prepareTopicCreate,
  5216. prepareTopicEdit,
  5217. PrepareErrorText<MTPDmessageActionWebViewDataSentMe>,
  5218. prepareSuggestProfilePhoto,
  5219. prepareRequestedPeer,
  5220. prepareSetChatWallPaper,
  5221. prepareGiftCode,
  5222. prepareGiveawayLaunch,
  5223. prepareGiveawayResults,
  5224. prepareBoostApply,
  5225. preparePaymentRefunded,
  5226. prepareGiftStars,
  5227. prepareGiftPrize,
  5228. prepareStarGift,
  5229. prepareStarGiftUnique,
  5230. PrepareEmptyText<MTPDmessageActionRequestedPeerSentMe>,
  5231. PrepareErrorText<MTPDmessageActionEmpty>));
  5232. // Additional information.
  5233. applyAction(action);
  5234. }
  5235. void HistoryItem::applyAction(const MTPMessageAction &action) {
  5236. action.match([&](const MTPDmessageActionChatAddUser &data) {
  5237. if (const auto channel = _history->peer->asMegagroup()) {
  5238. const auto selfUserId = _history->session().userId();
  5239. for (const auto &item : data.vusers().v) {
  5240. if (peerFromUser(item) == selfUserId) {
  5241. channel->mgInfo->joinedMessageFound = true;
  5242. break;
  5243. }
  5244. }
  5245. }
  5246. }, [&](const MTPDmessageActionChatJoinedByLink &data) {
  5247. if (_from->isSelf()) {
  5248. if (const auto channel = _history->peer->asMegagroup()) {
  5249. channel->mgInfo->joinedMessageFound = true;
  5250. }
  5251. }
  5252. }, [&](const MTPDmessageActionChatEditPhoto &data) {
  5253. data.vphoto().match([&](const MTPDphoto &photo) {
  5254. _media = std::make_unique<Data::MediaPhoto>(
  5255. this,
  5256. _history->peer,
  5257. _history->owner().processPhoto(photo));
  5258. }, [](const MTPDphotoEmpty &) {
  5259. });
  5260. }, [&](const MTPDmessageActionChatCreate &) {
  5261. _flags |= MessageFlag::IsGroupEssential;
  5262. }, [&](const MTPDmessageActionChannelCreate &) {
  5263. _flags |= MessageFlag::IsGroupEssential;
  5264. }, [&](const MTPDmessageActionChatMigrateTo &) {
  5265. _flags |= MessageFlag::IsGroupEssential;
  5266. }, [&](const MTPDmessageActionChannelMigrateFrom &) {
  5267. _flags |= MessageFlag::IsGroupEssential;
  5268. }, [&](const MTPDmessageActionContactSignUp &) {
  5269. _flags |= MessageFlag::IsContactSignUp;
  5270. }, [&](const MTPDmessageActionChatJoinedByRequest &data) {
  5271. if (_from->isSelf()) {
  5272. if (const auto channel = _history->peer->asMegagroup()) {
  5273. channel->mgInfo->joinedMessageFound = true;
  5274. }
  5275. }
  5276. }, [&](const MTPDmessageActionGiftPremium &data) {
  5277. const auto session = &history()->session();
  5278. _media = std::make_unique<Data::MediaGiftBox>(
  5279. this,
  5280. _from,
  5281. Data::GiftCode{
  5282. .message = (data.vmessage()
  5283. ? Api::ParseTextWithEntities(session, *data.vmessage())
  5284. : TextWithEntities()),
  5285. .count = data.vmonths().v,
  5286. .type = Data::GiftType::Premium,
  5287. });
  5288. }, [&](const MTPDmessageActionSuggestProfilePhoto &data) {
  5289. data.vphoto().match([&](const MTPDphoto &photo) {
  5290. _flags |= MessageFlag::IsUserpicSuggestion;
  5291. _media = std::make_unique<Data::MediaPhoto>(
  5292. this,
  5293. history()->peer,
  5294. history()->owner().processPhoto(photo));
  5295. }, [](const MTPDphotoEmpty &) {
  5296. });
  5297. }, [&](const MTPDmessageActionSetChatWallPaper &data) {
  5298. if (!data.is_same()) {
  5299. using namespace Data;
  5300. const auto session = &history()->session();
  5301. const auto &attached = data.vwallpaper();
  5302. if (const auto paper = WallPaper::Create(session, attached)) {
  5303. _media = std::make_unique<MediaWallPaper>(
  5304. this,
  5305. *paper,
  5306. data.is_for_both());
  5307. }
  5308. }
  5309. }, [&](const MTPDmessageActionGiftCode &data) {
  5310. const auto boostedId = data.vboost_peer()
  5311. ? peerToChannel(peerFromMTP(*data.vboost_peer()))
  5312. : ChannelId();
  5313. _media = std::make_unique<Data::MediaGiftBox>(
  5314. this,
  5315. _from,
  5316. Data::GiftCode{
  5317. .slug = qs(data.vslug()),
  5318. .message = (data.vmessage()
  5319. ? TextWithEntities{
  5320. .text = qs(data.vmessage()->data().vtext()),
  5321. .entities = Api::EntitiesFromMTP(
  5322. &history()->session(),
  5323. data.vmessage()->data().ventities().v),
  5324. }
  5325. : TextWithEntities()),
  5326. .channel = (boostedId
  5327. ? history()->owner().channel(boostedId).get()
  5328. : nullptr),
  5329. .count = data.vmonths().v,
  5330. .type = Data::GiftType::Premium,
  5331. .viaGiveaway = data.is_via_giveaway(),
  5332. .unclaimed = data.is_unclaimed(),
  5333. });
  5334. }, [&](const MTPDmessageActionGiftStars &data) {
  5335. _media = std::make_unique<Data::MediaGiftBox>(
  5336. this,
  5337. _from,
  5338. Data::GiftType::Credits,
  5339. data.vstars().v);
  5340. }, [&](const MTPDmessageActionPrizeStars &data) {
  5341. _media = std::make_unique<Data::MediaGiftBox>(
  5342. this,
  5343. _from,
  5344. Data::GiftCode{
  5345. .slug = qs(data.vtransaction_id()),
  5346. .channel = history()->owner().channel(
  5347. peerToChannel(peerFromMTP(data.vboost_peer()))),
  5348. .giveawayMsgId = data.vgiveaway_msg_id().v,
  5349. .count = int(data.vstars().v),
  5350. .type = Data::GiftType::Credits,
  5351. .viaGiveaway = true,
  5352. .unclaimed = data.is_unclaimed(),
  5353. });
  5354. }, [&](const MTPDmessageActionStarGift &data) {
  5355. const auto service = _from->isServiceUser();
  5356. const auto from = data.vfrom_id()
  5357. ? peerFromMTP(*data.vfrom_id())
  5358. : PeerId();
  5359. const auto to = data.vpeer()
  5360. ? peerFromMTP(*data.vpeer())
  5361. : PeerId();
  5362. using Fields = Data::GiftCode;
  5363. auto fields = Fields{
  5364. .message = (data.vmessage()
  5365. ? TextWithEntities{
  5366. .text = qs(data.vmessage()->data().vtext()),
  5367. .entities = Api::EntitiesFromMTP(
  5368. &history()->session(),
  5369. data.vmessage()->data().ventities().v),
  5370. }
  5371. : TextWithEntities()),
  5372. .channel = ((service && peerIsChannel(to))
  5373. ? history()->owner().channel(peerToChannel(to)).get()
  5374. : nullptr),
  5375. .channelFrom = ((service && from)
  5376. ? history()->owner().peer(from).get()
  5377. : nullptr),
  5378. .channelSavedId = data.vsaved_id().value_or_empty(),
  5379. .upgradeMsgId = data.vupgrade_msg_id().value_or_empty(),
  5380. .starsConverted = int(data.vconvert_stars().value_or_empty()),
  5381. .starsUpgradedBySender = int(
  5382. data.vupgrade_stars().value_or_empty()),
  5383. .type = Data::GiftType::StarGift,
  5384. .upgradable = data.is_can_upgrade(),
  5385. .anonymous = data.is_name_hidden(),
  5386. .converted = data.is_converted(),
  5387. .upgraded = data.is_upgraded(),
  5388. .saved = data.is_saved(),
  5389. };
  5390. if (auto gift = Api::FromTL(&history()->session(), data.vgift())) {
  5391. fields.stargiftId = gift->id;
  5392. fields.starsToUpgrade = gift->starsToUpgrade;
  5393. fields.document = gift->document;
  5394. fields.limitedCount = gift->limitedCount;
  5395. fields.limitedLeft = gift->limitedLeft;
  5396. fields.count = gift->stars;
  5397. fields.unique = gift->unique;
  5398. }
  5399. _media = std::make_unique<Data::MediaGiftBox>(
  5400. this,
  5401. _from,
  5402. std::move(fields));
  5403. }, [&](const MTPDmessageActionStarGiftUnique &data) {
  5404. const auto service = _from->isServiceUser();
  5405. const auto from = data.vfrom_id()
  5406. ? peerFromMTP(*data.vfrom_id())
  5407. : PeerId();
  5408. const auto to = data.vpeer()
  5409. ? peerFromMTP(*data.vpeer())
  5410. : PeerId();
  5411. using Fields = Data::GiftCode;
  5412. auto fields = Fields{
  5413. .channel = ((service && peerIsChannel(to))
  5414. ? history()->owner().channel(peerToChannel(to)).get()
  5415. : nullptr),
  5416. .channelFrom = ((service && from)
  5417. ? history()->owner().peer(from).get()
  5418. : nullptr),
  5419. .channelSavedId = data.vsaved_id().value_or_empty(),
  5420. .type = Data::GiftType::StarGift,
  5421. .transferred = data.is_transferred(),
  5422. .refunded = data.is_refunded(),
  5423. .upgrade = data.is_upgrade(),
  5424. .saved = data.is_saved(),
  5425. };
  5426. if (auto gift = Api::FromTL(&history()->session(), data.vgift())) {
  5427. fields.stargiftId = gift->id;
  5428. fields.document = gift->document;
  5429. fields.limitedCount = gift->limitedCount;
  5430. fields.limitedLeft = gift->limitedLeft;
  5431. fields.count = gift->stars;
  5432. fields.unique = std::move(gift->unique);
  5433. if (const auto unique = fields.unique.get()) {
  5434. unique->starsForTransfer
  5435. = data.vtransfer_stars().value_or(-1);
  5436. unique->exportAt = data.vcan_export_at().value_or_empty();
  5437. }
  5438. }
  5439. _media = std::make_unique<Data::MediaGiftBox>(
  5440. this,
  5441. _from,
  5442. std::move(fields));
  5443. }, [](const auto &) {
  5444. });
  5445. }
  5446. void HistoryItem::setSelfDestruct(
  5447. HistorySelfDestructType type,
  5448. MTPint mtpTTLvalue) {
  5449. UpdateComponents(HistoryServiceSelfDestruct::Bit());
  5450. const auto selfdestruct = Get<HistoryServiceSelfDestruct>();
  5451. if (mtpTTLvalue.v == TimeId(0x7FFFFFFF)) {
  5452. selfdestruct->timeToLive = TimeToLiveSingleView();
  5453. } else {
  5454. selfdestruct->timeToLive = mtpTTLvalue.v * crl::time(1000);
  5455. }
  5456. selfdestruct->type = type;
  5457. }
  5458. PreparedServiceText HistoryItem::prepareInvitedToCallText(
  5459. const std::vector<not_null<UserData*>> &users,
  5460. CallId linkCallId) {
  5461. auto chatText = tr::lng_action_invite_user_chat(
  5462. tr::now,
  5463. Ui::Text::WithEntities);
  5464. auto result = PreparedServiceText();
  5465. result.links.push_back(fromLink());
  5466. auto linkIndex = 1;
  5467. if (linkCallId) {
  5468. const auto peer = _history->peer;
  5469. result.links.push_back(GroupCallClickHandler(peer, linkCallId));
  5470. chatText = Ui::Text::Link(chatText.text, ++linkIndex);
  5471. }
  5472. if (users.size() == 1) {
  5473. auto user = users[0];
  5474. result.links.push_back(user->createOpenLink());
  5475. result.text = tr::lng_action_invite_user(
  5476. tr::now,
  5477. lt_from,
  5478. fromLinkText(), // Link 1.
  5479. lt_user,
  5480. Ui::Text::Link(user->name(), ++linkIndex), // Link N.
  5481. lt_chat,
  5482. chatText,
  5483. Ui::Text::WithEntities);
  5484. } else if (users.empty()) {
  5485. result.text = tr::lng_action_invite_user(
  5486. tr::now,
  5487. lt_from,
  5488. fromLinkText(), // Link 1.
  5489. lt_user,
  5490. { .text = u"somebody"_q },
  5491. lt_chat,
  5492. chatText,
  5493. Ui::Text::WithEntities);
  5494. } else {
  5495. for (auto i = 0, l = int(users.size()); i != l; ++i) {
  5496. const auto user = users[i];
  5497. result.links.push_back(user->createOpenLink());
  5498. auto linkText = Ui::Text::Link(user->name(), ++linkIndex);
  5499. if (i == 0) {
  5500. result.text = linkText;
  5501. } else if (i + 1 == l) {
  5502. result.text = tr::lng_action_invite_users_and_last(
  5503. tr::now,
  5504. lt_accumulated,
  5505. result.text,
  5506. lt_user,
  5507. linkText,
  5508. Ui::Text::WithEntities);
  5509. } else {
  5510. result.text = tr::lng_action_invite_users_and_one(
  5511. tr::now,
  5512. lt_accumulated,
  5513. result.text,
  5514. lt_user,
  5515. linkText,
  5516. Ui::Text::WithEntities);
  5517. }
  5518. }
  5519. result.text = tr::lng_action_invite_users_many(
  5520. tr::now,
  5521. lt_from,
  5522. fromLinkText(), // Link 1.
  5523. lt_users,
  5524. result.text,
  5525. lt_chat,
  5526. chatText,
  5527. Ui::Text::WithEntities);
  5528. }
  5529. return result;
  5530. }
  5531. PreparedServiceText HistoryItem::preparePinnedText() {
  5532. auto result = PreparedServiceText();
  5533. auto pinned = Get<HistoryServicePinned>();
  5534. if (pinned && pinned->msg) {
  5535. const auto mediaText = [&] {
  5536. using TTL = HistoryServiceSelfDestruct;
  5537. if (const auto media = pinned->msg->media()) {
  5538. return media->pinnedTextSubstring();
  5539. } else if (const auto selfdestruct = pinned->msg->Get<TTL>()) {
  5540. if (selfdestruct->type == TTL::Type::Photo) {
  5541. return tr::lng_action_pinned_media_photo(tr::now);
  5542. } else if (selfdestruct->type == TTL::Type::Video) {
  5543. return tr::lng_action_pinned_media_video(tr::now);
  5544. }
  5545. }
  5546. return QString();
  5547. }();
  5548. result.links.push_back(fromLink());
  5549. result.links.push_back(pinned->lnk);
  5550. if (mediaText.isEmpty()) {
  5551. auto original = pinned->msg->translatedText();
  5552. auto cutAt = 0;
  5553. auto limit = kPinnedMessageTextLimit;
  5554. auto size = original.text.size();
  5555. for (; limit != 0;) {
  5556. --limit;
  5557. if (cutAt >= size) break;
  5558. if (original.text.at(cutAt).isLowSurrogate()
  5559. && (cutAt + 1 < size)
  5560. && original.text.at(cutAt + 1).isHighSurrogate()) {
  5561. cutAt += 2;
  5562. } else {
  5563. ++cutAt;
  5564. }
  5565. }
  5566. if (!limit && cutAt + 5 < size) {
  5567. original = Ui::Text::Mid(original, 0, cutAt).append(
  5568. Ui::kQEllipsis);
  5569. }
  5570. original = Ui::Text::Link(
  5571. Ui::Text::Filtered(
  5572. std::move(original),
  5573. {
  5574. EntityType::Spoiler,
  5575. EntityType::StrikeOut,
  5576. EntityType::Italic,
  5577. EntityType::CustomEmoji,
  5578. }),
  5579. 2);
  5580. result.text = tr::lng_action_pinned_message(
  5581. tr::now,
  5582. lt_from,
  5583. fromLinkText(), // Link 1.
  5584. lt_text,
  5585. st::wrap_rtl(original), // Link 2.
  5586. Ui::Text::WithEntities);
  5587. } else {
  5588. result.text = tr::lng_action_pinned_media(
  5589. tr::now,
  5590. lt_from,
  5591. fromLinkText(), // Link 1.
  5592. lt_media,
  5593. Ui::Text::Link(mediaText, 2), // Link 2.
  5594. Ui::Text::WithEntities);
  5595. }
  5596. } else if (pinned && pinned->msgId) {
  5597. result.links.push_back(fromLink());
  5598. result.links.push_back(pinned->lnk);
  5599. result.text = tr::lng_action_pinned_media(
  5600. tr::now,
  5601. lt_from,
  5602. fromLinkText(), // Link 1.
  5603. lt_media,
  5604. Ui::Text::Link(tr::lng_contacts_loading(tr::now), 2), // Link 2.
  5605. Ui::Text::WithEntities);
  5606. } else {
  5607. result.links.push_back(fromLink());
  5608. result.text = tr::lng_action_pinned_media(
  5609. tr::now,
  5610. lt_from,
  5611. fromLinkText(), // Link 1.
  5612. lt_media,
  5613. { .text = tr::lng_deleted_message(tr::now) },
  5614. Ui::Text::WithEntities);
  5615. }
  5616. return result;
  5617. }
  5618. PreparedServiceText HistoryItem::prepareGameScoreText() {
  5619. auto result = PreparedServiceText();
  5620. auto gamescore = Get<HistoryServiceGameScore>();
  5621. auto computeGameTitle = [&]() -> TextWithEntities {
  5622. if (gamescore && gamescore->msg) {
  5623. if (const auto media = gamescore->msg->media()) {
  5624. if (const auto game = media->game()) {
  5625. const auto row = 0;
  5626. const auto column = 0;
  5627. result.links.push_back(
  5628. std::make_shared<ReplyMarkupClickHandler>(
  5629. &_history->owner(),
  5630. row,
  5631. column,
  5632. gamescore->msg->fullId()));
  5633. auto titleText = game->title;
  5634. return Ui::Text::Link(titleText, QString());
  5635. }
  5636. }
  5637. return tr::lng_deleted_message(tr::now, Ui::Text::WithEntities);
  5638. } else if (gamescore && gamescore->msgId) {
  5639. return tr::lng_contacts_loading(tr::now, Ui::Text::WithEntities);
  5640. }
  5641. return {};
  5642. };
  5643. const auto scoreNumber = gamescore ? gamescore->score : 0;
  5644. if (_from->isSelf()) {
  5645. auto gameTitle = computeGameTitle();
  5646. if (gameTitle.text.isEmpty()) {
  5647. result.text = tr::lng_action_game_you_scored_no_game(
  5648. tr::now,
  5649. lt_count,
  5650. scoreNumber,
  5651. Ui::Text::WithEntities);
  5652. } else {
  5653. result.text = tr::lng_action_game_you_scored(
  5654. tr::now,
  5655. lt_count,
  5656. scoreNumber,
  5657. lt_game,
  5658. gameTitle,
  5659. Ui::Text::WithEntities);
  5660. }
  5661. } else {
  5662. result.links.push_back(fromLink());
  5663. auto gameTitle = computeGameTitle();
  5664. if (gameTitle.text.isEmpty()) {
  5665. result.text = tr::lng_action_game_score_no_game(
  5666. tr::now,
  5667. lt_count,
  5668. scoreNumber,
  5669. lt_from,
  5670. fromLinkText(), // Link 1.
  5671. Ui::Text::WithEntities);
  5672. } else {
  5673. result.text = tr::lng_action_game_score(
  5674. tr::now,
  5675. lt_count,
  5676. scoreNumber,
  5677. lt_from,
  5678. fromLinkText(), // Link 1.
  5679. lt_game,
  5680. gameTitle,
  5681. Ui::Text::WithEntities);
  5682. }
  5683. }
  5684. return result;
  5685. }
  5686. PreparedServiceText HistoryItem::preparePaymentSentText() {
  5687. auto result = PreparedServiceText();
  5688. const auto payment = Get<HistoryServicePayment>();
  5689. Assert(payment != nullptr);
  5690. auto invoiceTitle = [&] {
  5691. if (payment->msg) {
  5692. if (const auto media = payment->msg->media()) {
  5693. if (const auto invoice = media->invoice()) {
  5694. return Ui::Text::Link(invoice->title, QString());
  5695. }
  5696. }
  5697. }
  5698. return TextWithEntities();
  5699. }();
  5700. if (invoiceTitle.text.isEmpty()) {
  5701. if (payment->recurringUsed) {
  5702. result.text = tr::lng_action_payment_used_recurring(
  5703. tr::now,
  5704. lt_amount,
  5705. payment->amount,
  5706. Ui::Text::WithEntities);
  5707. } else {
  5708. result.text = (payment->recurringInit
  5709. ? tr::lng_action_payment_init_recurring
  5710. : tr::lng_action_payment_done)(
  5711. tr::now,
  5712. lt_amount,
  5713. payment->amount,
  5714. lt_user,
  5715. { .text = _history->peer->name() },
  5716. Ui::Text::WithEntities);
  5717. }
  5718. } else {
  5719. result.text = (payment->recurringInit
  5720. ? tr::lng_action_payment_init_recurring_for
  5721. : tr::lng_action_payment_done_for)(
  5722. tr::now,
  5723. lt_amount,
  5724. payment->amount,
  5725. lt_user,
  5726. { .text = _history->peer->name() },
  5727. lt_invoice,
  5728. invoiceTitle,
  5729. Ui::Text::WithEntities);
  5730. if (payment->msg) {
  5731. result.links.push_back(payment->lnk);
  5732. }
  5733. }
  5734. return result;
  5735. }
  5736. PreparedServiceText HistoryItem::prepareStoryMentionText() {
  5737. auto result = PreparedServiceText();
  5738. const auto peer = history()->peer;
  5739. result.links.push_back(peer->createOpenLink());
  5740. const auto phrase = (this->media() && this->media()->storyExpired(true))
  5741. ? (out()
  5742. ? tr::lng_action_story_mention_me_unavailable
  5743. : tr::lng_action_story_mention_unavailable)
  5744. : (out()
  5745. ? tr::lng_action_story_mention_me
  5746. : tr::lng_action_story_mention);
  5747. result.text = phrase(
  5748. tr::now,
  5749. lt_user,
  5750. Ui::Text::Wrapped(
  5751. Ui::Text::Bold(peer->shortName()),
  5752. EntityType::CustomUrl,
  5753. u"internal:index"_q + QChar(1)),
  5754. Ui::Text::WithEntities);
  5755. return result;
  5756. }
  5757. PreparedServiceText HistoryItem::prepareCallScheduledText(
  5758. TimeId scheduleDate) {
  5759. const auto call = Get<HistoryServiceOngoingCall>();
  5760. Assert(call != nullptr);
  5761. const auto scheduled = base::unixtime::parse(scheduleDate);
  5762. const auto date = scheduled.date();
  5763. const auto now = QDateTime::currentDateTime();
  5764. const auto secsToDateAddDays = [&](int days) {
  5765. return now.secsTo(QDateTime(date.addDays(days), QTime(0, 0)));
  5766. };
  5767. auto result = PreparedServiceText();
  5768. const auto prepareWithDate = [&](const QString &date) {
  5769. if (_history->peer->isBroadcast()) {
  5770. result.text = tr::lng_action_group_call_scheduled_channel(
  5771. tr::now,
  5772. lt_date,
  5773. { .text = date },
  5774. Ui::Text::WithEntities);
  5775. } else {
  5776. result.links.push_back(fromLink());
  5777. result.text = tr::lng_action_group_call_scheduled_group(
  5778. tr::now,
  5779. lt_from,
  5780. fromLinkText(), // Link 1.
  5781. lt_date,
  5782. { .text = date },
  5783. Ui::Text::WithEntities);
  5784. }
  5785. };
  5786. const auto time = QLocale().toString(
  5787. scheduled.time(),
  5788. QLocale::ShortFormat);
  5789. const auto prepareGeneric = [&] {
  5790. prepareWithDate(tr::lng_group_call_starts_date(
  5791. tr::now,
  5792. lt_date,
  5793. langDayOfMonthFull(date),
  5794. lt_time,
  5795. time));
  5796. };
  5797. auto nextIn = TimeId(0);
  5798. if (now.date().addDays(1) < scheduled.date()) {
  5799. nextIn = secsToDateAddDays(-1);
  5800. prepareGeneric();
  5801. } else if (now.date().addDays(1) == scheduled.date()) {
  5802. nextIn = secsToDateAddDays(0);
  5803. prepareWithDate(
  5804. tr::lng_group_call_starts_tomorrow(tr::now, lt_time, time));
  5805. } else if (now.date() == scheduled.date()) {
  5806. nextIn = secsToDateAddDays(1);
  5807. prepareWithDate(
  5808. tr::lng_group_call_starts_today(tr::now, lt_time, time));
  5809. } else {
  5810. prepareGeneric();
  5811. }
  5812. if (nextIn) {
  5813. call->lifetime = base::timer_once(
  5814. (nextIn + 2) * crl::time(1000)
  5815. ) | rpl::start_with_next([=] {
  5816. updateServiceText(prepareCallScheduledText(scheduleDate));
  5817. });
  5818. }
  5819. return result;
  5820. }
  5821. TextWithEntities HistoryItem::fromLinkText() const {
  5822. return Ui::Text::Link(st::wrap_rtl(_from->name()), 1);
  5823. }
  5824. ClickHandlerPtr HistoryItem::fromLink() const {
  5825. return _from->createOpenLink();
  5826. }
  5827. crl::time HistoryItem::getSelfDestructIn(crl::time now) {
  5828. if (const auto selfdestruct = Get<HistoryServiceSelfDestruct>()) {
  5829. const auto at = std::get_if<crl::time>(&selfdestruct->destructAt);
  5830. if (at && (*at) > 0) {
  5831. const auto destruct = *at;
  5832. if (destruct <= now) {
  5833. auto text = [&] {
  5834. switch (selfdestruct->type) {
  5835. case HistoryServiceSelfDestruct::Type::Photo:
  5836. return tr::lng_ttl_photo_expired(tr::now);
  5837. case HistoryServiceSelfDestruct::Type::Video:
  5838. return tr::lng_ttl_video_expired(tr::now);
  5839. }
  5840. Unexpected("Type in HistoryServiceSelfDestruct::Type");
  5841. };
  5842. setServiceText({ TextWithEntities{ .text = text() } });
  5843. return 0;
  5844. }
  5845. return destruct - now;
  5846. }
  5847. }
  5848. return 0;
  5849. }
  5850. void HistoryItem::cacheOnlyEmojiAndSpaces(bool only) {
  5851. _flags |= MessageFlag::OnlyEmojiAndSpacesSet;
  5852. if (only) {
  5853. _flags |= MessageFlag::OnlyEmojiAndSpaces;
  5854. } else {
  5855. _flags &= ~MessageFlag::OnlyEmojiAndSpaces;
  5856. }
  5857. }
  5858. bool HistoryItem::isOnlyEmojiAndSpaces() const {
  5859. if (!(_flags & MessageFlag::OnlyEmojiAndSpacesSet)) {
  5860. const_cast<HistoryItem*>(this)->cacheOnlyEmojiAndSpaces(
  5861. !HasNotEmojiAndSpaces(_text.text));
  5862. }
  5863. return (_flags & MessageFlag::OnlyEmojiAndSpaces);
  5864. }
  5865. void HistoryItem::setupChatThemeChange() {
  5866. if (const auto user = history()->peer->asUser()) {
  5867. auto link = std::make_shared<LambdaClickHandler>([=](
  5868. ClickContext context) {
  5869. const auto my = context.other.value<ClickHandlerContext>();
  5870. if (const auto controller = my.sessionWindow.get()) {
  5871. controller->toggleChooseChatTheme(user);
  5872. }
  5873. });
  5874. UpdateComponents(HistoryServiceChatThemeChange::Bit());
  5875. Get<HistoryServiceChatThemeChange>()->link = std::move(link);
  5876. } else {
  5877. RemoveComponents(HistoryServiceChatThemeChange::Bit());
  5878. }
  5879. }
  5880. void HistoryItem::setupTTLChange() {
  5881. const auto peer = history()->peer;
  5882. auto link = std::make_shared<LambdaClickHandler>([=](
  5883. ClickContext context) {
  5884. const auto my = context.other.value<ClickHandlerContext>();
  5885. if (const auto controller = my.sessionWindow.get()) {
  5886. const auto validator = TTLMenu::TTLValidator(
  5887. controller->uiShow(),
  5888. peer);
  5889. if (validator.can()) {
  5890. validator.showBox();
  5891. }
  5892. }
  5893. });
  5894. UpdateComponents(HistoryServiceTTLChange::Bit());
  5895. Get<HistoryServiceTTLChange>()->link = std::move(link);
  5896. }
  5897. void HistoryItem::clearDependencyMessage() {
  5898. if (const auto dependent = GetServiceDependentData()) {
  5899. if (dependent->msg) {
  5900. _history->owner().unregisterDependentMessage(
  5901. this,
  5902. dependent->msg);
  5903. dependent->msg = nullptr;
  5904. dependent->msgId = 0;
  5905. }
  5906. }
  5907. }
  5908. void HistoryItem::overrideMedia(std::unique_ptr<Data::Media> media) {
  5909. Expects(!media || media->parent() == this);
  5910. _media = std::move(media);
  5911. }