portal.go 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/rand"
  21. "crypto/sha256"
  22. "encoding/hex"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "image"
  27. "image/color"
  28. _ "image/gif"
  29. "image/jpeg"
  30. "image/png"
  31. "io"
  32. "math"
  33. "mime"
  34. "net/http"
  35. "reflect"
  36. "runtime/debug"
  37. "strconv"
  38. "strings"
  39. "sync"
  40. "time"
  41. cwebp "github.com/chai2010/webp"
  42. "github.com/rs/zerolog"
  43. "github.com/tidwall/gjson"
  44. "go.mau.fi/util/dbutil"
  45. "go.mau.fi/util/exerrors"
  46. "go.mau.fi/util/exmime"
  47. "go.mau.fi/util/ffmpeg"
  48. "go.mau.fi/util/jsontime"
  49. "go.mau.fi/util/random"
  50. "go.mau.fi/util/variationselector"
  51. "go.mau.fi/whatsmeow"
  52. waProto "go.mau.fi/whatsmeow/binary/proto"
  53. "go.mau.fi/whatsmeow/types"
  54. "go.mau.fi/whatsmeow/types/events"
  55. "golang.org/x/exp/slices"
  56. "golang.org/x/image/draw"
  57. "golang.org/x/image/webp"
  58. "google.golang.org/protobuf/proto"
  59. log "maunium.net/go/maulogger/v2"
  60. "maunium.net/go/mautrix"
  61. "maunium.net/go/mautrix/appservice"
  62. "maunium.net/go/mautrix/bridge"
  63. "maunium.net/go/mautrix/bridge/bridgeconfig"
  64. "maunium.net/go/mautrix/bridge/status"
  65. "maunium.net/go/mautrix/crypto/attachment"
  66. "maunium.net/go/mautrix/event"
  67. "maunium.net/go/mautrix/format"
  68. "maunium.net/go/mautrix/id"
  69. "maunium.net/go/mautrix-whatsapp/database"
  70. )
  71. const StatusBroadcastTopic = "WhatsApp status updates from your contacts"
  72. const StatusBroadcastName = "WhatsApp Status Broadcast"
  73. const BroadcastTopic = "WhatsApp broadcast list"
  74. const UnnamedBroadcastName = "Unnamed broadcast list"
  75. const PrivateChatTopic = "WhatsApp private chat"
  76. var ErrStatusBroadcastDisabled = errors.New("status bridging is disabled")
  77. func (br *WABridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  78. br.portalsLock.Lock()
  79. defer br.portalsLock.Unlock()
  80. portal, ok := br.portalsByMXID[mxid]
  81. if !ok {
  82. return br.loadDBPortal(br.DB.Portal.GetByMXID(mxid), nil)
  83. }
  84. return portal
  85. }
  86. func (br *WABridge) GetIPortal(mxid id.RoomID) bridge.Portal {
  87. p := br.GetPortalByMXID(mxid)
  88. if p == nil {
  89. return nil
  90. }
  91. return p
  92. }
  93. func (portal *Portal) IsEncrypted() bool {
  94. return portal.Encrypted
  95. }
  96. func (portal *Portal) MarkEncrypted() {
  97. portal.Encrypted = true
  98. portal.Update(nil)
  99. }
  100. func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
  101. if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser || portal.HasRelaybot() {
  102. portal.matrixMessages <- PortalMatrixMessage{user: user.(*User), evt: evt, receivedAt: time.Now()}
  103. }
  104. }
  105. func (br *WABridge) GetPortalByJID(key database.PortalKey) *Portal {
  106. br.portalsLock.Lock()
  107. defer br.portalsLock.Unlock()
  108. portal, ok := br.portalsByJID[key]
  109. if !ok {
  110. return br.loadDBPortal(br.DB.Portal.GetByJID(key), &key)
  111. }
  112. return portal
  113. }
  114. func (br *WABridge) GetExistingPortalByJID(key database.PortalKey) *Portal {
  115. br.portalsLock.Lock()
  116. defer br.portalsLock.Unlock()
  117. portal, ok := br.portalsByJID[key]
  118. if !ok {
  119. return br.loadDBPortal(br.DB.Portal.GetByJID(key), nil)
  120. }
  121. return portal
  122. }
  123. func (br *WABridge) GetAllPortals() []*Portal {
  124. return br.dbPortalsToPortals(br.DB.Portal.GetAll())
  125. }
  126. func (br *WABridge) GetAllIPortals() (iportals []bridge.Portal) {
  127. portals := br.GetAllPortals()
  128. iportals = make([]bridge.Portal, len(portals))
  129. for i, portal := range portals {
  130. iportals[i] = portal
  131. }
  132. return iportals
  133. }
  134. func (br *WABridge) GetAllPortalsByJID(jid types.JID) []*Portal {
  135. return br.dbPortalsToPortals(br.DB.Portal.GetAllByJID(jid))
  136. }
  137. func (br *WABridge) GetAllByParentGroup(jid types.JID) []*Portal {
  138. return br.dbPortalsToPortals(br.DB.Portal.GetAllByParentGroup(jid))
  139. }
  140. func (br *WABridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  141. br.portalsLock.Lock()
  142. defer br.portalsLock.Unlock()
  143. output := make([]*Portal, len(dbPortals))
  144. for index, dbPortal := range dbPortals {
  145. if dbPortal == nil {
  146. continue
  147. }
  148. portal, ok := br.portalsByJID[dbPortal.Key]
  149. if !ok {
  150. portal = br.loadDBPortal(dbPortal, nil)
  151. }
  152. output[index] = portal
  153. }
  154. return output
  155. }
  156. func (br *WABridge) loadDBPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
  157. if dbPortal == nil {
  158. if key == nil {
  159. return nil
  160. }
  161. dbPortal = br.DB.Portal.New()
  162. dbPortal.Key = *key
  163. dbPortal.Insert()
  164. }
  165. portal := br.NewPortal(dbPortal)
  166. br.portalsByJID[portal.Key] = portal
  167. if len(portal.MXID) > 0 {
  168. br.portalsByMXID[portal.MXID] = portal
  169. }
  170. return portal
  171. }
  172. func (portal *Portal) GetUsers() []*User {
  173. return nil
  174. }
  175. func (br *WABridge) newBlankPortal(key database.PortalKey) *Portal {
  176. portal := &Portal{
  177. bridge: br,
  178. log: br.Log.Sub(fmt.Sprintf("Portal/%s", key)),
  179. zlog: br.ZLog.With().Str("portal_key", key.String()).Logger(),
  180. messages: make(chan PortalMessage, br.Config.Bridge.PortalMessageBuffer),
  181. matrixMessages: make(chan PortalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
  182. mediaRetries: make(chan PortalMediaRetry, br.Config.Bridge.PortalMessageBuffer),
  183. mediaErrorCache: make(map[types.MessageID]*FailedMediaMeta),
  184. }
  185. go portal.handleMessageLoop()
  186. return portal
  187. }
  188. func (br *WABridge) NewManualPortal(key database.PortalKey) *Portal {
  189. portal := br.newBlankPortal(key)
  190. portal.Portal = br.DB.Portal.New()
  191. portal.Key = key
  192. return portal
  193. }
  194. func (br *WABridge) NewPortal(dbPortal *database.Portal) *Portal {
  195. portal := br.newBlankPortal(dbPortal.Key)
  196. portal.Portal = dbPortal
  197. return portal
  198. }
  199. const recentlyHandledLength = 100
  200. type fakeMessage struct {
  201. Sender types.JID
  202. Text string
  203. ID string
  204. Time time.Time
  205. Important bool
  206. }
  207. type PortalMessage struct {
  208. evt *events.Message
  209. undecryptable *events.UndecryptableMessage
  210. receipt *events.Receipt
  211. fake *fakeMessage
  212. source *User
  213. }
  214. type PortalMatrixMessage struct {
  215. evt *event.Event
  216. user *User
  217. receivedAt time.Time
  218. }
  219. type PortalMediaRetry struct {
  220. evt *events.MediaRetry
  221. source *User
  222. }
  223. type recentlyHandledWrapper struct {
  224. id types.MessageID
  225. err database.MessageErrorType
  226. }
  227. type Portal struct {
  228. *database.Portal
  229. bridge *WABridge
  230. // Deprecated: use zerolog
  231. log log.Logger
  232. zlog zerolog.Logger
  233. roomCreateLock sync.Mutex
  234. encryptLock sync.Mutex
  235. backfillLock sync.Mutex
  236. avatarLock sync.Mutex
  237. latestEventBackfillLock sync.Mutex
  238. parentGroupUpdateLock sync.Mutex
  239. recentlyHandled [recentlyHandledLength]recentlyHandledWrapper
  240. recentlyHandledLock sync.Mutex
  241. recentlyHandledIndex uint8
  242. currentlyTyping []id.UserID
  243. currentlyTypingLock sync.Mutex
  244. messages chan PortalMessage
  245. matrixMessages chan PortalMatrixMessage
  246. mediaRetries chan PortalMediaRetry
  247. mediaErrorCache map[types.MessageID]*FailedMediaMeta
  248. galleryCache []*event.MessageEventContent
  249. galleryCacheRootEvent id.EventID
  250. galleryCacheStart time.Time
  251. galleryCacheReplyTo *ReplyInfo
  252. galleryCacheSender types.JID
  253. currentlySleepingToDelete sync.Map
  254. relayUser *User
  255. parentPortal *Portal
  256. }
  257. const GalleryMaxTime = 10 * time.Minute
  258. func (portal *Portal) stopGallery() {
  259. if portal.galleryCache != nil {
  260. portal.galleryCache = nil
  261. portal.galleryCacheSender = types.EmptyJID
  262. portal.galleryCacheReplyTo = nil
  263. portal.galleryCacheStart = time.Time{}
  264. portal.galleryCacheRootEvent = ""
  265. }
  266. }
  267. func (portal *Portal) startGallery(evt *events.Message, msg *ConvertedMessage) {
  268. portal.galleryCache = []*event.MessageEventContent{msg.Content}
  269. portal.galleryCacheSender = evt.Info.Sender.ToNonAD()
  270. portal.galleryCacheReplyTo = msg.ReplyTo
  271. portal.galleryCacheStart = time.Now()
  272. }
  273. func (portal *Portal) extendGallery(msg *ConvertedMessage) int {
  274. portal.galleryCache = append(portal.galleryCache, msg.Content)
  275. msg.Content = &event.MessageEventContent{
  276. MsgType: event.MsgBeeperGallery,
  277. Body: "Sent a gallery",
  278. BeeperGalleryImages: portal.galleryCache,
  279. }
  280. msg.Content.SetEdit(portal.galleryCacheRootEvent)
  281. // Don't set the gallery images in the edit fallback
  282. msg.Content.BeeperGalleryImages = nil
  283. return len(portal.galleryCache) - 1
  284. }
  285. var (
  286. _ bridge.Portal = (*Portal)(nil)
  287. _ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
  288. _ bridge.MembershipHandlingPortal = (*Portal)(nil)
  289. _ bridge.MetaHandlingPortal = (*Portal)(nil)
  290. _ bridge.TypingPortal = (*Portal)(nil)
  291. )
  292. func (portal *Portal) handleWhatsAppMessageLoopItem(msg PortalMessage) {
  293. if len(portal.MXID) == 0 {
  294. if msg.fake == nil && msg.undecryptable == nil && (msg.evt == nil || !containsSupportedMessage(msg.evt.Message)) {
  295. portal.log.Debugln("Not creating portal room for incoming message: message is not a chat message")
  296. return
  297. }
  298. portal.log.Debugln("Creating Matrix room from incoming message")
  299. err := portal.CreateMatrixRoom(msg.source, nil, false, true)
  300. if err != nil {
  301. portal.log.Errorln("Failed to create portal room:", err)
  302. return
  303. }
  304. }
  305. portal.latestEventBackfillLock.Lock()
  306. defer portal.latestEventBackfillLock.Unlock()
  307. switch {
  308. case msg.evt != nil:
  309. portal.handleMessage(msg.source, msg.evt, false)
  310. case msg.receipt != nil:
  311. portal.handleReceipt(msg.receipt, msg.source)
  312. case msg.undecryptable != nil:
  313. portal.stopGallery()
  314. portal.handleUndecryptableMessage(msg.source, msg.undecryptable)
  315. case msg.fake != nil:
  316. portal.stopGallery()
  317. msg.fake.ID = "FAKE::" + msg.fake.ID
  318. portal.handleFakeMessage(*msg.fake)
  319. default:
  320. portal.log.Warnln("Unexpected PortalMessage with no message: %+v", msg)
  321. }
  322. }
  323. func (portal *Portal) handleMatrixMessageLoopItem(msg PortalMatrixMessage) {
  324. portal.latestEventBackfillLock.Lock()
  325. defer portal.latestEventBackfillLock.Unlock()
  326. evtTS := time.UnixMilli(msg.evt.Timestamp)
  327. timings := messageTimings{
  328. initReceive: msg.evt.Mautrix.ReceivedAt.Sub(evtTS),
  329. decrypt: msg.evt.Mautrix.DecryptionDuration,
  330. portalQueue: time.Since(msg.receivedAt),
  331. totalReceive: time.Since(evtTS),
  332. }
  333. implicitRRStart := time.Now()
  334. portal.handleMatrixReadReceipt(msg.user, "", evtTS, false)
  335. timings.implicitRR = time.Since(implicitRRStart)
  336. switch msg.evt.Type {
  337. case event.EventMessage, event.EventSticker, TypeMSC3381V2PollResponse, TypeMSC3381PollResponse, TypeMSC3381PollStart:
  338. portal.HandleMatrixMessage(msg.user, msg.evt, timings)
  339. case event.EventRedaction:
  340. portal.HandleMatrixRedaction(msg.user, msg.evt)
  341. case event.EventReaction:
  342. portal.HandleMatrixReaction(msg.user, msg.evt)
  343. default:
  344. portal.log.Warnln("Unsupported event type %+v in portal message channel", msg.evt.Type)
  345. }
  346. }
  347. func (portal *Portal) handleDeliveryReceipt(receipt *events.Receipt, source *User) {
  348. if !portal.IsPrivateChat() {
  349. return
  350. }
  351. for _, msgID := range receipt.MessageIDs {
  352. msg := portal.bridge.DB.Message.GetByJID(portal.Key, msgID)
  353. if msg == nil || msg.IsFakeMXID() {
  354. continue
  355. }
  356. if msg.Sender == source.JID {
  357. portal.bridge.SendRawMessageCheckpoint(&status.MessageCheckpoint{
  358. EventID: msg.MXID,
  359. RoomID: portal.MXID,
  360. Step: status.MsgStepRemote,
  361. Timestamp: jsontime.UM(receipt.Timestamp),
  362. Status: status.MsgStatusDelivered,
  363. ReportedBy: status.MsgReportedByBridge,
  364. })
  365. portal.sendStatusEvent(msg.MXID, "", nil, &[]id.UserID{portal.MainIntent().UserID})
  366. }
  367. }
  368. }
  369. func (portal *Portal) handleReceipt(receipt *events.Receipt, source *User) {
  370. if receipt.Sender.Server != types.DefaultUserServer {
  371. // TODO handle lids
  372. return
  373. }
  374. if receipt.Type == events.ReceiptTypeDelivered {
  375. portal.handleDeliveryReceipt(receipt, source)
  376. return
  377. }
  378. // The order of the message ID array depends on the sender's platform, so we just have to find
  379. // the last message based on timestamp. Also, timestamps only have second precision, so if
  380. // there are many messages at the same second just mark them all as read, because we don't
  381. // know which one is last
  382. markAsRead := make([]*database.Message, 0, 1)
  383. var bestTimestamp time.Time
  384. for _, msgID := range receipt.MessageIDs {
  385. msg := portal.bridge.DB.Message.GetByJID(portal.Key, msgID)
  386. if msg == nil || msg.IsFakeMXID() {
  387. continue
  388. }
  389. if msg.Timestamp.After(bestTimestamp) {
  390. bestTimestamp = msg.Timestamp
  391. markAsRead = append(markAsRead[:0], msg)
  392. } else if msg != nil && msg.Timestamp.Equal(bestTimestamp) {
  393. markAsRead = append(markAsRead, msg)
  394. }
  395. }
  396. if receipt.Sender.User == source.JID.User {
  397. if len(markAsRead) > 0 {
  398. source.SetLastReadTS(portal.Key, markAsRead[0].Timestamp)
  399. } else {
  400. source.SetLastReadTS(portal.Key, receipt.Timestamp)
  401. }
  402. }
  403. intent := portal.bridge.GetPuppetByJID(receipt.Sender).IntentFor(portal)
  404. for _, msg := range markAsRead {
  405. err := intent.SetReadMarkers(portal.MXID, source.makeReadMarkerContent(msg.MXID, intent.IsCustomPuppet))
  406. if err != nil {
  407. portal.log.Warnfln("Failed to mark message %s as read by %s: %v", msg.MXID, intent.UserID, err)
  408. } else {
  409. portal.log.Debugfln("Marked %s as read by %s", msg.MXID, intent.UserID)
  410. }
  411. }
  412. }
  413. func (portal *Portal) handleMessageLoop() {
  414. for {
  415. portal.handleOneMessageLoopItem()
  416. }
  417. }
  418. func (portal *Portal) handleOneMessageLoopItem() {
  419. defer func() {
  420. if err := recover(); err != nil {
  421. logEvt := portal.zlog.WithLevel(zerolog.FatalLevel).
  422. Str(zerolog.ErrorStackFieldName, string(debug.Stack()))
  423. actualErr, ok := err.(error)
  424. if ok {
  425. logEvt = logEvt.Err(actualErr)
  426. } else {
  427. logEvt = logEvt.Any(zerolog.ErrorFieldName, err)
  428. }
  429. logEvt.Msg("Portal message handler panicked")
  430. }
  431. }()
  432. select {
  433. case msg := <-portal.messages:
  434. portal.handleWhatsAppMessageLoopItem(msg)
  435. case msg := <-portal.matrixMessages:
  436. portal.handleMatrixMessageLoopItem(msg)
  437. case retry := <-portal.mediaRetries:
  438. portal.handleMediaRetry(retry.evt, retry.source)
  439. }
  440. }
  441. func containsSupportedMessage(waMsg *waProto.Message) bool {
  442. if waMsg == nil {
  443. return false
  444. }
  445. return waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil || waMsg.ImageMessage != nil ||
  446. waMsg.StickerMessage != nil || waMsg.AudioMessage != nil || waMsg.VideoMessage != nil || waMsg.PtvMessage != nil ||
  447. waMsg.DocumentMessage != nil || waMsg.ContactMessage != nil || waMsg.LocationMessage != nil ||
  448. waMsg.LiveLocationMessage != nil || waMsg.GroupInviteMessage != nil || waMsg.ContactsArrayMessage != nil ||
  449. waMsg.HighlyStructuredMessage != nil || waMsg.TemplateMessage != nil || waMsg.TemplateButtonReplyMessage != nil ||
  450. waMsg.ListMessage != nil || waMsg.ListResponseMessage != nil || waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil
  451. }
  452. func getMessageType(waMsg *waProto.Message) string {
  453. switch {
  454. case waMsg == nil:
  455. return "ignore"
  456. case waMsg.Conversation != nil, waMsg.ExtendedTextMessage != nil:
  457. return "text"
  458. case waMsg.ImageMessage != nil:
  459. return fmt.Sprintf("image %s", waMsg.GetImageMessage().GetMimetype())
  460. case waMsg.StickerMessage != nil:
  461. return fmt.Sprintf("sticker %s", waMsg.GetStickerMessage().GetMimetype())
  462. case waMsg.VideoMessage != nil:
  463. return fmt.Sprintf("video %s", waMsg.GetVideoMessage().GetMimetype())
  464. case waMsg.PtvMessage != nil:
  465. return fmt.Sprintf("round video %s", waMsg.GetPtvMessage().GetMimetype())
  466. case waMsg.AudioMessage != nil:
  467. return fmt.Sprintf("audio %s", waMsg.GetAudioMessage().GetMimetype())
  468. case waMsg.DocumentMessage != nil:
  469. return fmt.Sprintf("document %s", waMsg.GetDocumentMessage().GetMimetype())
  470. case waMsg.ContactMessage != nil:
  471. return "contact"
  472. case waMsg.ContactsArrayMessage != nil:
  473. return "contact array"
  474. case waMsg.LocationMessage != nil:
  475. return "location"
  476. case waMsg.LiveLocationMessage != nil:
  477. return "live location start"
  478. case waMsg.GroupInviteMessage != nil:
  479. return "group invite"
  480. case waMsg.ReactionMessage != nil:
  481. return "reaction"
  482. case waMsg.EncReactionMessage != nil:
  483. return "encrypted reaction"
  484. case waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil || waMsg.PollCreationMessageV3 != nil:
  485. return "poll create"
  486. case waMsg.PollUpdateMessage != nil:
  487. return "poll update"
  488. case waMsg.ProtocolMessage != nil:
  489. switch waMsg.GetProtocolMessage().GetType() {
  490. case waProto.ProtocolMessage_REVOKE:
  491. if waMsg.GetProtocolMessage().GetKey() == nil {
  492. return "ignore"
  493. }
  494. return "revoke"
  495. case waProto.ProtocolMessage_MESSAGE_EDIT:
  496. return "edit"
  497. case waProto.ProtocolMessage_EPHEMERAL_SETTING:
  498. return "disappearing timer change"
  499. case waProto.ProtocolMessage_APP_STATE_SYNC_KEY_SHARE, waProto.ProtocolMessage_HISTORY_SYNC_NOTIFICATION, waProto.ProtocolMessage_INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC:
  500. return "ignore"
  501. default:
  502. return fmt.Sprintf("unknown_protocol_%d", waMsg.GetProtocolMessage().GetType())
  503. }
  504. case waMsg.ButtonsMessage != nil:
  505. return "buttons"
  506. case waMsg.ButtonsResponseMessage != nil:
  507. return "buttons response"
  508. case waMsg.TemplateMessage != nil:
  509. return "template"
  510. case waMsg.HighlyStructuredMessage != nil:
  511. return "highly structured template"
  512. case waMsg.TemplateButtonReplyMessage != nil:
  513. return "template button reply"
  514. case waMsg.InteractiveMessage != nil:
  515. return "interactive"
  516. case waMsg.ListMessage != nil:
  517. return "list"
  518. case waMsg.ProductMessage != nil:
  519. return "product"
  520. case waMsg.ListResponseMessage != nil:
  521. return "list response"
  522. case waMsg.OrderMessage != nil:
  523. return "order"
  524. case waMsg.InvoiceMessage != nil:
  525. return "invoice"
  526. case waMsg.SendPaymentMessage != nil, waMsg.RequestPaymentMessage != nil,
  527. waMsg.DeclinePaymentRequestMessage != nil, waMsg.CancelPaymentRequestMessage != nil,
  528. waMsg.PaymentInviteMessage != nil:
  529. return "payment"
  530. case waMsg.Call != nil:
  531. return "call"
  532. case waMsg.Chat != nil:
  533. return "chat"
  534. case waMsg.SenderKeyDistributionMessage != nil, waMsg.StickerSyncRmrMessage != nil:
  535. return "ignore"
  536. default:
  537. return "unknown"
  538. }
  539. }
  540. func pluralUnit(val int, name string) string {
  541. if val == 1 {
  542. return fmt.Sprintf("%d %s", val, name)
  543. } else if val == 0 {
  544. return ""
  545. }
  546. return fmt.Sprintf("%d %ss", val, name)
  547. }
  548. func naturalJoin(parts []string) string {
  549. if len(parts) == 0 {
  550. return ""
  551. } else if len(parts) == 1 {
  552. return parts[0]
  553. } else if len(parts) == 2 {
  554. return fmt.Sprintf("%s and %s", parts[0], parts[1])
  555. } else {
  556. return fmt.Sprintf("%s and %s", strings.Join(parts[:len(parts)-1], ", "), parts[len(parts)-1])
  557. }
  558. }
  559. func formatDuration(d time.Duration) string {
  560. const Day = time.Hour * 24
  561. var days, hours, minutes, seconds int
  562. days, d = int(d/Day), d%Day
  563. hours, d = int(d/time.Hour), d%time.Hour
  564. minutes, d = int(d/time.Minute), d%time.Minute
  565. seconds = int(d / time.Second)
  566. parts := make([]string, 0, 4)
  567. if days > 0 {
  568. parts = append(parts, pluralUnit(days, "day"))
  569. }
  570. if hours > 0 {
  571. parts = append(parts, pluralUnit(hours, "hour"))
  572. }
  573. if minutes > 0 {
  574. parts = append(parts, pluralUnit(seconds, "minute"))
  575. }
  576. if seconds > 0 {
  577. parts = append(parts, pluralUnit(seconds, "second"))
  578. }
  579. return naturalJoin(parts)
  580. }
  581. func (portal *Portal) convertMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, waMsg *waProto.Message, isBackfill bool) *ConvertedMessage {
  582. switch {
  583. case waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil:
  584. return portal.convertTextMessage(intent, source, waMsg)
  585. case waMsg.TemplateMessage != nil:
  586. return portal.convertTemplateMessage(intent, source, info, waMsg.GetTemplateMessage())
  587. case waMsg.HighlyStructuredMessage != nil:
  588. return portal.convertTemplateMessage(intent, source, info, waMsg.GetHighlyStructuredMessage().GetHydratedHsm())
  589. case waMsg.TemplateButtonReplyMessage != nil:
  590. return portal.convertTemplateButtonReplyMessage(intent, waMsg.GetTemplateButtonReplyMessage())
  591. case waMsg.ListMessage != nil:
  592. return portal.convertListMessage(intent, source, waMsg.GetListMessage())
  593. case waMsg.ListResponseMessage != nil:
  594. return portal.convertListResponseMessage(intent, waMsg.GetListResponseMessage())
  595. case waMsg.PollCreationMessage != nil:
  596. return portal.convertPollCreationMessage(intent, waMsg.GetPollCreationMessage())
  597. case waMsg.PollCreationMessageV2 != nil:
  598. return portal.convertPollCreationMessage(intent, waMsg.GetPollCreationMessageV2())
  599. case waMsg.PollCreationMessageV3 != nil:
  600. return portal.convertPollCreationMessage(intent, waMsg.GetPollCreationMessageV3())
  601. case waMsg.PollUpdateMessage != nil:
  602. return portal.convertPollUpdateMessage(intent, source, info, waMsg.GetPollUpdateMessage())
  603. case waMsg.ImageMessage != nil:
  604. return portal.convertMediaMessage(intent, source, info, waMsg.GetImageMessage(), "photo", isBackfill)
  605. case waMsg.StickerMessage != nil:
  606. return portal.convertMediaMessage(intent, source, info, waMsg.GetStickerMessage(), "sticker", isBackfill)
  607. case waMsg.VideoMessage != nil:
  608. return portal.convertMediaMessage(intent, source, info, waMsg.GetVideoMessage(), "video attachment", isBackfill)
  609. case waMsg.PtvMessage != nil:
  610. return portal.convertMediaMessage(intent, source, info, waMsg.GetPtvMessage(), "video message", isBackfill)
  611. case waMsg.AudioMessage != nil:
  612. typeName := "audio attachment"
  613. if waMsg.GetAudioMessage().GetPtt() {
  614. typeName = "voice message"
  615. }
  616. return portal.convertMediaMessage(intent, source, info, waMsg.GetAudioMessage(), typeName, isBackfill)
  617. case waMsg.DocumentMessage != nil:
  618. return portal.convertMediaMessage(intent, source, info, waMsg.GetDocumentMessage(), "file attachment", isBackfill)
  619. case waMsg.ContactMessage != nil:
  620. return portal.convertContactMessage(intent, waMsg.GetContactMessage())
  621. case waMsg.ContactsArrayMessage != nil:
  622. return portal.convertContactsArrayMessage(intent, waMsg.GetContactsArrayMessage())
  623. case waMsg.LocationMessage != nil:
  624. return portal.convertLocationMessage(intent, waMsg.GetLocationMessage())
  625. case waMsg.LiveLocationMessage != nil:
  626. return portal.convertLiveLocationMessage(intent, waMsg.GetLiveLocationMessage())
  627. case waMsg.GroupInviteMessage != nil:
  628. return portal.convertGroupInviteMessage(intent, info, waMsg.GetGroupInviteMessage())
  629. case waMsg.ProtocolMessage != nil && waMsg.ProtocolMessage.GetType() == waProto.ProtocolMessage_EPHEMERAL_SETTING:
  630. portal.ExpirationTime = waMsg.ProtocolMessage.GetEphemeralExpiration()
  631. portal.Update(nil)
  632. return &ConvertedMessage{
  633. Intent: intent,
  634. Type: event.EventMessage,
  635. Content: &event.MessageEventContent{
  636. Body: portal.formatDisappearingMessageNotice(),
  637. MsgType: event.MsgNotice,
  638. },
  639. }
  640. default:
  641. return nil
  642. }
  643. }
  644. func (portal *Portal) implicitlyEnableDisappearingMessages(timer time.Duration) {
  645. portal.ExpirationTime = uint32(timer.Seconds())
  646. portal.Update(nil)
  647. intent := portal.MainIntent()
  648. if portal.Encrypted {
  649. intent = portal.bridge.Bot
  650. }
  651. duration := formatDuration(time.Duration(portal.ExpirationTime) * time.Second)
  652. _, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  653. MsgType: event.MsgNotice,
  654. Body: fmt.Sprintf("Automatically enabled disappearing message timer (%s) because incoming message is disappearing", duration),
  655. }, nil, 0)
  656. if err != nil {
  657. portal.zlog.Warn().Err(err).Msg("Failed to send notice about implicit disappearing timer")
  658. }
  659. }
  660. func (portal *Portal) UpdateGroupDisappearingMessages(sender *types.JID, timestamp time.Time, timer uint32) {
  661. if portal.ExpirationTime == timer {
  662. return
  663. }
  664. portal.ExpirationTime = timer
  665. portal.Update(nil)
  666. intent := portal.MainIntent()
  667. if sender != nil && sender.Server == types.DefaultUserServer {
  668. intent = portal.bridge.GetPuppetByJID(sender.ToNonAD()).IntentFor(portal)
  669. } else {
  670. sender = &types.EmptyJID
  671. }
  672. _, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  673. Body: portal.formatDisappearingMessageNotice(),
  674. MsgType: event.MsgNotice,
  675. }, nil, timestamp.UnixMilli())
  676. if err != nil {
  677. portal.log.Warnfln("Failed to notify portal about disappearing message timer change by %s to %d", *sender, timer)
  678. }
  679. }
  680. func (portal *Portal) formatDisappearingMessageNotice() string {
  681. if portal.ExpirationTime == 0 {
  682. return "Turned off disappearing messages"
  683. }
  684. return fmt.Sprintf("Set the disappearing message timer to %s", formatDuration(time.Duration(portal.ExpirationTime)*time.Second))
  685. }
  686. const UndecryptableMessageNotice = "Decrypting message from WhatsApp failed, waiting for sender to re-send... " +
  687. "([learn more](https://faq.whatsapp.com/general/security-and-privacy/seeing-waiting-for-this-message-this-may-take-a-while))"
  688. var undecryptableMessageContent event.MessageEventContent
  689. func init() {
  690. undecryptableMessageContent = format.RenderMarkdown(UndecryptableMessageNotice, true, false)
  691. undecryptableMessageContent.MsgType = event.MsgNotice
  692. }
  693. func (portal *Portal) handleUndecryptableMessage(source *User, evt *events.UndecryptableMessage) {
  694. if len(portal.MXID) == 0 {
  695. portal.log.Warnln("handleUndecryptableMessage called even though portal.MXID is empty")
  696. return
  697. } else if portal.isRecentlyHandled(evt.Info.ID, database.MsgErrDecryptionFailed) {
  698. portal.log.Debugfln("Not handling %s (undecryptable): message was recently handled", evt.Info.ID)
  699. return
  700. } else if existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, evt.Info.ID); existingMsg != nil {
  701. portal.log.Debugfln("Not handling %s (undecryptable): message is duplicate", evt.Info.ID)
  702. return
  703. }
  704. metricType := "error"
  705. if evt.IsUnavailable {
  706. metricType = "unavailable"
  707. }
  708. Segment.Track(source.MXID, "WhatsApp undecryptable message", map[string]interface{}{
  709. "messageID": evt.Info.ID,
  710. "undecryptableType": metricType,
  711. })
  712. intent := portal.getMessageIntent(source, &evt.Info, "undecryptable")
  713. if intent == nil {
  714. return
  715. }
  716. content := undecryptableMessageContent
  717. resp, err := portal.sendMessage(intent, event.EventMessage, &content, nil, evt.Info.Timestamp.UnixMilli())
  718. if err != nil {
  719. portal.log.Errorfln("Failed to send decryption error of %s to Matrix: %v", evt.Info.ID, err)
  720. return
  721. }
  722. portal.finishHandling(nil, &evt.Info, resp.EventID, intent.UserID, database.MsgUnknown, 0, database.MsgErrDecryptionFailed)
  723. }
  724. func (portal *Portal) handleFakeMessage(msg fakeMessage) {
  725. if portal.isRecentlyHandled(msg.ID, database.MsgNoError) {
  726. portal.log.Debugfln("Not handling %s (fake): message was recently handled", msg.ID)
  727. return
  728. } else if existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, msg.ID); existingMsg != nil {
  729. portal.log.Debugfln("Not handling %s (fake): message is duplicate", msg.ID)
  730. return
  731. }
  732. if msg.Sender.Server != types.DefaultUserServer {
  733. portal.log.Debugfln("Not handling %s (fake): message is from a lid user (%s)", msg.ID, msg.Sender)
  734. // TODO handle lids
  735. return
  736. }
  737. intent := portal.bridge.GetPuppetByJID(msg.Sender).IntentFor(portal)
  738. if !intent.IsCustomPuppet && portal.IsPrivateChat() && msg.Sender.User == portal.Key.Receiver.User && portal.Key.Receiver != portal.Key.JID {
  739. portal.log.Debugfln("Not handling %s (fake): user doesn't have double puppeting enabled", msg.ID)
  740. return
  741. }
  742. msgType := event.MsgNotice
  743. if msg.Important {
  744. msgType = event.MsgText
  745. }
  746. resp, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  747. MsgType: msgType,
  748. Body: msg.Text,
  749. }, nil, msg.Time.UnixMilli())
  750. if err != nil {
  751. portal.log.Errorfln("Failed to send %s to Matrix: %v", msg.ID, err)
  752. } else {
  753. portal.finishHandling(nil, &types.MessageInfo{
  754. ID: msg.ID,
  755. Timestamp: msg.Time,
  756. MessageSource: types.MessageSource{
  757. Sender: msg.Sender,
  758. },
  759. }, resp.EventID, intent.UserID, database.MsgFake, 0, database.MsgNoError)
  760. }
  761. }
  762. func (portal *Portal) handleMessage(source *User, evt *events.Message, historical bool) {
  763. if len(portal.MXID) == 0 {
  764. portal.log.Warnln("handleMessage called even though portal.MXID is empty")
  765. return
  766. }
  767. msgID := evt.Info.ID
  768. msgType := getMessageType(evt.Message)
  769. if msgType == "ignore" {
  770. return
  771. } else if portal.isRecentlyHandled(msgID, database.MsgNoError) {
  772. portal.log.Debugfln("Not handling %s (%s): message was recently handled", msgID, msgType)
  773. return
  774. }
  775. existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, msgID)
  776. if existingMsg != nil {
  777. if existingMsg.Error == database.MsgErrDecryptionFailed {
  778. resolveType := "sender"
  779. if evt.UnavailableRequestID != "" {
  780. resolveType = "phone"
  781. }
  782. Segment.Track(source.MXID, "WhatsApp undecryptable message resolved", map[string]interface{}{
  783. "messageID": evt.Info.ID,
  784. "resolveType": resolveType,
  785. })
  786. portal.log.Debugfln("Got decryptable version of previously undecryptable message %s (%s) via %s", msgID, msgType, resolveType)
  787. } else {
  788. portal.log.Debugfln("Not handling %s (%s): message is duplicate", msgID, msgType)
  789. return
  790. }
  791. }
  792. var editTargetMsg *database.Message
  793. if msgType == "edit" {
  794. editTargetID := evt.Message.GetProtocolMessage().GetKey().GetId()
  795. editTargetMsg = portal.bridge.DB.Message.GetByJID(portal.Key, editTargetID)
  796. if editTargetMsg == nil {
  797. portal.log.Warnfln("Not handling %s: couldn't find edit target %s", msgID, editTargetID)
  798. return
  799. } else if editTargetMsg.Type != database.MsgNormal {
  800. portal.log.Warnfln("Not handling %s: edit target %s is not a normal message (it's %s)", msgID, editTargetID, editTargetMsg.Type)
  801. return
  802. } else if editTargetMsg.Sender.User != evt.Info.Sender.User {
  803. portal.log.Warnfln("Not handling %s: edit target %s was sent by %s, not %s", msgID, editTargetID, editTargetMsg.Sender.User, evt.Info.Sender.User)
  804. return
  805. }
  806. evt.Message = evt.Message.GetProtocolMessage().GetEditedMessage()
  807. }
  808. intent := portal.getMessageIntent(source, &evt.Info, msgType)
  809. if intent == nil {
  810. return
  811. }
  812. converted := portal.convertMessage(intent, source, &evt.Info, evt.Message, false)
  813. if converted != nil {
  814. isGalleriable := portal.bridge.Config.Bridge.BeeperGalleries &&
  815. (evt.Message.ImageMessage != nil || evt.Message.VideoMessage != nil) &&
  816. (portal.galleryCache == nil ||
  817. (evt.Info.Sender.ToNonAD() == portal.galleryCacheSender &&
  818. converted.ReplyTo.Equals(portal.galleryCacheReplyTo) &&
  819. time.Since(portal.galleryCacheStart) < GalleryMaxTime)) &&
  820. // Captions aren't allowed in galleries (this needs to be checked before the caption is merged)
  821. converted.Caption == nil &&
  822. // Images can't be edited
  823. editTargetMsg == nil
  824. if !historical && portal.IsPrivateChat() && evt.Info.Sender.Device == 0 && converted.ExpiresIn > 0 && portal.ExpirationTime == 0 {
  825. portal.zlog.Info().
  826. Str("timer", converted.ExpiresIn.String()).
  827. Str("sender_jid", evt.Info.Sender.String()).
  828. Str("message_id", evt.Info.ID).
  829. Msg("Implicitly enabling disappearing messages as incoming message is disappearing")
  830. portal.implicitlyEnableDisappearingMessages(converted.ExpiresIn)
  831. }
  832. if evt.Info.IsIncomingBroadcast() {
  833. if converted.Extra == nil {
  834. converted.Extra = map[string]interface{}{}
  835. }
  836. converted.Extra["fi.mau.whatsapp.source_broadcast_list"] = evt.Info.Chat.String()
  837. }
  838. if portal.bridge.Config.Bridge.CaptionInMessage {
  839. converted.MergeCaption()
  840. }
  841. var eventID id.EventID
  842. var lastEventID id.EventID
  843. if existingMsg != nil {
  844. portal.MarkDisappearing(nil, existingMsg.MXID, converted.ExpiresIn, evt.Info.Timestamp)
  845. converted.Content.SetEdit(existingMsg.MXID)
  846. } else if converted.ReplyTo != nil {
  847. portal.SetReply(evt.Info.ID, converted.Content, converted.ReplyTo, false)
  848. }
  849. dbMsgType := database.MsgNormal
  850. if editTargetMsg != nil {
  851. dbMsgType = database.MsgEdit
  852. converted.Content.SetEdit(editTargetMsg.MXID)
  853. }
  854. galleryStarted := false
  855. var galleryPart int
  856. if isGalleriable {
  857. if portal.galleryCache == nil {
  858. portal.startGallery(evt, converted)
  859. galleryStarted = true
  860. } else {
  861. galleryPart = portal.extendGallery(converted)
  862. dbMsgType = database.MsgBeeperGallery
  863. }
  864. } else if editTargetMsg == nil {
  865. // Stop collecting a gallery (except if it's an edit)
  866. portal.stopGallery()
  867. }
  868. resp, err := portal.sendMessage(converted.Intent, converted.Type, converted.Content, converted.Extra, evt.Info.Timestamp.UnixMilli())
  869. if err != nil {
  870. portal.log.Errorfln("Failed to send %s to Matrix: %v", msgID, err)
  871. } else {
  872. if editTargetMsg == nil {
  873. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, evt.Info.Timestamp)
  874. }
  875. eventID = resp.EventID
  876. lastEventID = eventID
  877. if galleryStarted {
  878. portal.galleryCacheRootEvent = eventID
  879. } else if galleryPart != 0 {
  880. eventID = portal.galleryCacheRootEvent
  881. }
  882. }
  883. // TODO figure out how to handle captions with undecryptable messages turning decryptable
  884. if converted.Caption != nil && existingMsg == nil && editTargetMsg == nil {
  885. resp, err = portal.sendMessage(converted.Intent, converted.Type, converted.Caption, nil, evt.Info.Timestamp.UnixMilli())
  886. if err != nil {
  887. portal.log.Errorfln("Failed to send caption of %s to Matrix: %v", msgID, err)
  888. } else {
  889. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, evt.Info.Timestamp)
  890. lastEventID = resp.EventID
  891. }
  892. }
  893. if converted.MultiEvent != nil && existingMsg == nil && editTargetMsg == nil {
  894. for index, subEvt := range converted.MultiEvent {
  895. resp, err = portal.sendMessage(converted.Intent, converted.Type, subEvt, nil, evt.Info.Timestamp.UnixMilli())
  896. if err != nil {
  897. portal.log.Errorfln("Failed to send sub-event %d of %s to Matrix: %v", index+1, msgID, err)
  898. } else {
  899. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, evt.Info.Timestamp)
  900. lastEventID = resp.EventID
  901. }
  902. }
  903. }
  904. if source.MXID == intent.UserID && portal.bridge.Config.Homeserver.Software != bridgeconfig.SoftwareHungry {
  905. // There are some edge cases (like call notices) where previous messages aren't marked as read
  906. // when the user sends a message from another device, so just mark the new message as read to be safe.
  907. // Hungryserv does this automatically, so the bridge doesn't need to do it manually.
  908. err = intent.SetReadMarkers(portal.MXID, source.makeReadMarkerContent(lastEventID, true))
  909. if err != nil {
  910. portal.log.Warnfln("Failed to mark own message %s as read by %s: %v", lastEventID, source.MXID, err)
  911. }
  912. }
  913. if len(eventID) != 0 {
  914. portal.finishHandling(existingMsg, &evt.Info, eventID, intent.UserID, dbMsgType, galleryPart, converted.Error)
  915. }
  916. } else if msgType == "reaction" || msgType == "encrypted reaction" {
  917. if evt.Message.GetEncReactionMessage() != nil {
  918. decryptedReaction, err := source.Client.DecryptReaction(evt)
  919. if err != nil {
  920. portal.log.Errorfln("Failed to decrypt reaction from %s to %s: %v", evt.Info.Sender, evt.Message.GetEncReactionMessage().GetTargetMessageKey().GetId(), err)
  921. } else {
  922. portal.HandleMessageReaction(intent, source, &evt.Info, decryptedReaction, existingMsg)
  923. }
  924. } else {
  925. portal.HandleMessageReaction(intent, source, &evt.Info, evt.Message.GetReactionMessage(), existingMsg)
  926. }
  927. } else if msgType == "revoke" {
  928. portal.HandleMessageRevoke(source, &evt.Info, evt.Message.GetProtocolMessage().GetKey())
  929. if existingMsg != nil {
  930. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  931. Reason: "The undecryptable message was actually the deletion of another message",
  932. })
  933. existingMsg.UpdateMXID(nil, "net.maunium.whatsapp.fake::"+existingMsg.MXID, database.MsgFake, database.MsgNoError)
  934. }
  935. } else {
  936. portal.log.Warnfln("Unhandled message: %+v (%s)", evt.Info, msgType)
  937. if existingMsg != nil {
  938. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  939. Reason: "The undecryptable message contained an unsupported message type",
  940. })
  941. existingMsg.UpdateMXID(nil, "net.maunium.whatsapp.fake::"+existingMsg.MXID, database.MsgFake, database.MsgNoError)
  942. }
  943. return
  944. }
  945. portal.bridge.Metrics.TrackWhatsAppMessage(evt.Info.Timestamp, strings.Split(msgType, " ")[0])
  946. }
  947. func (portal *Portal) isRecentlyHandled(id types.MessageID, error database.MessageErrorType) bool {
  948. start := portal.recentlyHandledIndex
  949. lookingForMsg := recentlyHandledWrapper{id, error}
  950. for i := start; i != start; i = (i - 1) % recentlyHandledLength {
  951. if portal.recentlyHandled[i] == lookingForMsg {
  952. return true
  953. }
  954. }
  955. return false
  956. }
  957. func (portal *Portal) markHandled(txn dbutil.Transaction, msg *database.Message, info *types.MessageInfo, mxid id.EventID, senderMXID id.UserID, isSent, recent bool, msgType database.MessageType, galleryPart int, errType database.MessageErrorType) *database.Message {
  958. if msg == nil {
  959. msg = portal.bridge.DB.Message.New()
  960. msg.Chat = portal.Key
  961. msg.JID = info.ID
  962. msg.MXID = mxid
  963. msg.GalleryPart = galleryPart
  964. msg.Timestamp = info.Timestamp
  965. msg.Sender = info.Sender
  966. msg.SenderMXID = senderMXID
  967. msg.Sent = isSent
  968. msg.Type = msgType
  969. msg.Error = errType
  970. if info.IsIncomingBroadcast() {
  971. msg.BroadcastListJID = info.Chat
  972. }
  973. msg.Insert(txn)
  974. } else {
  975. msg.UpdateMXID(txn, mxid, msgType, errType)
  976. }
  977. if recent {
  978. portal.recentlyHandledLock.Lock()
  979. index := portal.recentlyHandledIndex
  980. portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
  981. portal.recentlyHandledLock.Unlock()
  982. portal.recentlyHandled[index] = recentlyHandledWrapper{msg.JID, errType}
  983. }
  984. return msg
  985. }
  986. func (portal *Portal) getMessagePuppet(user *User, info *types.MessageInfo) (puppet *Puppet) {
  987. if info.IsFromMe {
  988. return portal.bridge.GetPuppetByJID(user.JID)
  989. } else if portal.IsPrivateChat() {
  990. puppet = portal.bridge.GetPuppetByJID(portal.Key.JID)
  991. } else if !info.Sender.IsEmpty() {
  992. puppet = portal.bridge.GetPuppetByJID(info.Sender)
  993. }
  994. if puppet == nil {
  995. portal.log.Warnfln("Message %+v doesn't seem to have a valid sender (%s): puppet is nil", *info, info.Sender)
  996. return nil
  997. }
  998. user.EnqueuePortalResync(portal)
  999. puppet.SyncContact(user, true, true, "handling message")
  1000. return puppet
  1001. }
  1002. func (portal *Portal) getMessageIntent(user *User, info *types.MessageInfo, msgType string) *appservice.IntentAPI {
  1003. puppet := portal.getMessagePuppet(user, info)
  1004. if puppet == nil {
  1005. return nil
  1006. }
  1007. intent := puppet.IntentFor(portal)
  1008. if !intent.IsCustomPuppet && portal.IsPrivateChat() && info.Sender.User == portal.Key.Receiver.User && portal.Key.Receiver != portal.Key.JID {
  1009. portal.log.Debugfln("Not handling %s (%s): user doesn't have double puppeting enabled", info.ID, msgType)
  1010. return nil
  1011. }
  1012. return intent
  1013. }
  1014. func (portal *Portal) finishHandling(existing *database.Message, message *types.MessageInfo, mxid id.EventID, senderMXID id.UserID, msgType database.MessageType, galleryPart int, errType database.MessageErrorType) {
  1015. portal.markHandled(nil, existing, message, mxid, senderMXID, true, true, msgType, galleryPart, errType)
  1016. portal.sendDeliveryReceipt(mxid)
  1017. var suffix string
  1018. if errType == database.MsgErrDecryptionFailed {
  1019. suffix = "(undecryptable message error notice)"
  1020. } else if errType == database.MsgErrMediaNotFound {
  1021. suffix = "(media not found notice)"
  1022. }
  1023. portal.log.Debugfln("Handled message %s (%s) -> %s %s", message.ID, msgType, mxid, suffix)
  1024. }
  1025. func (portal *Portal) kickExtraUsers(participantMap map[types.JID]bool) {
  1026. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  1027. if err != nil {
  1028. portal.log.Warnln("Failed to get member list:", err)
  1029. return
  1030. }
  1031. for member := range members.Joined {
  1032. jid, ok := portal.bridge.ParsePuppetMXID(member)
  1033. if ok {
  1034. _, shouldBePresent := participantMap[jid]
  1035. if !shouldBePresent {
  1036. _, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  1037. UserID: member,
  1038. Reason: "User had left this WhatsApp chat",
  1039. })
  1040. if err != nil {
  1041. portal.log.Warnfln("Failed to kick user %s who had left: %v", member, err)
  1042. }
  1043. }
  1044. }
  1045. }
  1046. }
  1047. //func (portal *Portal) SyncBroadcastRecipients(source *User, metadata *whatsapp.BroadcastListInfo) {
  1048. // participantMap := make(map[whatsapp.JID]bool)
  1049. // for _, recipient := range metadata.Recipients {
  1050. // participantMap[recipient.JID] = true
  1051. //
  1052. // puppet := portal.bridge.GetPuppetByJID(recipient.JID)
  1053. // puppet.SyncContactIfNecessary(source)
  1054. // err := puppet.DefaultIntent().EnsureJoined(portal.MXID)
  1055. // if err != nil {
  1056. // portal.log.Warnfln("Failed to make puppet of %s join %s: %v", recipient.JID, portal.MXID, err)
  1057. // }
  1058. // }
  1059. // portal.kickExtraUsers(participantMap)
  1060. //}
  1061. func (portal *Portal) syncParticipant(source *User, participant types.GroupParticipant, puppet *Puppet, user *User, wg *sync.WaitGroup) {
  1062. defer func() {
  1063. wg.Done()
  1064. if err := recover(); err != nil {
  1065. portal.log.Errorfln("Syncing participant %s panicked: %v\n%s", participant.JID, err, debug.Stack())
  1066. }
  1067. }()
  1068. puppet.SyncContact(source, true, false, "group participant")
  1069. if portal.MXID != "" {
  1070. if user != nil && user != source {
  1071. portal.ensureUserInvited(user)
  1072. }
  1073. if user == nil || !puppet.IntentFor(portal).IsCustomPuppet {
  1074. err := puppet.IntentFor(portal).EnsureJoined(portal.MXID)
  1075. if err != nil {
  1076. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.JID, portal.MXID, err)
  1077. }
  1078. }
  1079. }
  1080. }
  1081. func (portal *Portal) SyncParticipants(source *User, metadata *types.GroupInfo) ([]id.UserID, *event.PowerLevelsEventContent) {
  1082. changed := false
  1083. var levels *event.PowerLevelsEventContent
  1084. var err error
  1085. if portal.MXID != "" {
  1086. levels, err = portal.MainIntent().PowerLevels(portal.MXID)
  1087. }
  1088. if levels == nil || err != nil {
  1089. levels = portal.GetBasePowerLevels()
  1090. changed = true
  1091. }
  1092. changed = portal.applyPowerLevelFixes(levels) || changed
  1093. var wg sync.WaitGroup
  1094. wg.Add(len(metadata.Participants))
  1095. participantMap := make(map[types.JID]bool)
  1096. userIDs := make([]id.UserID, 0, len(metadata.Participants))
  1097. for _, participant := range metadata.Participants {
  1098. if participant.JID.IsEmpty() || participant.JID.Server != types.DefaultUserServer {
  1099. wg.Done()
  1100. // TODO handle lids
  1101. continue
  1102. }
  1103. portal.log.Debugfln("Syncing participant %s (admin: %t)", participant.JID, participant.IsAdmin)
  1104. participantMap[participant.JID] = true
  1105. puppet := portal.bridge.GetPuppetByJID(participant.JID)
  1106. user := portal.bridge.GetUserByJID(participant.JID)
  1107. if portal.bridge.Config.Bridge.ParallelMemberSync {
  1108. go portal.syncParticipant(source, participant, puppet, user, &wg)
  1109. } else {
  1110. portal.syncParticipant(source, participant, puppet, user, &wg)
  1111. }
  1112. expectedLevel := 0
  1113. if participant.IsSuperAdmin {
  1114. expectedLevel = 95
  1115. } else if participant.IsAdmin {
  1116. expectedLevel = 50
  1117. }
  1118. changed = levels.EnsureUserLevel(puppet.MXID, expectedLevel) || changed
  1119. if user != nil {
  1120. userIDs = append(userIDs, user.MXID)
  1121. changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed
  1122. }
  1123. if user == nil || puppet.CustomMXID != user.MXID {
  1124. userIDs = append(userIDs, puppet.MXID)
  1125. }
  1126. }
  1127. if portal.MXID != "" {
  1128. if changed {
  1129. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1130. if err != nil {
  1131. portal.log.Errorln("Failed to change power levels:", err)
  1132. }
  1133. }
  1134. portal.kickExtraUsers(participantMap)
  1135. }
  1136. wg.Wait()
  1137. portal.log.Debugln("Participant sync completed")
  1138. return userIDs, levels
  1139. }
  1140. func reuploadAvatar(intent *appservice.IntentAPI, url string) (id.ContentURI, error) {
  1141. getResp, err := http.DefaultClient.Get(url)
  1142. if err != nil {
  1143. return id.ContentURI{}, fmt.Errorf("failed to download avatar: %w", err)
  1144. }
  1145. data, err := io.ReadAll(getResp.Body)
  1146. _ = getResp.Body.Close()
  1147. if err != nil {
  1148. return id.ContentURI{}, fmt.Errorf("failed to read avatar bytes: %w", err)
  1149. }
  1150. resp, err := intent.UploadBytes(data, http.DetectContentType(data))
  1151. if err != nil {
  1152. return id.ContentURI{}, fmt.Errorf("failed to upload avatar to Matrix: %w", err)
  1153. }
  1154. return resp.ContentURI, nil
  1155. }
  1156. func (user *User) updateAvatar(jid types.JID, isCommunity bool, avatarID *string, avatarURL *id.ContentURI, avatarSet *bool, log log.Logger, intent *appservice.IntentAPI) bool {
  1157. currentID := ""
  1158. if *avatarSet && *avatarID != "remove" && *avatarID != "unauthorized" {
  1159. currentID = *avatarID
  1160. }
  1161. avatar, err := user.Client.GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
  1162. Preview: false,
  1163. ExistingID: currentID,
  1164. IsCommunity: isCommunity,
  1165. })
  1166. if errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) {
  1167. if *avatarID == "" {
  1168. *avatarID = "unauthorized"
  1169. *avatarSet = false
  1170. return true
  1171. }
  1172. return false
  1173. } else if errors.Is(err, whatsmeow.ErrProfilePictureNotSet) {
  1174. avatar = &types.ProfilePictureInfo{ID: "remove"}
  1175. if avatar.ID == *avatarID && *avatarSet {
  1176. return false
  1177. }
  1178. *avatarID = avatar.ID
  1179. *avatarURL = id.ContentURI{}
  1180. return true
  1181. } else if err != nil {
  1182. log.Warnln("Failed to get avatar URL:", err)
  1183. return false
  1184. } else if avatar == nil {
  1185. // Avatar hasn't changed
  1186. return false
  1187. }
  1188. if avatar.ID == *avatarID && *avatarSet {
  1189. return false
  1190. } else if len(avatar.URL) == 0 {
  1191. log.Warnln("Didn't get URL in response to avatar query")
  1192. return false
  1193. } else if avatar.ID != *avatarID || avatarURL.IsEmpty() {
  1194. url, err := reuploadAvatar(intent, avatar.URL)
  1195. if err != nil {
  1196. log.Warnln("Failed to reupload avatar:", err)
  1197. return false
  1198. }
  1199. *avatarURL = url
  1200. }
  1201. log.Debugfln("Updated avatar %s -> %s", *avatarID, avatar.ID)
  1202. *avatarID = avatar.ID
  1203. *avatarSet = false
  1204. return true
  1205. }
  1206. func (portal *Portal) UpdateAvatar(user *User, setBy types.JID, updateInfo bool) bool {
  1207. portal.avatarLock.Lock()
  1208. defer portal.avatarLock.Unlock()
  1209. changed := user.updateAvatar(portal.Key.JID, portal.IsParent, &portal.Avatar, &portal.AvatarURL, &portal.AvatarSet, portal.log, portal.MainIntent())
  1210. if !changed || portal.Avatar == "unauthorized" {
  1211. if changed || updateInfo {
  1212. portal.Update(nil)
  1213. }
  1214. return changed
  1215. }
  1216. if len(portal.MXID) > 0 {
  1217. intent := portal.MainIntent()
  1218. if !setBy.IsEmpty() && setBy.Server == types.DefaultUserServer {
  1219. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1220. }
  1221. _, err := intent.SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1222. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1223. _, err = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1224. }
  1225. if err != nil {
  1226. portal.log.Warnln("Failed to set room avatar:", err)
  1227. return true
  1228. } else {
  1229. portal.AvatarSet = true
  1230. }
  1231. }
  1232. if updateInfo {
  1233. portal.UpdateBridgeInfo()
  1234. portal.Update(nil)
  1235. portal.updateChildRooms()
  1236. }
  1237. return true
  1238. }
  1239. func (portal *Portal) UpdateName(name string, setBy types.JID, updateInfo bool) bool {
  1240. if name == "" && portal.IsBroadcastList() {
  1241. name = UnnamedBroadcastName
  1242. }
  1243. if portal.Name != name || (!portal.NameSet && len(portal.MXID) > 0 && portal.shouldSetDMRoomMetadata()) {
  1244. portal.log.Debugfln("Updating name %q -> %q", portal.Name, name)
  1245. portal.Name = name
  1246. portal.NameSet = false
  1247. if updateInfo {
  1248. defer portal.Update(nil)
  1249. }
  1250. if len(portal.MXID) > 0 && !portal.shouldSetDMRoomMetadata() {
  1251. portal.UpdateBridgeInfo()
  1252. } else if len(portal.MXID) > 0 {
  1253. intent := portal.MainIntent()
  1254. if !setBy.IsEmpty() && setBy.Server == types.DefaultUserServer {
  1255. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1256. }
  1257. _, err := intent.SetRoomName(portal.MXID, name)
  1258. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1259. _, err = portal.MainIntent().SetRoomName(portal.MXID, name)
  1260. }
  1261. if err == nil {
  1262. portal.NameSet = true
  1263. if updateInfo {
  1264. portal.UpdateBridgeInfo()
  1265. portal.updateChildRooms()
  1266. }
  1267. return true
  1268. } else {
  1269. portal.log.Warnln("Failed to set room name:", err)
  1270. }
  1271. }
  1272. }
  1273. return false
  1274. }
  1275. func (portal *Portal) UpdateTopic(topic string, setBy types.JID, updateInfo bool) bool {
  1276. if portal.Topic != topic || !portal.TopicSet {
  1277. portal.log.Debugfln("Updating topic %q -> %q", portal.Topic, topic)
  1278. portal.Topic = topic
  1279. portal.TopicSet = false
  1280. intent := portal.MainIntent()
  1281. if !setBy.IsEmpty() && setBy.Server == types.DefaultUserServer {
  1282. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1283. }
  1284. _, err := intent.SetRoomTopic(portal.MXID, topic)
  1285. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1286. _, err = portal.MainIntent().SetRoomTopic(portal.MXID, topic)
  1287. }
  1288. if err == nil {
  1289. portal.TopicSet = true
  1290. if updateInfo {
  1291. portal.UpdateBridgeInfo()
  1292. portal.Update(nil)
  1293. }
  1294. return true
  1295. } else {
  1296. portal.log.Warnln("Failed to set room topic:", err)
  1297. }
  1298. }
  1299. return false
  1300. }
  1301. func (portal *Portal) UpdateParentGroup(source *User, parent types.JID, updateInfo bool) bool {
  1302. portal.parentGroupUpdateLock.Lock()
  1303. defer portal.parentGroupUpdateLock.Unlock()
  1304. if portal.ParentGroup != parent {
  1305. portal.log.Debugfln("Updating parent group %v -> %v", portal.ParentGroup, parent)
  1306. portal.updateCommunitySpace(source, false, false)
  1307. portal.ParentGroup = parent
  1308. portal.parentPortal = nil
  1309. portal.InSpace = false
  1310. portal.updateCommunitySpace(source, true, false)
  1311. if updateInfo {
  1312. portal.UpdateBridgeInfo()
  1313. portal.Update(nil)
  1314. }
  1315. return true
  1316. } else if !portal.ParentGroup.IsEmpty() && !portal.InSpace {
  1317. return portal.updateCommunitySpace(source, true, updateInfo)
  1318. }
  1319. return false
  1320. }
  1321. func (portal *Portal) UpdateMetadata(user *User, groupInfo *types.GroupInfo) bool {
  1322. if portal.IsPrivateChat() {
  1323. return false
  1324. } else if portal.IsStatusBroadcastList() {
  1325. update := false
  1326. update = portal.UpdateName(StatusBroadcastName, types.EmptyJID, false) || update
  1327. update = portal.UpdateTopic(StatusBroadcastTopic, types.EmptyJID, false) || update
  1328. return update
  1329. } else if portal.IsBroadcastList() {
  1330. update := false
  1331. //broadcastMetadata, err := user.Conn.GetBroadcastMetadata(portal.Key.JID)
  1332. //if err == nil && broadcastMetadata.Status == 200 {
  1333. // portal.SyncBroadcastRecipients(user, broadcastMetadata)
  1334. // update = portal.UpdateName(broadcastMetadata.Name, "", nil, false) || update
  1335. //} else {
  1336. // user.Conn.Store.ContactsLock.RLock()
  1337. // contact, _ := user.Conn.Store.Contacts[portal.Key.JID]
  1338. // user.Conn.Store.ContactsLock.RUnlock()
  1339. // update = portal.UpdateName(contact.Name, "", nil, false) || update
  1340. //}
  1341. //update = portal.UpdateTopic(BroadcastTopic, "", nil, false) || update
  1342. return update
  1343. }
  1344. if groupInfo == nil {
  1345. var err error
  1346. groupInfo, err = user.Client.GetGroupInfo(portal.Key.JID)
  1347. if err != nil {
  1348. portal.log.Errorln("Failed to get group info:", err)
  1349. return false
  1350. }
  1351. }
  1352. portal.SyncParticipants(user, groupInfo)
  1353. update := false
  1354. update = portal.UpdateName(groupInfo.Name, groupInfo.NameSetBy, false) || update
  1355. update = portal.UpdateTopic(groupInfo.Topic, groupInfo.TopicSetBy, false) || update
  1356. update = portal.UpdateParentGroup(user, groupInfo.LinkedParentJID, false) || update
  1357. if portal.ExpirationTime != groupInfo.DisappearingTimer {
  1358. update = true
  1359. portal.ExpirationTime = groupInfo.DisappearingTimer
  1360. }
  1361. if portal.IsParent != groupInfo.IsParent {
  1362. if portal.MXID != "" {
  1363. portal.log.Warnfln("Existing group changed is_parent from %t to %t", portal.IsParent, groupInfo.IsParent)
  1364. }
  1365. portal.IsParent = groupInfo.IsParent
  1366. update = true
  1367. }
  1368. portal.RestrictMessageSending(groupInfo.IsAnnounce)
  1369. portal.RestrictMetadataChanges(groupInfo.IsLocked)
  1370. return update
  1371. }
  1372. func (portal *Portal) ensureUserInvited(user *User) bool {
  1373. return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
  1374. }
  1375. func (portal *Portal) UpdateMatrixRoom(user *User, groupInfo *types.GroupInfo) bool {
  1376. if len(portal.MXID) == 0 {
  1377. return false
  1378. }
  1379. portal.log.Infoln("Syncing portal for", user.MXID)
  1380. portal.ensureUserInvited(user)
  1381. go portal.addToPersonalSpace(user)
  1382. update := false
  1383. update = portal.UpdateMetadata(user, groupInfo) || update
  1384. if !portal.IsPrivateChat() && !portal.IsBroadcastList() {
  1385. update = portal.UpdateAvatar(user, types.EmptyJID, false) || update
  1386. }
  1387. if update || portal.LastSync.Add(24*time.Hour).Before(time.Now()) {
  1388. portal.LastSync = time.Now()
  1389. portal.Update(nil)
  1390. portal.UpdateBridgeInfo()
  1391. portal.updateChildRooms()
  1392. }
  1393. return true
  1394. }
  1395. func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
  1396. anyone := 0
  1397. nope := 99
  1398. invite := 50
  1399. if portal.bridge.Config.Bridge.AllowUserInvite {
  1400. invite = 0
  1401. }
  1402. return &event.PowerLevelsEventContent{
  1403. UsersDefault: anyone,
  1404. EventsDefault: anyone,
  1405. RedactPtr: &anyone,
  1406. StateDefaultPtr: &nope,
  1407. BanPtr: &nope,
  1408. InvitePtr: &invite,
  1409. Users: map[id.UserID]int{
  1410. portal.MainIntent().UserID: 100,
  1411. },
  1412. Events: map[string]int{
  1413. event.StateRoomName.Type: anyone,
  1414. event.StateRoomAvatar.Type: anyone,
  1415. event.StateTopic.Type: anyone,
  1416. event.EventReaction.Type: anyone,
  1417. event.EventRedaction.Type: anyone,
  1418. TypeMSC3381PollResponse.Type: anyone,
  1419. },
  1420. }
  1421. }
  1422. func (portal *Portal) applyPowerLevelFixes(levels *event.PowerLevelsEventContent) bool {
  1423. changed := false
  1424. changed = levels.EnsureEventLevel(event.EventReaction, 0) || changed
  1425. changed = levels.EnsureEventLevel(event.EventRedaction, 0) || changed
  1426. changed = levels.EnsureEventLevel(TypeMSC3381PollResponse, 0) || changed
  1427. return changed
  1428. }
  1429. func (portal *Portal) ChangeAdminStatus(jids []types.JID, setAdmin bool) id.EventID {
  1430. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1431. if err != nil {
  1432. levels = portal.GetBasePowerLevels()
  1433. }
  1434. newLevel := 0
  1435. if setAdmin {
  1436. newLevel = 50
  1437. }
  1438. changed := portal.applyPowerLevelFixes(levels)
  1439. for _, jid := range jids {
  1440. if jid.Server != types.DefaultUserServer {
  1441. // TODO handle lids
  1442. continue
  1443. }
  1444. puppet := portal.bridge.GetPuppetByJID(jid)
  1445. changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
  1446. user := portal.bridge.GetUserByJID(jid)
  1447. if user != nil {
  1448. changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
  1449. }
  1450. }
  1451. if changed {
  1452. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1453. if err != nil {
  1454. portal.log.Errorln("Failed to change power levels:", err)
  1455. } else {
  1456. return resp.EventID
  1457. }
  1458. }
  1459. return ""
  1460. }
  1461. func (portal *Portal) RestrictMessageSending(restrict bool) id.EventID {
  1462. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1463. if err != nil {
  1464. levels = portal.GetBasePowerLevels()
  1465. }
  1466. newLevel := 0
  1467. if restrict {
  1468. newLevel = 50
  1469. }
  1470. changed := portal.applyPowerLevelFixes(levels)
  1471. if levels.EventsDefault == newLevel && !changed {
  1472. return ""
  1473. }
  1474. levels.EventsDefault = newLevel
  1475. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1476. if err != nil {
  1477. portal.log.Errorln("Failed to change power levels:", err)
  1478. return ""
  1479. } else {
  1480. return resp.EventID
  1481. }
  1482. }
  1483. func (portal *Portal) RestrictMetadataChanges(restrict bool) id.EventID {
  1484. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1485. if err != nil {
  1486. levels = portal.GetBasePowerLevels()
  1487. }
  1488. newLevel := 0
  1489. if restrict {
  1490. newLevel = 50
  1491. }
  1492. changed := portal.applyPowerLevelFixes(levels)
  1493. changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
  1494. changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
  1495. changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
  1496. if changed {
  1497. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1498. if err != nil {
  1499. portal.log.Errorln("Failed to change power levels:", err)
  1500. } else {
  1501. return resp.EventID
  1502. }
  1503. }
  1504. return ""
  1505. }
  1506. func (portal *Portal) getBridgeInfoStateKey() string {
  1507. return fmt.Sprintf("net.maunium.whatsapp://whatsapp/%s", portal.Key.JID)
  1508. }
  1509. func (portal *Portal) getBridgeInfo() (string, event.BridgeEventContent) {
  1510. bridgeInfo := event.BridgeEventContent{
  1511. BridgeBot: portal.bridge.Bot.UserID,
  1512. Creator: portal.MainIntent().UserID,
  1513. Protocol: event.BridgeInfoSection{
  1514. ID: "whatsapp",
  1515. DisplayName: "WhatsApp",
  1516. AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
  1517. ExternalURL: "https://www.whatsapp.com/",
  1518. },
  1519. Channel: event.BridgeInfoSection{
  1520. ID: portal.Key.JID.String(),
  1521. DisplayName: portal.Name,
  1522. AvatarURL: portal.AvatarURL.CUString(),
  1523. },
  1524. }
  1525. if parent := portal.GetParentPortal(); parent != nil {
  1526. bridgeInfo.Network = &event.BridgeInfoSection{
  1527. ID: parent.Key.JID.String(),
  1528. DisplayName: parent.Name,
  1529. AvatarURL: parent.AvatarURL.CUString(),
  1530. }
  1531. }
  1532. return portal.getBridgeInfoStateKey(), bridgeInfo
  1533. }
  1534. func (portal *Portal) UpdateBridgeInfo() {
  1535. if len(portal.MXID) == 0 {
  1536. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  1537. return
  1538. }
  1539. portal.log.Debugln("Updating bridge info...")
  1540. stateKey, content := portal.getBridgeInfo()
  1541. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
  1542. if err != nil {
  1543. portal.log.Warnln("Failed to update m.bridge:", err)
  1544. }
  1545. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1546. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
  1547. if err != nil {
  1548. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  1549. }
  1550. }
  1551. func (portal *Portal) updateChildRooms() {
  1552. if !portal.IsParent {
  1553. return
  1554. }
  1555. children := portal.bridge.GetAllByParentGroup(portal.Key.JID)
  1556. for _, child := range children {
  1557. changed := child.updateCommunitySpace(nil, true, false)
  1558. child.UpdateBridgeInfo()
  1559. if changed {
  1560. portal.Update(nil)
  1561. }
  1562. }
  1563. }
  1564. func (portal *Portal) shouldSetDMRoomMetadata() bool {
  1565. return !portal.IsPrivateChat() ||
  1566. portal.bridge.Config.Bridge.PrivateChatPortalMeta == "always" ||
  1567. (portal.IsEncrypted() && portal.bridge.Config.Bridge.PrivateChatPortalMeta != "never")
  1568. }
  1569. func (portal *Portal) GetEncryptionEventContent() (evt *event.EncryptionEventContent) {
  1570. evt = &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1}
  1571. if rot := portal.bridge.Config.Bridge.Encryption.Rotation; rot.EnableCustom {
  1572. evt.RotationPeriodMillis = rot.Milliseconds
  1573. evt.RotationPeriodMessages = rot.Messages
  1574. }
  1575. return
  1576. }
  1577. func (portal *Portal) CreateMatrixRoom(user *User, groupInfo *types.GroupInfo, isFullInfo, backfill bool) error {
  1578. portal.roomCreateLock.Lock()
  1579. defer portal.roomCreateLock.Unlock()
  1580. if len(portal.MXID) > 0 {
  1581. return nil
  1582. }
  1583. intent := portal.MainIntent()
  1584. if err := intent.EnsureRegistered(); err != nil {
  1585. return err
  1586. }
  1587. portal.log.Infoln("Creating Matrix room. Info source:", user.MXID)
  1588. //var broadcastMetadata *types.BroadcastListInfo
  1589. if portal.IsPrivateChat() {
  1590. puppet := portal.bridge.GetPuppetByJID(portal.Key.JID)
  1591. puppet.SyncContact(user, true, false, "creating private chat portal")
  1592. portal.Name = puppet.Displayname
  1593. portal.AvatarURL = puppet.AvatarURL
  1594. portal.Avatar = puppet.Avatar
  1595. portal.Topic = PrivateChatTopic
  1596. } else if portal.IsStatusBroadcastList() {
  1597. if !portal.bridge.Config.Bridge.EnableStatusBroadcast {
  1598. portal.log.Debugln("Status bridging is disabled in config, not creating room after all")
  1599. return ErrStatusBroadcastDisabled
  1600. }
  1601. portal.Name = StatusBroadcastName
  1602. portal.Topic = StatusBroadcastTopic
  1603. } else if portal.IsBroadcastList() {
  1604. //var err error
  1605. //broadcastMetadata, err = user.Conn.GetBroadcastMetadata(portal.Key.JID)
  1606. //if err == nil && broadcastMetadata.Status == 200 {
  1607. // portal.Name = broadcastMetadata.Name
  1608. //} else {
  1609. // user.Conn.Store.ContactsLock.RLock()
  1610. // contact, _ := user.Conn.Store.Contacts[portal.Key.JID]
  1611. // user.Conn.Store.ContactsLock.RUnlock()
  1612. // portal.Name = contact.Name
  1613. //}
  1614. //if len(portal.Name) == 0 {
  1615. // portal.Name = UnnamedBroadcastName
  1616. //}
  1617. //portal.Topic = BroadcastTopic
  1618. portal.log.Debugln("Broadcast list is not yet supported, not creating room after all")
  1619. return fmt.Errorf("broadcast list bridging is currently not supported")
  1620. } else {
  1621. if groupInfo == nil || !isFullInfo {
  1622. foundInfo, err := user.Client.GetGroupInfo(portal.Key.JID)
  1623. // Ensure that the user is actually a participant in the conversation
  1624. // before creating the matrix room
  1625. if errors.Is(err, whatsmeow.ErrNotInGroup) {
  1626. user.log.Debugfln("Skipping creating matrix room for %s because the user is not a participant", portal.Key.JID)
  1627. user.bridge.DB.Backfill.DeleteAllForPortal(user.MXID, portal.Key)
  1628. user.bridge.DB.HistorySync.DeleteAllMessagesForPortal(user.MXID, portal.Key)
  1629. return err
  1630. } else if err != nil {
  1631. portal.log.Warnfln("Failed to get group info through %s: %v", user.JID, err)
  1632. } else {
  1633. groupInfo = foundInfo
  1634. isFullInfo = true
  1635. }
  1636. }
  1637. if groupInfo != nil {
  1638. portal.Name = groupInfo.Name
  1639. portal.Topic = groupInfo.Topic
  1640. portal.IsParent = groupInfo.IsParent
  1641. portal.ParentGroup = groupInfo.LinkedParentJID
  1642. if groupInfo.IsEphemeral {
  1643. portal.ExpirationTime = groupInfo.DisappearingTimer
  1644. }
  1645. }
  1646. portal.UpdateAvatar(user, types.EmptyJID, false)
  1647. }
  1648. powerLevels := portal.GetBasePowerLevels()
  1649. if groupInfo != nil {
  1650. if groupInfo.IsAnnounce {
  1651. powerLevels.EventsDefault = 50
  1652. }
  1653. if groupInfo.IsLocked {
  1654. powerLevels.EnsureEventLevel(event.StateRoomName, 50)
  1655. powerLevels.EnsureEventLevel(event.StateRoomAvatar, 50)
  1656. powerLevels.EnsureEventLevel(event.StateTopic, 50)
  1657. }
  1658. }
  1659. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  1660. initialState := []*event.Event{{
  1661. Type: event.StatePowerLevels,
  1662. Content: event.Content{
  1663. Parsed: powerLevels,
  1664. },
  1665. }, {
  1666. Type: event.StateBridge,
  1667. Content: event.Content{Parsed: bridgeInfo},
  1668. StateKey: &bridgeInfoStateKey,
  1669. }, {
  1670. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1671. Type: event.StateHalfShotBridge,
  1672. Content: event.Content{Parsed: bridgeInfo},
  1673. StateKey: &bridgeInfoStateKey,
  1674. }}
  1675. var invite []id.UserID
  1676. if portal.bridge.Config.Bridge.Encryption.Default {
  1677. initialState = append(initialState, &event.Event{
  1678. Type: event.StateEncryption,
  1679. Content: event.Content{
  1680. Parsed: portal.GetEncryptionEventContent(),
  1681. },
  1682. })
  1683. portal.Encrypted = true
  1684. if portal.IsPrivateChat() {
  1685. invite = append(invite, portal.bridge.Bot.UserID)
  1686. }
  1687. }
  1688. if !portal.AvatarURL.IsEmpty() && portal.shouldSetDMRoomMetadata() {
  1689. initialState = append(initialState, &event.Event{
  1690. Type: event.StateRoomAvatar,
  1691. Content: event.Content{
  1692. Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL},
  1693. },
  1694. })
  1695. portal.AvatarSet = true
  1696. } else {
  1697. portal.AvatarSet = false
  1698. }
  1699. creationContent := make(map[string]interface{})
  1700. if !portal.bridge.Config.Bridge.FederateRooms {
  1701. creationContent["m.federate"] = false
  1702. }
  1703. if portal.IsParent {
  1704. creationContent["type"] = event.RoomTypeSpace
  1705. } else if parent := portal.GetParentPortal(); parent != nil && parent.MXID != "" {
  1706. initialState = append(initialState, &event.Event{
  1707. Type: event.StateSpaceParent,
  1708. StateKey: proto.String(parent.MXID.String()),
  1709. Content: event.Content{
  1710. Parsed: &event.SpaceParentEventContent{
  1711. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1712. Canonical: true,
  1713. },
  1714. },
  1715. })
  1716. }
  1717. autoJoinInvites := portal.bridge.SpecVersions.Supports(mautrix.BeeperFeatureAutojoinInvites)
  1718. if autoJoinInvites {
  1719. portal.log.Debugfln("Hungryserv mode: adding all group members in create request")
  1720. if groupInfo != nil {
  1721. // TODO non-hungryserv could also include all members in invites, and then send joins manually?
  1722. participants, powerLevels := portal.SyncParticipants(user, groupInfo)
  1723. invite = append(invite, participants...)
  1724. if initialState[0].Type != event.StatePowerLevels {
  1725. panic(fmt.Errorf("unexpected type %s in first initial state event", initialState[0].Type.Type))
  1726. }
  1727. initialState[0].Content.Parsed = powerLevels
  1728. } else {
  1729. invite = append(invite, user.MXID)
  1730. }
  1731. }
  1732. req := &mautrix.ReqCreateRoom{
  1733. Visibility: "private",
  1734. Name: portal.Name,
  1735. Topic: portal.Topic,
  1736. Invite: invite,
  1737. Preset: "private_chat",
  1738. IsDirect: portal.IsPrivateChat(),
  1739. InitialState: initialState,
  1740. CreationContent: creationContent,
  1741. BeeperAutoJoinInvites: autoJoinInvites,
  1742. }
  1743. if !portal.shouldSetDMRoomMetadata() {
  1744. req.Name = ""
  1745. }
  1746. legacyBackfill := user.bridge.Config.Bridge.HistorySync.Backfill && backfill && !user.bridge.SpecVersions.Supports(mautrix.BeeperFeatureBatchSending)
  1747. var backfillStarted bool
  1748. if legacyBackfill {
  1749. portal.latestEventBackfillLock.Lock()
  1750. defer func() {
  1751. if !backfillStarted {
  1752. portal.latestEventBackfillLock.Unlock()
  1753. }
  1754. }()
  1755. }
  1756. resp, err := intent.CreateRoom(req)
  1757. if err != nil {
  1758. return err
  1759. }
  1760. portal.log.Infoln("Matrix room created:", resp.RoomID)
  1761. portal.InSpace = false
  1762. portal.NameSet = len(req.Name) > 0
  1763. portal.TopicSet = len(req.Topic) > 0
  1764. portal.MXID = resp.RoomID
  1765. portal.bridge.portalsLock.Lock()
  1766. portal.bridge.portalsByMXID[portal.MXID] = portal
  1767. portal.bridge.portalsLock.Unlock()
  1768. portal.Update(nil)
  1769. // We set the memberships beforehand to make sure the encryption key exchange in initial backfill knows the users are here.
  1770. inviteMembership := event.MembershipInvite
  1771. if autoJoinInvites {
  1772. inviteMembership = event.MembershipJoin
  1773. }
  1774. for _, userID := range invite {
  1775. portal.bridge.StateStore.SetMembership(portal.MXID, userID, inviteMembership)
  1776. }
  1777. if !autoJoinInvites {
  1778. portal.ensureUserInvited(user)
  1779. }
  1780. user.syncChatDoublePuppetDetails(portal, true)
  1781. go portal.updateCommunitySpace(user, true, true)
  1782. go portal.addToPersonalSpace(user)
  1783. if groupInfo != nil && !autoJoinInvites {
  1784. portal.SyncParticipants(user, groupInfo)
  1785. }
  1786. //if broadcastMetadata != nil {
  1787. // portal.SyncBroadcastRecipients(user, broadcastMetadata)
  1788. //}
  1789. if portal.IsPrivateChat() {
  1790. puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
  1791. if portal.bridge.Config.Bridge.Encryption.Default {
  1792. err = portal.bridge.Bot.EnsureJoined(portal.MXID)
  1793. if err != nil {
  1794. portal.log.Errorln("Failed to join created portal with bridge bot for e2be:", err)
  1795. }
  1796. }
  1797. user.UpdateDirectChats(map[id.UserID][]id.RoomID{puppet.MXID: {portal.MXID}})
  1798. } else if portal.IsParent {
  1799. portal.updateChildRooms()
  1800. }
  1801. firstEventResp, err := portal.MainIntent().SendMessageEvent(portal.MXID, PortalCreationDummyEvent, struct{}{})
  1802. if err != nil {
  1803. portal.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  1804. } else {
  1805. portal.FirstEventID = firstEventResp.EventID
  1806. portal.Update(nil)
  1807. }
  1808. if user.bridge.Config.Bridge.HistorySync.Backfill && backfill {
  1809. if legacyBackfill {
  1810. backfillStarted = true
  1811. go portal.legacyBackfill(user)
  1812. } else {
  1813. portals := []*Portal{portal}
  1814. user.EnqueueImmediateBackfills(portals)
  1815. user.EnqueueDeferredBackfills(portals)
  1816. user.BackfillQueue.ReCheck()
  1817. }
  1818. }
  1819. return nil
  1820. }
  1821. func (portal *Portal) addToPersonalSpace(user *User) {
  1822. spaceID := user.GetSpaceRoom()
  1823. if len(spaceID) == 0 || user.IsInSpace(portal.Key) {
  1824. return
  1825. }
  1826. _, err := portal.bridge.Bot.SendStateEvent(spaceID, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1827. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1828. })
  1829. if err != nil {
  1830. portal.log.Errorfln("Failed to add room to %s's personal filtering space (%s): %v", user.MXID, spaceID, err)
  1831. } else {
  1832. portal.log.Debugfln("Added room to %s's personal filtering space (%s)", user.MXID, spaceID)
  1833. user.MarkInSpace(portal.Key)
  1834. }
  1835. }
  1836. func (portal *Portal) removeSpaceParentEvent(space id.RoomID) {
  1837. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.String(), &event.SpaceParentEventContent{})
  1838. if err != nil {
  1839. portal.log.Warnfln("Failed to send m.space.parent event to remove portal from %s: %v", space, err)
  1840. }
  1841. }
  1842. func (portal *Portal) updateCommunitySpace(user *User, add, updateInfo bool) bool {
  1843. if add == portal.InSpace {
  1844. return false
  1845. }
  1846. space := portal.GetParentPortal()
  1847. if space == nil {
  1848. return false
  1849. } else if space.MXID == "" {
  1850. if !add || user == nil {
  1851. return false
  1852. }
  1853. portal.log.Debugfln("Creating portal for parent group %v", space.Key.JID)
  1854. err := space.CreateMatrixRoom(user, nil, false, false)
  1855. if err != nil {
  1856. portal.log.Debugfln("Failed to create portal for parent group: %v", err)
  1857. return false
  1858. }
  1859. }
  1860. var action string
  1861. var parentContent event.SpaceParentEventContent
  1862. var childContent event.SpaceChildEventContent
  1863. if add {
  1864. parentContent.Canonical = true
  1865. parentContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1866. childContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1867. action = "add portal to"
  1868. portal.log.Debugfln("Adding %s to space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1869. } else {
  1870. action = "remove portal from"
  1871. portal.log.Debugfln("Removing %s from space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1872. }
  1873. _, err := space.MainIntent().SendStateEvent(space.MXID, event.StateSpaceChild, portal.MXID.String(), &childContent)
  1874. if err != nil {
  1875. portal.log.Errorfln("Failed to send m.space.child event to %s %s: %v", action, space.MXID, err)
  1876. return false
  1877. }
  1878. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.MXID.String(), &parentContent)
  1879. if err != nil {
  1880. portal.log.Warnfln("Failed to send m.space.parent event to %s %s: %v", action, space.MXID, err)
  1881. }
  1882. portal.InSpace = add
  1883. if updateInfo {
  1884. portal.Update(nil)
  1885. portal.UpdateBridgeInfo()
  1886. }
  1887. return true
  1888. }
  1889. func (portal *Portal) IsPrivateChat() bool {
  1890. return portal.Key.JID.Server == types.DefaultUserServer
  1891. }
  1892. func (portal *Portal) IsGroupChat() bool {
  1893. return portal.Key.JID.Server == types.GroupServer
  1894. }
  1895. func (portal *Portal) IsBroadcastList() bool {
  1896. return portal.Key.JID.Server == types.BroadcastServer
  1897. }
  1898. func (portal *Portal) IsStatusBroadcastList() bool {
  1899. return portal.Key.JID == types.StatusBroadcastJID
  1900. }
  1901. func (portal *Portal) HasRelaybot() bool {
  1902. return portal.bridge.Config.Bridge.Relay.Enabled && len(portal.RelayUserID) > 0
  1903. }
  1904. func (portal *Portal) GetRelayUser() *User {
  1905. if !portal.HasRelaybot() {
  1906. return nil
  1907. } else if portal.relayUser == nil {
  1908. portal.relayUser = portal.bridge.GetUserByMXID(portal.RelayUserID)
  1909. }
  1910. return portal.relayUser
  1911. }
  1912. func (portal *Portal) GetParentPortal() *Portal {
  1913. if portal.ParentGroup.IsEmpty() {
  1914. return nil
  1915. } else if portal.parentPortal == nil {
  1916. portal.parentPortal = portal.bridge.GetPortalByJID(database.NewPortalKey(portal.ParentGroup, portal.ParentGroup))
  1917. }
  1918. return portal.parentPortal
  1919. }
  1920. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  1921. if portal.IsPrivateChat() {
  1922. return portal.bridge.GetPuppetByJID(portal.Key.JID).DefaultIntent()
  1923. }
  1924. return portal.bridge.Bot
  1925. }
  1926. func (portal *Portal) addReplyMention(content *event.MessageEventContent, sender types.JID, senderMXID id.UserID) {
  1927. if content.Mentions == nil || (sender.IsEmpty() && senderMXID == "") {
  1928. return
  1929. }
  1930. // TODO handle lids
  1931. if senderMXID == "" && sender.Server == types.DefaultUserServer {
  1932. if user := portal.bridge.GetUserByJID(sender); user != nil {
  1933. senderMXID = user.MXID
  1934. } else {
  1935. puppet := portal.bridge.GetPuppetByJID(sender)
  1936. senderMXID = puppet.MXID
  1937. }
  1938. }
  1939. if senderMXID != "" && !slices.Contains(content.Mentions.UserIDs, senderMXID) {
  1940. content.Mentions.UserIDs = append(content.Mentions.UserIDs, senderMXID)
  1941. }
  1942. }
  1943. func (portal *Portal) SetReply(msgID string, content *event.MessageEventContent, replyTo *ReplyInfo, isHungryBackfill bool) bool {
  1944. if replyTo == nil {
  1945. return false
  1946. }
  1947. log := portal.zlog.With().
  1948. Str("message_id", msgID).
  1949. Object("reply_to", replyTo).
  1950. Str("action", "SetReply").
  1951. Logger()
  1952. key := portal.Key
  1953. targetPortal := portal
  1954. defer func() {
  1955. if content.RelatesTo != nil && content.RelatesTo.InReplyTo != nil && targetPortal != portal {
  1956. content.RelatesTo.InReplyTo.UnstableRoomID = targetPortal.MXID
  1957. }
  1958. }()
  1959. if portal.bridge.Config.Bridge.CrossRoomReplies && !replyTo.Chat.IsEmpty() && replyTo.Chat != key.JID {
  1960. if replyTo.Chat.Server == types.GroupServer {
  1961. key = database.NewPortalKey(replyTo.Chat, types.EmptyJID)
  1962. } else if replyTo.Chat == types.StatusBroadcastJID {
  1963. key = database.NewPortalKey(replyTo.Chat, key.Receiver)
  1964. }
  1965. if key != portal.Key {
  1966. targetPortal = portal.bridge.GetExistingPortalByJID(key)
  1967. if targetPortal == nil {
  1968. return false
  1969. }
  1970. }
  1971. }
  1972. message := portal.bridge.DB.Message.GetByJID(key, replyTo.MessageID)
  1973. if message == nil || message.IsFakeMXID() {
  1974. if isHungryBackfill {
  1975. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(targetPortal.deterministicEventID(replyTo.Sender, replyTo.MessageID, ""))
  1976. portal.addReplyMention(content, replyTo.Sender, "")
  1977. return true
  1978. } else {
  1979. log.Warn().Msg("Failed to find reply target")
  1980. }
  1981. return false
  1982. }
  1983. portal.addReplyMention(content, message.Sender, message.SenderMXID)
  1984. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(message.MXID)
  1985. if portal.bridge.Config.Bridge.DisableReplyFallbacks {
  1986. return true
  1987. }
  1988. evt, err := targetPortal.MainIntent().GetEvent(targetPortal.MXID, message.MXID)
  1989. if err != nil {
  1990. log.Warn().Err(err).Msg("Failed to get reply target event")
  1991. return true
  1992. }
  1993. _ = evt.Content.ParseRaw(evt.Type)
  1994. if evt.Type == event.EventEncrypted {
  1995. decryptedEvt, err := portal.bridge.Crypto.Decrypt(evt)
  1996. if err != nil {
  1997. log.Warn().Err(err).Msg("Failed to decrypt reply target event")
  1998. } else {
  1999. evt = decryptedEvt
  2000. }
  2001. }
  2002. content.SetReply(evt)
  2003. return true
  2004. }
  2005. func (portal *Portal) HandleMessageReaction(intent *appservice.IntentAPI, user *User, info *types.MessageInfo, reaction *waProto.ReactionMessage, existingMsg *database.Message) {
  2006. if existingMsg != nil {
  2007. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  2008. Reason: "The undecryptable message was actually a reaction",
  2009. })
  2010. }
  2011. targetJID := reaction.GetKey().GetId()
  2012. if reaction.GetText() == "" {
  2013. existing := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, info.Sender)
  2014. if existing == nil {
  2015. portal.log.Debugfln("Dropping removal %s of unknown reaction to %s from %s", info.ID, targetJID, info.Sender)
  2016. return
  2017. }
  2018. resp, err := intent.RedactEvent(portal.MXID, existing.MXID)
  2019. if err != nil {
  2020. portal.log.Errorfln("Failed to redact reaction %s/%s from %s to %s: %v", existing.MXID, existing.JID, info.Sender, targetJID, err)
  2021. }
  2022. portal.finishHandling(existingMsg, info, resp.EventID, intent.UserID, database.MsgReaction, 0, database.MsgNoError)
  2023. existing.Delete()
  2024. } else {
  2025. target := portal.bridge.DB.Message.GetByJID(portal.Key, targetJID)
  2026. if target == nil {
  2027. portal.log.Debugfln("Dropping reaction %s from %s to unknown message %s", info.ID, info.Sender, targetJID)
  2028. return
  2029. }
  2030. var content event.ReactionEventContent
  2031. content.RelatesTo = event.RelatesTo{
  2032. Type: event.RelAnnotation,
  2033. EventID: target.MXID,
  2034. Key: variationselector.Add(reaction.GetText()),
  2035. }
  2036. resp, err := intent.SendMassagedMessageEvent(portal.MXID, event.EventReaction, &content, info.Timestamp.UnixMilli())
  2037. if err != nil {
  2038. portal.log.Errorfln("Failed to bridge reaction %s from %s to %s: %v", info.ID, info.Sender, target.JID, err)
  2039. return
  2040. }
  2041. portal.finishHandling(existingMsg, info, resp.EventID, intent.UserID, database.MsgReaction, 0, database.MsgNoError)
  2042. portal.upsertReaction(nil, intent, target.JID, info.Sender, resp.EventID, info.ID)
  2043. }
  2044. }
  2045. func (portal *Portal) HandleMessageRevoke(user *User, info *types.MessageInfo, key *waProto.MessageKey) bool {
  2046. msg := portal.bridge.DB.Message.GetByJID(portal.Key, key.GetId())
  2047. if msg == nil || msg.IsFakeMXID() {
  2048. return false
  2049. }
  2050. intent := portal.bridge.GetPuppetByJID(info.Sender).IntentFor(portal)
  2051. _, err := intent.RedactEvent(portal.MXID, msg.MXID)
  2052. if err != nil {
  2053. if errors.Is(err, mautrix.MForbidden) {
  2054. _, err = portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  2055. if err != nil {
  2056. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  2057. }
  2058. }
  2059. } else {
  2060. msg.Delete()
  2061. }
  2062. return true
  2063. }
  2064. func (portal *Portal) deleteForMe(user *User, content *events.DeleteForMe) bool {
  2065. matrixUsers, err := portal.GetMatrixUsers()
  2066. if err != nil {
  2067. portal.log.Errorln("Failed to get Matrix users in portal to see if DeleteForMe should be handled:", err)
  2068. return false
  2069. }
  2070. if len(matrixUsers) == 1 && matrixUsers[0] == user.MXID {
  2071. msg := portal.bridge.DB.Message.GetByJID(portal.Key, content.MessageID)
  2072. if msg == nil || msg.IsFakeMXID() {
  2073. return false
  2074. }
  2075. _, err := portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  2076. if err != nil {
  2077. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  2078. } else {
  2079. msg.Delete()
  2080. }
  2081. return true
  2082. }
  2083. return false
  2084. }
  2085. func (portal *Portal) sendMainIntentMessage(content *event.MessageEventContent) (*mautrix.RespSendEvent, error) {
  2086. return portal.sendMessage(portal.MainIntent(), event.EventMessage, content, nil, 0)
  2087. }
  2088. func (portal *Portal) encrypt(intent *appservice.IntentAPI, content *event.Content, eventType event.Type) (event.Type, error) {
  2089. if !portal.Encrypted || portal.bridge.Crypto == nil {
  2090. return eventType, nil
  2091. }
  2092. intent.AddDoublePuppetValue(content)
  2093. // TODO maybe the locking should be inside mautrix-go?
  2094. portal.encryptLock.Lock()
  2095. defer portal.encryptLock.Unlock()
  2096. err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, content)
  2097. if err != nil {
  2098. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  2099. }
  2100. return event.EventEncrypted, nil
  2101. }
  2102. func (portal *Portal) sendMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  2103. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  2104. var err error
  2105. eventType, err = portal.encrypt(intent, &wrappedContent, eventType)
  2106. if err != nil {
  2107. return nil, err
  2108. }
  2109. _, _ = intent.UserTyping(portal.MXID, false, 0)
  2110. if timestamp == 0 {
  2111. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  2112. } else {
  2113. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  2114. }
  2115. }
  2116. type ReplyInfo struct {
  2117. MessageID types.MessageID
  2118. Chat types.JID
  2119. Sender types.JID
  2120. }
  2121. func (r *ReplyInfo) Equals(other *ReplyInfo) bool {
  2122. if r == nil {
  2123. return other == nil
  2124. } else if other == nil {
  2125. return false
  2126. }
  2127. return r.MessageID == other.MessageID && r.Chat == other.Chat && r.Sender == other.Sender
  2128. }
  2129. func (r ReplyInfo) MarshalZerologObject(e *zerolog.Event) {
  2130. e.Str("message_id", r.MessageID)
  2131. e.Str("chat_jid", r.Chat.String())
  2132. e.Str("sender_jid", r.Sender.String())
  2133. }
  2134. type Replyable interface {
  2135. GetStanzaId() string
  2136. GetParticipant() string
  2137. GetRemoteJid() string
  2138. }
  2139. func GetReply(replyable Replyable) *ReplyInfo {
  2140. if replyable.GetStanzaId() == "" {
  2141. return nil
  2142. }
  2143. sender, err := types.ParseJID(replyable.GetParticipant())
  2144. if err != nil {
  2145. return nil
  2146. }
  2147. chat, _ := types.ParseJID(replyable.GetRemoteJid())
  2148. return &ReplyInfo{
  2149. MessageID: types.MessageID(replyable.GetStanzaId()),
  2150. Chat: chat,
  2151. Sender: sender,
  2152. }
  2153. }
  2154. type ConvertedMessage struct {
  2155. Intent *appservice.IntentAPI
  2156. Type event.Type
  2157. Content *event.MessageEventContent
  2158. Extra map[string]interface{}
  2159. Caption *event.MessageEventContent
  2160. MultiEvent []*event.MessageEventContent
  2161. ReplyTo *ReplyInfo
  2162. ExpiresIn time.Duration
  2163. Error database.MessageErrorType
  2164. MediaKey []byte
  2165. }
  2166. func (cm *ConvertedMessage) MergeCaption() {
  2167. if cm.Caption == nil {
  2168. return
  2169. }
  2170. cm.Content.FileName = cm.Content.Body
  2171. extensibleCaption := map[string]interface{}{
  2172. "org.matrix.msc1767.text": cm.Caption.Body,
  2173. }
  2174. cm.Extra["org.matrix.msc1767.caption"] = extensibleCaption
  2175. cm.Content.Body = cm.Caption.Body
  2176. if cm.Caption.Format == event.FormatHTML {
  2177. cm.Content.Format = event.FormatHTML
  2178. cm.Content.FormattedBody = cm.Caption.FormattedBody
  2179. extensibleCaption["org.matrix.msc1767.html"] = cm.Caption.FormattedBody
  2180. }
  2181. cm.Caption = nil
  2182. }
  2183. func (portal *Portal) convertTextMessage(intent *appservice.IntentAPI, source *User, msg *waProto.Message) *ConvertedMessage {
  2184. content := &event.MessageEventContent{
  2185. Body: msg.GetConversation(),
  2186. MsgType: event.MsgText,
  2187. }
  2188. if len(msg.GetExtendedTextMessage().GetText()) > 0 {
  2189. content.Body = msg.GetExtendedTextMessage().GetText()
  2190. }
  2191. contextInfo := msg.GetExtendedTextMessage().GetContextInfo()
  2192. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, content, contextInfo.GetMentionedJid(), false, false)
  2193. expiresIn := time.Duration(contextInfo.GetExpiration()) * time.Second
  2194. extraAttrs := map[string]interface{}{}
  2195. extraAttrs["com.beeper.linkpreviews"] = portal.convertURLPreviewToBeeper(intent, source, msg.GetExtendedTextMessage())
  2196. return &ConvertedMessage{
  2197. Intent: intent,
  2198. Type: event.EventMessage,
  2199. Content: content,
  2200. ReplyTo: GetReply(contextInfo),
  2201. ExpiresIn: expiresIn,
  2202. Extra: extraAttrs,
  2203. }
  2204. }
  2205. func (portal *Portal) convertTemplateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, tplMsg *waProto.TemplateMessage) *ConvertedMessage {
  2206. converted := &ConvertedMessage{
  2207. Intent: intent,
  2208. Type: event.EventMessage,
  2209. Content: &event.MessageEventContent{
  2210. Body: "Unsupported business message",
  2211. MsgType: event.MsgText,
  2212. },
  2213. ReplyTo: GetReply(tplMsg.GetContextInfo()),
  2214. ExpiresIn: time.Duration(tplMsg.GetContextInfo().GetExpiration()) * time.Second,
  2215. }
  2216. tpl := tplMsg.GetHydratedTemplate()
  2217. if tpl == nil {
  2218. return converted
  2219. }
  2220. content := tpl.GetHydratedContentText()
  2221. if buttons := tpl.GetHydratedButtons(); len(buttons) > 0 {
  2222. addButtonText := false
  2223. descriptions := make([]string, len(buttons))
  2224. for i, rawButton := range buttons {
  2225. switch button := rawButton.GetHydratedButton().(type) {
  2226. case *waProto.HydratedTemplateButton_QuickReplyButton:
  2227. descriptions[i] = fmt.Sprintf("<%s>", button.QuickReplyButton.GetDisplayText())
  2228. addButtonText = true
  2229. case *waProto.HydratedTemplateButton_UrlButton:
  2230. descriptions[i] = fmt.Sprintf("[%s](%s)", button.UrlButton.GetDisplayText(), button.UrlButton.GetUrl())
  2231. case *waProto.HydratedTemplateButton_CallButton:
  2232. descriptions[i] = fmt.Sprintf("[%s](tel:%s)", button.CallButton.GetDisplayText(), button.CallButton.GetPhoneNumber())
  2233. }
  2234. }
  2235. description := strings.Join(descriptions, " - ")
  2236. if addButtonText {
  2237. description += "\nUse the WhatsApp app to click buttons"
  2238. }
  2239. content = fmt.Sprintf("%s\n\n%s", content, description)
  2240. }
  2241. if footer := tpl.GetHydratedFooterText(); footer != "" {
  2242. content = fmt.Sprintf("%s\n\n%s", content, footer)
  2243. }
  2244. var convertedTitle *ConvertedMessage
  2245. switch title := tpl.GetTitle().(type) {
  2246. case *waProto.TemplateMessage_HydratedFourRowTemplate_DocumentMessage:
  2247. convertedTitle = portal.convertMediaMessage(intent, source, info, title.DocumentMessage, "file attachment", false)
  2248. case *waProto.TemplateMessage_HydratedFourRowTemplate_ImageMessage:
  2249. convertedTitle = portal.convertMediaMessage(intent, source, info, title.ImageMessage, "photo", false)
  2250. case *waProto.TemplateMessage_HydratedFourRowTemplate_VideoMessage:
  2251. convertedTitle = portal.convertMediaMessage(intent, source, info, title.VideoMessage, "video attachment", false)
  2252. case *waProto.TemplateMessage_HydratedFourRowTemplate_LocationMessage:
  2253. content = fmt.Sprintf("Unsupported location message\n\n%s", content)
  2254. case *waProto.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText:
  2255. content = fmt.Sprintf("%s\n\n%s", title.HydratedTitleText, content)
  2256. }
  2257. converted.Content.Body = content
  2258. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, true, false)
  2259. if convertedTitle != nil {
  2260. converted.MediaKey = convertedTitle.MediaKey
  2261. converted.Extra = convertedTitle.Extra
  2262. converted.Caption = converted.Content
  2263. converted.Content = convertedTitle.Content
  2264. converted.Error = convertedTitle.Error
  2265. }
  2266. if converted.Extra == nil {
  2267. converted.Extra = make(map[string]interface{})
  2268. }
  2269. converted.Extra["fi.mau.whatsapp.hydrated_template_id"] = tpl.GetTemplateId()
  2270. return converted
  2271. }
  2272. func (portal *Portal) convertTemplateButtonReplyMessage(intent *appservice.IntentAPI, msg *waProto.TemplateButtonReplyMessage) *ConvertedMessage {
  2273. return &ConvertedMessage{
  2274. Intent: intent,
  2275. Type: event.EventMessage,
  2276. Content: &event.MessageEventContent{
  2277. Body: msg.GetSelectedDisplayText(),
  2278. MsgType: event.MsgText,
  2279. },
  2280. Extra: map[string]interface{}{
  2281. "fi.mau.whatsapp.template_button_reply": map[string]interface{}{
  2282. "id": msg.GetSelectedId(),
  2283. "index": msg.GetSelectedIndex(),
  2284. },
  2285. },
  2286. ReplyTo: GetReply(msg.GetContextInfo()),
  2287. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2288. }
  2289. }
  2290. func (portal *Portal) convertListMessage(intent *appservice.IntentAPI, source *User, msg *waProto.ListMessage) *ConvertedMessage {
  2291. converted := &ConvertedMessage{
  2292. Intent: intent,
  2293. Type: event.EventMessage,
  2294. Content: &event.MessageEventContent{
  2295. Body: "Unsupported business message",
  2296. MsgType: event.MsgText,
  2297. },
  2298. ReplyTo: GetReply(msg.GetContextInfo()),
  2299. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2300. }
  2301. body := msg.GetDescription()
  2302. if msg.GetTitle() != "" {
  2303. if body == "" {
  2304. body = msg.GetTitle()
  2305. } else {
  2306. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), body)
  2307. }
  2308. }
  2309. randomID := random.String(64)
  2310. body = fmt.Sprintf("%s\n%s", body, randomID)
  2311. if msg.GetFooterText() != "" {
  2312. body = fmt.Sprintf("%s\n\n%s", body, msg.GetFooterText())
  2313. }
  2314. converted.Content.Body = body
  2315. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, false, true)
  2316. var optionsMarkdown strings.Builder
  2317. _, _ = fmt.Fprintf(&optionsMarkdown, "#### %s\n", msg.GetButtonText())
  2318. for _, section := range msg.GetSections() {
  2319. nesting := ""
  2320. if section.GetTitle() != "" {
  2321. _, _ = fmt.Fprintf(&optionsMarkdown, "* %s\n", section.GetTitle())
  2322. nesting = " "
  2323. }
  2324. for _, row := range section.GetRows() {
  2325. if row.GetDescription() != "" {
  2326. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s: %s\n", nesting, row.GetTitle(), row.GetDescription())
  2327. } else {
  2328. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s\n", nesting, row.GetTitle())
  2329. }
  2330. }
  2331. }
  2332. optionsMarkdown.WriteString("\nUse the WhatsApp app to respond")
  2333. rendered := format.RenderMarkdown(optionsMarkdown.String(), true, false)
  2334. converted.Content.Body = strings.Replace(converted.Content.Body, randomID, rendered.Body, 1)
  2335. converted.Content.FormattedBody = strings.Replace(converted.Content.FormattedBody, randomID, rendered.FormattedBody, 1)
  2336. return converted
  2337. }
  2338. func (portal *Portal) convertListResponseMessage(intent *appservice.IntentAPI, msg *waProto.ListResponseMessage) *ConvertedMessage {
  2339. var body string
  2340. if msg.GetTitle() != "" {
  2341. if msg.GetDescription() != "" {
  2342. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), msg.GetDescription())
  2343. } else {
  2344. body = msg.GetTitle()
  2345. }
  2346. } else if msg.GetDescription() != "" {
  2347. body = msg.GetDescription()
  2348. } else {
  2349. body = "Unsupported list reply message"
  2350. }
  2351. return &ConvertedMessage{
  2352. Intent: intent,
  2353. Type: event.EventMessage,
  2354. Content: &event.MessageEventContent{
  2355. Body: body,
  2356. MsgType: event.MsgText,
  2357. },
  2358. Extra: map[string]interface{}{
  2359. "fi.mau.whatsapp.list_reply": map[string]interface{}{
  2360. "row_id": msg.GetSingleSelectReply().GetSelectedRowId(),
  2361. },
  2362. },
  2363. ReplyTo: GetReply(msg.GetContextInfo()),
  2364. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2365. }
  2366. }
  2367. func (portal *Portal) convertPollUpdateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg *waProto.PollUpdateMessage) *ConvertedMessage {
  2368. pollMessage := portal.bridge.DB.Message.GetByJID(portal.Key, msg.GetPollCreationMessageKey().GetId())
  2369. if pollMessage == nil {
  2370. portal.log.Warnfln("Failed to convert vote message %s: poll message %s not found", info.ID, msg.GetPollCreationMessageKey().GetId())
  2371. return nil
  2372. }
  2373. vote, err := source.Client.DecryptPollVote(&events.Message{
  2374. Info: *info,
  2375. Message: &waProto.Message{PollUpdateMessage: msg},
  2376. })
  2377. if err != nil {
  2378. portal.log.Errorfln("Failed to decrypt vote message %s: %v", info.ID, err)
  2379. return nil
  2380. }
  2381. selectedHashes := make([]string, len(vote.GetSelectedOptions()))
  2382. if pollMessage.Type == database.MsgMatrixPoll {
  2383. mappedAnswers := pollMessage.GetPollOptionIDs(vote.GetSelectedOptions())
  2384. for i, opt := range vote.GetSelectedOptions() {
  2385. if len(opt) != 32 {
  2386. portal.log.Warnfln("Unexpected option hash length %d in %s's vote to %s", len(opt), info.Sender, pollMessage.MXID)
  2387. continue
  2388. }
  2389. var ok bool
  2390. selectedHashes[i], ok = mappedAnswers[*(*[32]byte)(opt)]
  2391. if !ok {
  2392. portal.log.Warnfln("Didn't find ID for option %X in %s's vote to %s", opt, info.Sender, pollMessage.MXID)
  2393. }
  2394. }
  2395. } else {
  2396. for i, opt := range vote.GetSelectedOptions() {
  2397. selectedHashes[i] = hex.EncodeToString(opt)
  2398. }
  2399. }
  2400. evtType := TypeMSC3381PollResponse
  2401. //if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2402. // evtType = TypeMSC3381V2PollResponse
  2403. //}
  2404. return &ConvertedMessage{
  2405. Intent: intent,
  2406. Type: evtType,
  2407. Content: &event.MessageEventContent{
  2408. RelatesTo: &event.RelatesTo{
  2409. Type: event.RelReference,
  2410. EventID: pollMessage.MXID,
  2411. },
  2412. },
  2413. Extra: map[string]any{
  2414. "org.matrix.msc3381.poll.response": map[string]any{
  2415. "answers": selectedHashes,
  2416. },
  2417. "org.matrix.msc3381.v2.selections": selectedHashes,
  2418. },
  2419. }
  2420. }
  2421. func (portal *Portal) convertPollCreationMessage(intent *appservice.IntentAPI, msg *waProto.PollCreationMessage) *ConvertedMessage {
  2422. optionNames := make([]string, len(msg.GetOptions()))
  2423. optionsListText := make([]string, len(optionNames))
  2424. optionsListHTML := make([]string, len(optionNames))
  2425. msc3381Answers := make([]map[string]any, len(optionNames))
  2426. msc3381V2Answers := make([]map[string]any, len(optionNames))
  2427. for i, opt := range msg.GetOptions() {
  2428. optionNames[i] = opt.GetOptionName()
  2429. optionsListText[i] = fmt.Sprintf("%d. %s\n", i+1, optionNames[i])
  2430. optionsListHTML[i] = fmt.Sprintf("<li>%s</li>", event.TextToHTML(optionNames[i]))
  2431. optionHash := sha256.Sum256([]byte(opt.GetOptionName()))
  2432. optionHashStr := hex.EncodeToString(optionHash[:])
  2433. msc3381Answers[i] = map[string]any{
  2434. "id": optionHashStr,
  2435. "org.matrix.msc1767.text": opt.GetOptionName(),
  2436. }
  2437. msc3381V2Answers[i] = map[string]any{
  2438. "org.matrix.msc3381.v2.id": optionHashStr,
  2439. "org.matrix.msc1767.markup": []map[string]any{
  2440. {"mimetype": "text/plain", "body": opt.GetOptionName()},
  2441. },
  2442. }
  2443. }
  2444. body := fmt.Sprintf("%s\n\n%s", msg.GetName(), strings.Join(optionsListText, "\n"))
  2445. formattedBody := fmt.Sprintf("<p>%s</p><ol>%s</ol>", event.TextToHTML(msg.GetName()), strings.Join(optionsListHTML, ""))
  2446. maxChoices := int(msg.GetSelectableOptionsCount())
  2447. if maxChoices <= 0 {
  2448. maxChoices = len(optionNames)
  2449. }
  2450. evtType := event.EventMessage
  2451. if portal.bridge.Config.Bridge.ExtEvPolls {
  2452. evtType = TypeMSC3381PollStart
  2453. }
  2454. //else if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2455. // evtType.Type = "org.matrix.msc3381.v2.poll.start"
  2456. //}
  2457. return &ConvertedMessage{
  2458. Intent: intent,
  2459. Type: evtType,
  2460. Content: &event.MessageEventContent{
  2461. Body: body,
  2462. MsgType: event.MsgText,
  2463. Format: event.FormatHTML,
  2464. FormattedBody: formattedBody,
  2465. },
  2466. Extra: map[string]any{
  2467. // Custom metadata
  2468. "fi.mau.whatsapp.poll": map[string]any{
  2469. "option_names": optionNames,
  2470. "selectable_options_count": msg.GetSelectableOptionsCount(),
  2471. },
  2472. // Current extensible events (as of November 2022)
  2473. "org.matrix.msc1767.markup": []map[string]any{
  2474. {"mimetype": "text/html", "body": formattedBody},
  2475. {"mimetype": "text/plain", "body": body},
  2476. },
  2477. "org.matrix.msc3381.v2.poll": map[string]any{
  2478. "kind": "org.matrix.msc3381.v2.disclosed",
  2479. "max_selections": maxChoices,
  2480. "question": map[string]any{
  2481. "org.matrix.msc1767.markup": []map[string]any{
  2482. {"mimetype": "text/plain", "body": msg.GetName()},
  2483. },
  2484. },
  2485. "answers": msc3381V2Answers,
  2486. },
  2487. // Legacy extensible events
  2488. "org.matrix.msc1767.message": []map[string]any{
  2489. {"mimetype": "text/html", "body": formattedBody},
  2490. {"mimetype": "text/plain", "body": body},
  2491. },
  2492. "org.matrix.msc3381.poll.start": map[string]any{
  2493. "kind": "org.matrix.msc3381.poll.disclosed",
  2494. "max_selections": maxChoices,
  2495. "question": map[string]any{
  2496. "org.matrix.msc1767.text": msg.GetName(),
  2497. },
  2498. "answers": msc3381Answers,
  2499. },
  2500. },
  2501. ReplyTo: GetReply(msg.GetContextInfo()),
  2502. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2503. }
  2504. }
  2505. func (portal *Portal) convertLiveLocationMessage(intent *appservice.IntentAPI, msg *waProto.LiveLocationMessage) *ConvertedMessage {
  2506. content := &event.MessageEventContent{
  2507. Body: "Started sharing live location",
  2508. MsgType: event.MsgNotice,
  2509. }
  2510. if len(msg.GetCaption()) > 0 {
  2511. content.Body += ": " + msg.GetCaption()
  2512. }
  2513. return &ConvertedMessage{
  2514. Intent: intent,
  2515. Type: event.EventMessage,
  2516. Content: content,
  2517. ReplyTo: GetReply(msg.GetContextInfo()),
  2518. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2519. }
  2520. }
  2521. func (portal *Portal) convertLocationMessage(intent *appservice.IntentAPI, msg *waProto.LocationMessage) *ConvertedMessage {
  2522. url := msg.GetUrl()
  2523. if len(url) == 0 {
  2524. url = fmt.Sprintf("https://maps.google.com/?q=%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude())
  2525. }
  2526. name := msg.GetName()
  2527. if len(name) == 0 {
  2528. latChar := 'N'
  2529. if msg.GetDegreesLatitude() < 0 {
  2530. latChar = 'S'
  2531. }
  2532. longChar := 'E'
  2533. if msg.GetDegreesLongitude() < 0 {
  2534. longChar = 'W'
  2535. }
  2536. name = fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(msg.GetDegreesLatitude()), latChar, math.Abs(msg.GetDegreesLongitude()), longChar)
  2537. }
  2538. content := &event.MessageEventContent{
  2539. MsgType: event.MsgLocation,
  2540. Body: fmt.Sprintf("Location: %s\n%s\n%s", name, msg.GetAddress(), url),
  2541. Format: event.FormatHTML,
  2542. FormattedBody: fmt.Sprintf("Location: <a href='%s'>%s</a><br>%s", url, name, msg.GetAddress()),
  2543. GeoURI: fmt.Sprintf("geo:%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude()),
  2544. }
  2545. if len(msg.GetJpegThumbnail()) > 0 {
  2546. thumbnailMime := http.DetectContentType(msg.GetJpegThumbnail())
  2547. uploadedThumbnail, _ := intent.UploadBytes(msg.GetJpegThumbnail(), thumbnailMime)
  2548. if uploadedThumbnail != nil {
  2549. cfg, _, _ := image.DecodeConfig(bytes.NewReader(msg.GetJpegThumbnail()))
  2550. content.Info = &event.FileInfo{
  2551. ThumbnailInfo: &event.FileInfo{
  2552. Size: len(msg.GetJpegThumbnail()),
  2553. Width: cfg.Width,
  2554. Height: cfg.Height,
  2555. MimeType: thumbnailMime,
  2556. },
  2557. ThumbnailURL: uploadedThumbnail.ContentURI.CUString(),
  2558. }
  2559. }
  2560. }
  2561. return &ConvertedMessage{
  2562. Intent: intent,
  2563. Type: event.EventMessage,
  2564. Content: content,
  2565. ReplyTo: GetReply(msg.GetContextInfo()),
  2566. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2567. }
  2568. }
  2569. const inviteMsg = `%s<hr/>This invitation to join "%s" expires at %s. Reply to this message with <code>!wa accept</code> to accept the invite.`
  2570. const inviteMetaField = "fi.mau.whatsapp.invite"
  2571. const escapedInviteMetaField = `fi\.mau\.whatsapp\.invite`
  2572. type InviteMeta struct {
  2573. JID types.JID `json:"jid"`
  2574. Code string `json:"code"`
  2575. Expiration int64 `json:"expiration,string"`
  2576. Inviter types.JID `json:"inviter"`
  2577. }
  2578. func (portal *Portal) convertGroupInviteMessage(intent *appservice.IntentAPI, info *types.MessageInfo, msg *waProto.GroupInviteMessage) *ConvertedMessage {
  2579. expiry := time.Unix(msg.GetInviteExpiration(), 0)
  2580. htmlMessage := fmt.Sprintf(inviteMsg, event.TextToHTML(msg.GetCaption()), msg.GetGroupName(), expiry)
  2581. content := &event.MessageEventContent{
  2582. MsgType: event.MsgText,
  2583. Body: format.HTMLToText(htmlMessage),
  2584. Format: event.FormatHTML,
  2585. FormattedBody: htmlMessage,
  2586. }
  2587. groupJID, err := types.ParseJID(msg.GetGroupJid())
  2588. if err != nil {
  2589. portal.log.Errorfln("Failed to parse invite group JID: %v", err)
  2590. }
  2591. extraAttrs := map[string]interface{}{
  2592. inviteMetaField: InviteMeta{
  2593. JID: groupJID,
  2594. Code: msg.GetInviteCode(),
  2595. Expiration: msg.GetInviteExpiration(),
  2596. Inviter: info.Sender.ToNonAD(),
  2597. },
  2598. }
  2599. return &ConvertedMessage{
  2600. Intent: intent,
  2601. Type: event.EventMessage,
  2602. Content: content,
  2603. Extra: extraAttrs,
  2604. ReplyTo: GetReply(msg.GetContextInfo()),
  2605. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2606. }
  2607. }
  2608. func (portal *Portal) convertContactMessage(intent *appservice.IntentAPI, msg *waProto.ContactMessage) *ConvertedMessage {
  2609. fileName := fmt.Sprintf("%s.vcf", msg.GetDisplayName())
  2610. data := []byte(msg.GetVcard())
  2611. mimeType := "text/vcard"
  2612. uploadMimeType, file := portal.encryptFileInPlace(data, mimeType)
  2613. uploadResp, err := intent.UploadBytesWithName(data, uploadMimeType, fileName)
  2614. if err != nil {
  2615. portal.log.Errorfln("Failed to upload vcard of %s: %v", msg.GetDisplayName(), err)
  2616. return nil
  2617. }
  2618. content := &event.MessageEventContent{
  2619. Body: fileName,
  2620. MsgType: event.MsgFile,
  2621. File: file,
  2622. Info: &event.FileInfo{
  2623. MimeType: mimeType,
  2624. Size: len(msg.GetVcard()),
  2625. },
  2626. }
  2627. if content.File != nil {
  2628. content.File.URL = uploadResp.ContentURI.CUString()
  2629. } else {
  2630. content.URL = uploadResp.ContentURI.CUString()
  2631. }
  2632. return &ConvertedMessage{
  2633. Intent: intent,
  2634. Type: event.EventMessage,
  2635. Content: content,
  2636. ReplyTo: GetReply(msg.GetContextInfo()),
  2637. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2638. }
  2639. }
  2640. func (portal *Portal) convertContactsArrayMessage(intent *appservice.IntentAPI, msg *waProto.ContactsArrayMessage) *ConvertedMessage {
  2641. name := msg.GetDisplayName()
  2642. if len(name) == 0 {
  2643. name = fmt.Sprintf("%d contacts", len(msg.GetContacts()))
  2644. }
  2645. contacts := make([]*event.MessageEventContent, 0, len(msg.GetContacts()))
  2646. for _, contact := range msg.GetContacts() {
  2647. converted := portal.convertContactMessage(intent, contact)
  2648. if converted != nil {
  2649. contacts = append(contacts, converted.Content)
  2650. }
  2651. }
  2652. return &ConvertedMessage{
  2653. Intent: intent,
  2654. Type: event.EventMessage,
  2655. Content: &event.MessageEventContent{
  2656. MsgType: event.MsgNotice,
  2657. Body: fmt.Sprintf("Sent %s", name),
  2658. },
  2659. ReplyTo: GetReply(msg.GetContextInfo()),
  2660. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2661. MultiEvent: contacts,
  2662. }
  2663. }
  2664. func (portal *Portal) tryKickUser(userID id.UserID, intent *appservice.IntentAPI) error {
  2665. _, err := intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2666. if err != nil {
  2667. httpErr, ok := err.(mautrix.HTTPError)
  2668. if ok && httpErr.RespError != nil && httpErr.RespError.ErrCode == "M_FORBIDDEN" {
  2669. _, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2670. }
  2671. }
  2672. return err
  2673. }
  2674. func (portal *Portal) removeUser(isSameUser bool, kicker *appservice.IntentAPI, target id.UserID, targetIntent *appservice.IntentAPI) {
  2675. if !isSameUser || targetIntent == nil {
  2676. err := portal.tryKickUser(target, kicker)
  2677. if err != nil {
  2678. portal.log.Warnfln("Failed to kick %s from %s: %v", target, portal.MXID, err)
  2679. if targetIntent != nil {
  2680. _, _ = targetIntent.LeaveRoom(portal.MXID)
  2681. }
  2682. }
  2683. } else {
  2684. _, err := targetIntent.LeaveRoom(portal.MXID)
  2685. if err != nil {
  2686. portal.log.Warnfln("Failed to leave portal as %s: %v", target, err)
  2687. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: target})
  2688. }
  2689. }
  2690. portal.CleanupIfEmpty()
  2691. }
  2692. func (portal *Portal) HandleWhatsAppKick(source *User, senderJID types.JID, jids []types.JID) {
  2693. sender := portal.bridge.GetPuppetByJID(senderJID)
  2694. senderIntent := sender.IntentFor(portal)
  2695. for _, jid := range jids {
  2696. if jid.Server != types.DefaultUserServer {
  2697. // TODO handle lids
  2698. continue
  2699. }
  2700. //if source != nil && source.JID.User == jid.User {
  2701. // portal.log.Debugln("Ignoring self-kick by", source.MXID)
  2702. // continue
  2703. //}
  2704. puppet := portal.bridge.GetPuppetByJID(jid)
  2705. portal.removeUser(puppet.JID == sender.JID, senderIntent, puppet.MXID, puppet.DefaultIntent())
  2706. if !portal.IsBroadcastList() {
  2707. user := portal.bridge.GetUserByJID(jid)
  2708. if user != nil {
  2709. var customIntent *appservice.IntentAPI
  2710. if puppet.CustomMXID == user.MXID {
  2711. customIntent = puppet.CustomIntent()
  2712. }
  2713. portal.removeUser(puppet.JID == sender.JID, senderIntent, user.MXID, customIntent)
  2714. }
  2715. }
  2716. }
  2717. }
  2718. func (portal *Portal) HandleWhatsAppInvite(source *User, senderJID *types.JID, jids []types.JID) (evtID id.EventID) {
  2719. intent := portal.MainIntent()
  2720. if senderJID != nil && !senderJID.IsEmpty() {
  2721. sender := portal.bridge.GetPuppetByJID(*senderJID)
  2722. intent = sender.IntentFor(portal)
  2723. }
  2724. for _, jid := range jids {
  2725. if jid.Server != types.DefaultUserServer {
  2726. // TODO handle lids
  2727. continue
  2728. }
  2729. puppet := portal.bridge.GetPuppetByJID(jid)
  2730. puppet.SyncContact(source, true, false, "handling whatsapp invite")
  2731. resp, err := intent.SendStateEvent(portal.MXID, event.StateMember, puppet.MXID.String(), &event.MemberEventContent{
  2732. Membership: event.MembershipInvite,
  2733. Displayname: puppet.Displayname,
  2734. AvatarURL: puppet.AvatarURL.CUString(),
  2735. })
  2736. if err != nil {
  2737. portal.log.Warnfln("Failed to invite %s as %s: %v", puppet.MXID, intent.UserID, err)
  2738. _ = portal.MainIntent().EnsureInvited(portal.MXID, puppet.MXID)
  2739. } else {
  2740. evtID = resp.EventID
  2741. }
  2742. err = puppet.DefaultIntent().EnsureJoined(portal.MXID)
  2743. if err != nil {
  2744. portal.log.Errorfln("Failed to ensure %s is joined: %v", puppet.MXID, err)
  2745. }
  2746. }
  2747. return
  2748. }
  2749. func (portal *Portal) HandleWhatsAppDeleteChat(user *User) {
  2750. if portal.MXID == "" {
  2751. return
  2752. }
  2753. matrixUsers, err := portal.GetMatrixUsers()
  2754. if err != nil {
  2755. portal.log.Errorln("Failed to get Matrix users to see if DeleteChat should be handled:", err)
  2756. return
  2757. }
  2758. if len(matrixUsers) > 1 {
  2759. portal.log.Infoln("Portal contains more than one Matrix user, so deleteChat will not be handled.")
  2760. return
  2761. } else if (len(matrixUsers) == 1 && matrixUsers[0] == user.MXID) || len(matrixUsers) < 1 {
  2762. portal.log.Debugln("User deleted chat and there are no other Matrix users using it, deleting portal...")
  2763. portal.Delete()
  2764. portal.Cleanup(false)
  2765. }
  2766. }
  2767. const failedMediaField = "fi.mau.whatsapp.failed_media"
  2768. type FailedMediaKeys struct {
  2769. Key []byte `json:"key"`
  2770. Length int `json:"length"`
  2771. Type whatsmeow.MediaType `json:"type"`
  2772. SHA256 []byte `json:"sha256"`
  2773. EncSHA256 []byte `json:"enc_sha256"`
  2774. }
  2775. type FailedMediaMeta struct {
  2776. Type event.Type `json:"type"`
  2777. Content *event.MessageEventContent `json:"content"`
  2778. ExtraContent map[string]interface{} `json:"extra_content,omitempty"`
  2779. Media FailedMediaKeys `json:"whatsapp_media"`
  2780. }
  2781. func shallowCopyMap(data map[string]interface{}) map[string]interface{} {
  2782. newMap := make(map[string]interface{}, len(data))
  2783. for key, value := range data {
  2784. newMap[key] = value
  2785. }
  2786. return newMap
  2787. }
  2788. func (portal *Portal) makeMediaBridgeFailureMessage(info *types.MessageInfo, bridgeErr error, converted *ConvertedMessage, keys *FailedMediaKeys, userFriendlyError string) *ConvertedMessage {
  2789. if errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith403) || errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith410) {
  2790. portal.log.Debugfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2791. } else {
  2792. portal.log.Errorfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2793. }
  2794. if keys != nil {
  2795. if portal.bridge.Config.Bridge.CaptionInMessage {
  2796. converted.MergeCaption()
  2797. }
  2798. meta := &FailedMediaMeta{
  2799. Type: converted.Type,
  2800. Content: converted.Content,
  2801. ExtraContent: shallowCopyMap(converted.Extra),
  2802. Media: *keys,
  2803. }
  2804. converted.Extra[failedMediaField] = meta
  2805. portal.mediaErrorCache[info.ID] = meta
  2806. }
  2807. converted.Type = event.EventMessage
  2808. body := userFriendlyError
  2809. if body == "" {
  2810. body = fmt.Sprintf("Failed to bridge media: %v", bridgeErr)
  2811. }
  2812. converted.Content = &event.MessageEventContent{
  2813. MsgType: event.MsgNotice,
  2814. Body: body,
  2815. }
  2816. return converted
  2817. }
  2818. func (portal *Portal) encryptFileInPlace(data []byte, mimeType string) (string, *event.EncryptedFileInfo) {
  2819. if !portal.Encrypted {
  2820. return mimeType, nil
  2821. }
  2822. file := &event.EncryptedFileInfo{
  2823. EncryptedFile: *attachment.NewEncryptedFile(),
  2824. URL: "",
  2825. }
  2826. file.EncryptInPlace(data)
  2827. return "application/octet-stream", file
  2828. }
  2829. type MediaMessage interface {
  2830. whatsmeow.DownloadableMessage
  2831. GetContextInfo() *waProto.ContextInfo
  2832. GetFileLength() uint64
  2833. GetMimetype() string
  2834. }
  2835. type MediaMessageWithThumbnail interface {
  2836. MediaMessage
  2837. GetJpegThumbnail() []byte
  2838. }
  2839. type MediaMessageWithCaption interface {
  2840. MediaMessage
  2841. GetCaption() string
  2842. }
  2843. type MediaMessageWithDimensions interface {
  2844. MediaMessage
  2845. GetHeight() uint32
  2846. GetWidth() uint32
  2847. }
  2848. type MediaMessageWithFileName interface {
  2849. MediaMessage
  2850. GetFileName() string
  2851. }
  2852. type MediaMessageWithDuration interface {
  2853. MediaMessage
  2854. GetSeconds() uint32
  2855. }
  2856. const WhatsAppStickerSize = 190
  2857. func (portal *Portal) convertMediaMessageContent(intent *appservice.IntentAPI, msg MediaMessage) *ConvertedMessage {
  2858. content := &event.MessageEventContent{
  2859. Info: &event.FileInfo{
  2860. MimeType: msg.GetMimetype(),
  2861. Size: int(msg.GetFileLength()),
  2862. },
  2863. }
  2864. extraContent := map[string]interface{}{}
  2865. messageWithDimensions, ok := msg.(MediaMessageWithDimensions)
  2866. if ok {
  2867. content.Info.Width = int(messageWithDimensions.GetWidth())
  2868. content.Info.Height = int(messageWithDimensions.GetHeight())
  2869. }
  2870. msgWithName, ok := msg.(MediaMessageWithFileName)
  2871. if ok && len(msgWithName.GetFileName()) > 0 {
  2872. content.Body = msgWithName.GetFileName()
  2873. } else {
  2874. mimeClass := strings.Split(msg.GetMimetype(), "/")[0]
  2875. switch mimeClass {
  2876. case "application":
  2877. content.Body = "file"
  2878. default:
  2879. content.Body = mimeClass
  2880. }
  2881. content.Body += exmime.ExtensionFromMimetype(msg.GetMimetype())
  2882. }
  2883. msgWithDuration, ok := msg.(MediaMessageWithDuration)
  2884. if ok {
  2885. content.Info.Duration = int(msgWithDuration.GetSeconds()) * 1000
  2886. }
  2887. videoMessage, ok := msg.(*waProto.VideoMessage)
  2888. var isGIF bool
  2889. if ok && videoMessage.GetGifPlayback() {
  2890. isGIF = true
  2891. extraContent["info"] = map[string]interface{}{
  2892. "fi.mau.loop": true,
  2893. "fi.mau.autoplay": true,
  2894. "fi.mau.hide_controls": true,
  2895. "fi.mau.no_audio": true,
  2896. "fi.mau.gif": true,
  2897. }
  2898. }
  2899. messageWithThumbnail, ok := msg.(MediaMessageWithThumbnail)
  2900. if ok && messageWithThumbnail.GetJpegThumbnail() != nil && (portal.bridge.Config.Bridge.WhatsappThumbnail || isGIF) {
  2901. thumbnailData := messageWithThumbnail.GetJpegThumbnail()
  2902. thumbnailMime := http.DetectContentType(thumbnailData)
  2903. thumbnailCfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnailData))
  2904. thumbnailSize := len(thumbnailData)
  2905. thumbnailUploadMime, thumbnailFile := portal.encryptFileInPlace(thumbnailData, thumbnailMime)
  2906. uploadedThumbnail, err := intent.UploadBytes(thumbnailData, thumbnailUploadMime)
  2907. if err != nil {
  2908. portal.log.Warnfln("Failed to upload thumbnail: %v", err)
  2909. } else if uploadedThumbnail != nil {
  2910. if thumbnailFile != nil {
  2911. thumbnailFile.URL = uploadedThumbnail.ContentURI.CUString()
  2912. content.Info.ThumbnailFile = thumbnailFile
  2913. } else {
  2914. content.Info.ThumbnailURL = uploadedThumbnail.ContentURI.CUString()
  2915. }
  2916. content.Info.ThumbnailInfo = &event.FileInfo{
  2917. Size: thumbnailSize,
  2918. Width: thumbnailCfg.Width,
  2919. Height: thumbnailCfg.Height,
  2920. MimeType: thumbnailMime,
  2921. }
  2922. }
  2923. }
  2924. eventType := event.EventMessage
  2925. switch msg.(type) {
  2926. case *waProto.ImageMessage:
  2927. content.MsgType = event.MsgImage
  2928. case *waProto.StickerMessage:
  2929. eventType = event.EventSticker
  2930. if content.Info.Width > content.Info.Height {
  2931. content.Info.Height /= content.Info.Width / WhatsAppStickerSize
  2932. content.Info.Width = WhatsAppStickerSize
  2933. } else if content.Info.Width < content.Info.Height {
  2934. content.Info.Width /= content.Info.Height / WhatsAppStickerSize
  2935. content.Info.Height = WhatsAppStickerSize
  2936. } else {
  2937. content.Info.Width = WhatsAppStickerSize
  2938. content.Info.Height = WhatsAppStickerSize
  2939. }
  2940. case *waProto.VideoMessage:
  2941. content.MsgType = event.MsgVideo
  2942. case *waProto.AudioMessage:
  2943. content.MsgType = event.MsgAudio
  2944. case *waProto.DocumentMessage:
  2945. content.MsgType = event.MsgFile
  2946. default:
  2947. portal.log.Warnfln("Unexpected media type %T in convertMediaMessageContent", msg)
  2948. content.MsgType = event.MsgFile
  2949. }
  2950. audioMessage, ok := msg.(*waProto.AudioMessage)
  2951. if ok {
  2952. var waveform []int
  2953. if audioMessage.Waveform != nil {
  2954. waveform = make([]int, len(audioMessage.Waveform))
  2955. max := 0
  2956. for i, part := range audioMessage.Waveform {
  2957. waveform[i] = int(part)
  2958. if waveform[i] > max {
  2959. max = waveform[i]
  2960. }
  2961. }
  2962. multiplier := 0
  2963. if max > 0 {
  2964. multiplier = 1024 / max
  2965. }
  2966. if multiplier > 32 {
  2967. multiplier = 32
  2968. }
  2969. for i := range waveform {
  2970. waveform[i] *= multiplier
  2971. }
  2972. }
  2973. extraContent["org.matrix.msc1767.audio"] = map[string]interface{}{
  2974. "duration": int(audioMessage.GetSeconds()) * 1000,
  2975. "waveform": waveform,
  2976. }
  2977. if audioMessage.GetPtt() || audioMessage.GetMimetype() == "audio/ogg; codecs/opus" {
  2978. extraContent["org.matrix.msc3245.voice"] = map[string]interface{}{}
  2979. }
  2980. }
  2981. messageWithCaption, ok := msg.(MediaMessageWithCaption)
  2982. var captionContent *event.MessageEventContent
  2983. if ok && len(messageWithCaption.GetCaption()) > 0 {
  2984. captionContent = &event.MessageEventContent{
  2985. Body: messageWithCaption.GetCaption(),
  2986. MsgType: event.MsgNotice,
  2987. }
  2988. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, captionContent, msg.GetContextInfo().GetMentionedJid(), false, false)
  2989. }
  2990. return &ConvertedMessage{
  2991. Intent: intent,
  2992. Type: eventType,
  2993. Content: content,
  2994. Caption: captionContent,
  2995. ReplyTo: GetReply(msg.GetContextInfo()),
  2996. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2997. Extra: extraContent,
  2998. }
  2999. }
  3000. func (portal *Portal) uploadMedia(intent *appservice.IntentAPI, data []byte, content *event.MessageEventContent) error {
  3001. uploadMimeType, file := portal.encryptFileInPlace(data, content.Info.MimeType)
  3002. req := mautrix.ReqUploadMedia{
  3003. ContentBytes: data,
  3004. ContentType: uploadMimeType,
  3005. }
  3006. var mxc id.ContentURI
  3007. if portal.bridge.Config.Homeserver.AsyncMedia {
  3008. uploaded, err := intent.UploadAsync(req)
  3009. if err != nil {
  3010. return err
  3011. }
  3012. mxc = uploaded.ContentURI
  3013. } else {
  3014. uploaded, err := intent.UploadMedia(req)
  3015. if err != nil {
  3016. return err
  3017. }
  3018. mxc = uploaded.ContentURI
  3019. }
  3020. if file != nil {
  3021. file.URL = mxc.CUString()
  3022. content.File = file
  3023. } else {
  3024. content.URL = mxc.CUString()
  3025. }
  3026. content.Info.Size = len(data)
  3027. if content.Info.Width == 0 && content.Info.Height == 0 && strings.HasPrefix(content.Info.MimeType, "image/") {
  3028. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  3029. content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
  3030. }
  3031. // This is a hack for bad clients like Element iOS that require a thumbnail (https://github.com/vector-im/element-ios/issues/4004)
  3032. if strings.HasPrefix(content.Info.MimeType, "image/") && content.Info.ThumbnailInfo == nil {
  3033. infoCopy := *content.Info
  3034. content.Info.ThumbnailInfo = &infoCopy
  3035. if content.File != nil {
  3036. content.Info.ThumbnailFile = file
  3037. } else {
  3038. content.Info.ThumbnailURL = content.URL
  3039. }
  3040. }
  3041. return nil
  3042. }
  3043. func (portal *Portal) convertMediaMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg MediaMessage, typeName string, isBackfill bool) *ConvertedMessage {
  3044. converted := portal.convertMediaMessageContent(intent, msg)
  3045. if msg.GetFileLength() > uint64(portal.bridge.MediaConfig.UploadSize) {
  3046. return portal.makeMediaBridgeFailureMessage(info, errors.New("file is too large"), converted, nil, fmt.Sprintf("Large %s not bridged - please use WhatsApp app to view", typeName))
  3047. }
  3048. data, err := source.Client.Download(msg)
  3049. if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith403) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) {
  3050. converted.Error = database.MsgErrMediaNotFound
  3051. converted.MediaKey = msg.GetMediaKey()
  3052. errorText := fmt.Sprintf("Old %s.", typeName)
  3053. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia && isBackfill {
  3054. errorText += " Media will be automatically requested from your phone later."
  3055. } else {
  3056. errorText += " React with the \u267b (recycle) emoji to request this media from your phone."
  3057. }
  3058. return portal.makeMediaBridgeFailureMessage(info, err, converted, &FailedMediaKeys{
  3059. Key: msg.GetMediaKey(),
  3060. Length: int(msg.GetFileLength()),
  3061. Type: whatsmeow.GetMediaType(msg),
  3062. SHA256: msg.GetFileSha256(),
  3063. EncSHA256: msg.GetFileEncSha256(),
  3064. }, errorText)
  3065. } else if errors.Is(err, whatsmeow.ErrNoURLPresent) {
  3066. portal.log.Debugfln("No URL present error for media message %s, ignoring...", info.ID)
  3067. return nil
  3068. } else if errors.Is(err, whatsmeow.ErrFileLengthMismatch) || errors.Is(err, whatsmeow.ErrInvalidMediaSHA256) {
  3069. portal.log.Warnfln("Mismatching media checksums in %s: %v. Ignoring because WhatsApp seems to ignore them too", info.ID, err)
  3070. } else if err != nil {
  3071. return portal.makeMediaBridgeFailureMessage(info, err, converted, nil, "")
  3072. }
  3073. err = portal.uploadMedia(intent, data, converted.Content)
  3074. if err != nil {
  3075. if errors.Is(err, mautrix.MTooLarge) {
  3076. return portal.makeMediaBridgeFailureMessage(info, errors.New("homeserver rejected too large file"), converted, nil, "")
  3077. } else if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.IsStatus(413) {
  3078. return portal.makeMediaBridgeFailureMessage(info, errors.New("proxy rejected too large file"), converted, nil, "")
  3079. } else {
  3080. return portal.makeMediaBridgeFailureMessage(info, fmt.Errorf("failed to upload media: %w", err), converted, nil, "")
  3081. }
  3082. }
  3083. return converted
  3084. }
  3085. func (portal *Portal) fetchMediaRetryEvent(msg *database.Message) (*FailedMediaMeta, error) {
  3086. errorMeta, ok := portal.mediaErrorCache[msg.JID]
  3087. if ok {
  3088. return errorMeta, nil
  3089. }
  3090. evt, err := portal.MainIntent().GetEvent(portal.MXID, msg.MXID)
  3091. if err != nil {
  3092. return nil, fmt.Errorf("failed to fetch event %s: %w", msg.MXID, err)
  3093. }
  3094. if evt.Type == event.EventEncrypted {
  3095. err = evt.Content.ParseRaw(evt.Type)
  3096. if err != nil {
  3097. return nil, fmt.Errorf("failed to parse encrypted content in %s: %w", msg.MXID, err)
  3098. }
  3099. evt, err = portal.bridge.Crypto.Decrypt(evt)
  3100. if err != nil {
  3101. return nil, fmt.Errorf("failed to decrypt event %s: %w", msg.MXID, err)
  3102. }
  3103. }
  3104. errorMetaResult := gjson.GetBytes(evt.Content.VeryRaw, strings.ReplaceAll(failedMediaField, ".", "\\."))
  3105. if !errorMetaResult.Exists() || !errorMetaResult.IsObject() {
  3106. return nil, fmt.Errorf("didn't find failed media metadata in %s", msg.MXID)
  3107. }
  3108. var errorMetaBytes []byte
  3109. if errorMetaResult.Index > 0 {
  3110. errorMetaBytes = evt.Content.VeryRaw[errorMetaResult.Index : errorMetaResult.Index+len(errorMetaResult.Raw)]
  3111. } else {
  3112. errorMetaBytes = []byte(errorMetaResult.Raw)
  3113. }
  3114. err = json.Unmarshal(errorMetaBytes, &errorMeta)
  3115. if err != nil {
  3116. return nil, fmt.Errorf("failed to unmarshal failed media metadata in %s: %w", msg.MXID, err)
  3117. }
  3118. return errorMeta, nil
  3119. }
  3120. func (portal *Portal) sendMediaRetryFailureEdit(intent *appservice.IntentAPI, msg *database.Message, err error) {
  3121. content := event.MessageEventContent{
  3122. MsgType: event.MsgNotice,
  3123. Body: fmt.Sprintf("Failed to bridge media after re-requesting it from your phone: %v", err),
  3124. }
  3125. contentCopy := content
  3126. content.NewContent = &contentCopy
  3127. content.RelatesTo = &event.RelatesTo{
  3128. EventID: msg.MXID,
  3129. Type: event.RelReplace,
  3130. }
  3131. resp, sendErr := portal.sendMessage(intent, event.EventMessage, &content, nil, time.Now().UnixMilli())
  3132. if sendErr != nil {
  3133. portal.log.Warnfln("Failed to edit %s after retry failure for %s: %v", msg.MXID, msg.JID, sendErr)
  3134. } else {
  3135. portal.log.Debugfln("Successfully edited %s -> %s after retry failure for %s", msg.MXID, resp.EventID, msg.JID)
  3136. }
  3137. }
  3138. func (portal *Portal) handleMediaRetry(retry *events.MediaRetry, source *User) {
  3139. msg := portal.bridge.DB.Message.GetByJID(portal.Key, retry.MessageID)
  3140. if msg == nil {
  3141. portal.log.Warnfln("Dropping media retry notification for unknown message %s", retry.MessageID)
  3142. return
  3143. } else if msg.Error != database.MsgErrMediaNotFound {
  3144. portal.log.Warnfln("Dropping media retry notification for non-errored message %s / %s", retry.MessageID, msg.MXID)
  3145. return
  3146. }
  3147. meta, err := portal.fetchMediaRetryEvent(msg)
  3148. if err != nil {
  3149. portal.log.Warnfln("Can't handle media retry notification for %s: %v", retry.MessageID, err)
  3150. return
  3151. }
  3152. var puppet *Puppet
  3153. if retry.FromMe {
  3154. puppet = portal.bridge.GetPuppetByJID(source.JID)
  3155. } else if retry.ChatID.Server == types.DefaultUserServer {
  3156. puppet = portal.bridge.GetPuppetByJID(retry.ChatID)
  3157. } else {
  3158. puppet = portal.bridge.GetPuppetByJID(retry.SenderID)
  3159. }
  3160. if puppet == nil {
  3161. // TODO handle lids?
  3162. return
  3163. }
  3164. intent := puppet.IntentFor(portal)
  3165. retryData, err := whatsmeow.DecryptMediaRetryNotification(retry, meta.Media.Key)
  3166. if err != nil {
  3167. portal.log.Warnfln("Failed to handle media retry notification for %s: %v", retry.MessageID, err)
  3168. portal.sendMediaRetryFailureEdit(intent, msg, err)
  3169. return
  3170. } else if retryData.GetResult() != waProto.MediaRetryNotification_SUCCESS {
  3171. errorName := waProto.MediaRetryNotification_ResultType_name[int32(retryData.GetResult())]
  3172. if retryData.GetDirectPath() == "" {
  3173. portal.log.Warnfln("Got error response in media retry notification for %s: %s", retry.MessageID, errorName)
  3174. portal.log.Debugfln("Error response contents: %+v", retryData)
  3175. if retryData.GetResult() == waProto.MediaRetryNotification_NOT_FOUND {
  3176. portal.sendMediaRetryFailureEdit(intent, msg, whatsmeow.ErrMediaNotAvailableOnPhone)
  3177. } else {
  3178. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("phone sent error response: %s", errorName))
  3179. }
  3180. return
  3181. } else {
  3182. portal.log.Debugfln("Got error response %s in media retry notification for %s, but response also contains a new download URL - trying to download", retry.MessageID, errorName)
  3183. }
  3184. }
  3185. data, err := source.Client.DownloadMediaWithPath(retryData.GetDirectPath(), meta.Media.EncSHA256, meta.Media.SHA256, meta.Media.Key, meta.Media.Length, meta.Media.Type, "")
  3186. if err != nil {
  3187. portal.log.Warnfln("Failed to download media in %s after retry notification: %v", retry.MessageID, err)
  3188. portal.sendMediaRetryFailureEdit(intent, msg, err)
  3189. return
  3190. }
  3191. err = portal.uploadMedia(intent, data, meta.Content)
  3192. if err != nil {
  3193. portal.log.Warnfln("Failed to re-upload media for %s after retry notification: %v", retry.MessageID, err)
  3194. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("re-uploading media failed: %v", err))
  3195. return
  3196. }
  3197. replaceContent := &event.MessageEventContent{
  3198. MsgType: meta.Content.MsgType,
  3199. Body: "* " + meta.Content.Body,
  3200. NewContent: meta.Content,
  3201. RelatesTo: &event.RelatesTo{
  3202. EventID: msg.MXID,
  3203. Type: event.RelReplace,
  3204. },
  3205. }
  3206. // Move the extra content into m.new_content too
  3207. meta.ExtraContent = map[string]interface{}{
  3208. "m.new_content": shallowCopyMap(meta.ExtraContent),
  3209. }
  3210. resp, err := portal.sendMessage(intent, meta.Type, replaceContent, meta.ExtraContent, time.Now().UnixMilli())
  3211. if err != nil {
  3212. portal.log.Warnfln("Failed to edit %s after retry notification for %s: %v", msg.MXID, retry.MessageID, err)
  3213. return
  3214. }
  3215. portal.log.Debugfln("Successfully edited %s -> %s after retry notification for %s", msg.MXID, resp.EventID, retry.MessageID)
  3216. msg.UpdateMXID(nil, resp.EventID, database.MsgNormal, database.MsgNoError)
  3217. }
  3218. func (portal *Portal) requestMediaRetry(user *User, eventID id.EventID, mediaKey []byte) (bool, error) {
  3219. msg := portal.bridge.DB.Message.GetByMXID(eventID)
  3220. if msg == nil {
  3221. err := errors.New(fmt.Sprintf("%s requested a media retry for unknown event %s", user.MXID, eventID))
  3222. portal.log.Debugfln(err.Error())
  3223. return false, err
  3224. } else if msg.Error != database.MsgErrMediaNotFound {
  3225. err := errors.New(fmt.Sprintf("%s requested a media retry for non-errored event %s", user.MXID, eventID))
  3226. portal.log.Debugfln(err.Error())
  3227. return false, err
  3228. }
  3229. // If the media key is not provided, grab it from the event in Matrix
  3230. if mediaKey == nil {
  3231. evt, err := portal.fetchMediaRetryEvent(msg)
  3232. if err != nil {
  3233. portal.log.Warnfln("Can't send media retry request for %s: %v", msg.JID, err)
  3234. return true, nil
  3235. }
  3236. mediaKey = evt.Media.Key
  3237. }
  3238. err := user.Client.SendMediaRetryReceipt(&types.MessageInfo{
  3239. ID: msg.JID,
  3240. MessageSource: types.MessageSource{
  3241. IsFromMe: msg.Sender.User == user.JID.User,
  3242. IsGroup: !portal.IsPrivateChat(),
  3243. Sender: msg.Sender,
  3244. Chat: portal.Key.JID,
  3245. },
  3246. }, mediaKey)
  3247. if err != nil {
  3248. portal.log.Warnfln("Failed to send media retry request for %s: %v", msg.JID, err)
  3249. } else {
  3250. portal.log.Debugfln("Sent media retry request for %s", msg.JID)
  3251. }
  3252. return true, err
  3253. }
  3254. const thumbnailMaxSize = 72
  3255. const thumbnailMinSize = 24
  3256. func createThumbnailAndGetSize(source []byte, pngThumbnail bool) ([]byte, int, int, error) {
  3257. src, _, err := image.Decode(bytes.NewReader(source))
  3258. if err != nil {
  3259. return nil, 0, 0, fmt.Errorf("failed to decode thumbnail: %w", err)
  3260. }
  3261. imageBounds := src.Bounds()
  3262. width, height := imageBounds.Max.X, imageBounds.Max.Y
  3263. var img image.Image
  3264. if width <= thumbnailMaxSize && height <= thumbnailMaxSize {
  3265. // No need to resize
  3266. img = src
  3267. } else {
  3268. if width == height {
  3269. width = thumbnailMaxSize
  3270. height = thumbnailMaxSize
  3271. } else if width < height {
  3272. width /= height / thumbnailMaxSize
  3273. height = thumbnailMaxSize
  3274. } else {
  3275. height /= width / thumbnailMaxSize
  3276. width = thumbnailMaxSize
  3277. }
  3278. if width < thumbnailMinSize {
  3279. width = thumbnailMinSize
  3280. }
  3281. if height < thumbnailMinSize {
  3282. height = thumbnailMinSize
  3283. }
  3284. dst := image.NewRGBA(image.Rect(0, 0, width, height))
  3285. draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  3286. img = dst
  3287. }
  3288. var buf bytes.Buffer
  3289. if pngThumbnail {
  3290. err = png.Encode(&buf, img)
  3291. } else {
  3292. err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
  3293. }
  3294. if err != nil {
  3295. return nil, width, height, fmt.Errorf("failed to re-encode thumbnail: %w", err)
  3296. }
  3297. return buf.Bytes(), width, height, nil
  3298. }
  3299. func createThumbnail(source []byte, png bool) ([]byte, error) {
  3300. data, _, _, err := createThumbnailAndGetSize(source, png)
  3301. return data, err
  3302. }
  3303. func (portal *Portal) downloadThumbnail(ctx context.Context, original []byte, thumbnailURL id.ContentURIString, eventID id.EventID, png bool) ([]byte, error) {
  3304. if len(thumbnailURL) == 0 {
  3305. // just fall back to making thumbnail of original
  3306. } else if mxc, err := thumbnailURL.Parse(); err != nil {
  3307. portal.log.Warnfln("Malformed thumbnail URL in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3308. } else if thumbnail, err := portal.MainIntent().DownloadBytesContext(ctx, mxc); err != nil {
  3309. portal.log.Warnfln("Failed to download thumbnail in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3310. } else {
  3311. return createThumbnail(thumbnail, png)
  3312. }
  3313. return createThumbnail(original, png)
  3314. }
  3315. func (portal *Portal) convertWebPtoPNG(webpImage []byte) ([]byte, error) {
  3316. webpDecoded, err := webp.Decode(bytes.NewReader(webpImage))
  3317. if err != nil {
  3318. return nil, fmt.Errorf("failed to decode webp image: %w", err)
  3319. }
  3320. var pngBuffer bytes.Buffer
  3321. if err = png.Encode(&pngBuffer, webpDecoded); err != nil {
  3322. return nil, fmt.Errorf("failed to encode png image: %w", err)
  3323. }
  3324. return pngBuffer.Bytes(), nil
  3325. }
  3326. type PaddedImage struct {
  3327. image.Image
  3328. Size int
  3329. OffsetX int
  3330. OffsetY int
  3331. }
  3332. func (img *PaddedImage) Bounds() image.Rectangle {
  3333. return image.Rect(0, 0, img.Size, img.Size)
  3334. }
  3335. func (img *PaddedImage) At(x, y int) color.Color {
  3336. return img.Image.At(x+img.OffsetX, y+img.OffsetY)
  3337. }
  3338. func (portal *Portal) convertToWebP(img []byte) ([]byte, error) {
  3339. decodedImg, _, err := image.Decode(bytes.NewReader(img))
  3340. if err != nil {
  3341. return img, fmt.Errorf("failed to decode image: %w", err)
  3342. }
  3343. bounds := decodedImg.Bounds()
  3344. width, height := bounds.Dx(), bounds.Dy()
  3345. if width != height {
  3346. paddedImg := &PaddedImage{
  3347. Image: decodedImg,
  3348. OffsetX: bounds.Min.Y,
  3349. OffsetY: bounds.Min.X,
  3350. }
  3351. if width > height {
  3352. paddedImg.Size = width
  3353. paddedImg.OffsetY -= (paddedImg.Size - height) / 2
  3354. } else {
  3355. paddedImg.Size = height
  3356. paddedImg.OffsetX -= (paddedImg.Size - width) / 2
  3357. }
  3358. decodedImg = paddedImg
  3359. }
  3360. var webpBuffer bytes.Buffer
  3361. if err = cwebp.Encode(&webpBuffer, decodedImg, nil); err != nil {
  3362. return img, fmt.Errorf("failed to encode webp image: %w", err)
  3363. }
  3364. return webpBuffer.Bytes(), nil
  3365. }
  3366. func (portal *Portal) preprocessMatrixMedia(ctx context.Context, sender *User, relaybotFormatted bool, content *event.MessageEventContent, eventID id.EventID, mediaType whatsmeow.MediaType) (*MediaUpload, error) {
  3367. fileName := content.Body
  3368. var caption string
  3369. var mentionedJIDs []string
  3370. var hasHTMLCaption bool
  3371. isSticker := string(content.MsgType) == event.EventSticker.Type
  3372. if content.FileName != "" && content.Body != content.FileName {
  3373. fileName = content.FileName
  3374. caption = content.Body
  3375. hasHTMLCaption = content.Format == event.FormatHTML
  3376. }
  3377. if relaybotFormatted || hasHTMLCaption {
  3378. caption, mentionedJIDs = portal.bridge.Formatter.ParseMatrix(content.FormattedBody, content.Mentions)
  3379. }
  3380. var file *event.EncryptedFileInfo
  3381. rawMXC := content.URL
  3382. if content.File != nil {
  3383. file = content.File
  3384. rawMXC = file.URL
  3385. }
  3386. mxc, err := rawMXC.Parse()
  3387. if err != nil {
  3388. return nil, err
  3389. }
  3390. data, err := portal.MainIntent().DownloadBytesContext(ctx, mxc)
  3391. if err != nil {
  3392. return nil, exerrors.NewDualError(errMediaDownloadFailed, err)
  3393. }
  3394. if file != nil {
  3395. err = file.DecryptInPlace(data)
  3396. if err != nil {
  3397. return nil, exerrors.NewDualError(errMediaDecryptFailed, err)
  3398. }
  3399. }
  3400. mimeType := content.GetInfo().MimeType
  3401. var convertErr error
  3402. // Allowed mime types from https://developers.facebook.com/docs/whatsapp/on-premises/reference/media
  3403. switch {
  3404. case isSticker:
  3405. if mimeType != "image/webp" || content.Info.Width != content.Info.Height {
  3406. data, convertErr = portal.convertToWebP(data)
  3407. content.Info.MimeType = "image/webp"
  3408. }
  3409. case mediaType == whatsmeow.MediaVideo:
  3410. switch mimeType {
  3411. case "video/mp4", "video/3gpp":
  3412. // Allowed
  3413. case "image/gif":
  3414. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "gif"}, []string{
  3415. "-pix_fmt", "yuv420p", "-c:v", "libx264", "-movflags", "+faststart",
  3416. "-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'",
  3417. }, mimeType)
  3418. content.Info.MimeType = "video/mp4"
  3419. case "video/webm":
  3420. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "webm"}, []string{
  3421. "-pix_fmt", "yuv420p", "-c:v", "libx264",
  3422. }, mimeType)
  3423. content.Info.MimeType = "video/mp4"
  3424. default:
  3425. return nil, fmt.Errorf("%w %q in video message", errMediaUnsupportedType, mimeType)
  3426. }
  3427. case mediaType == whatsmeow.MediaImage:
  3428. switch mimeType {
  3429. case "image/jpeg", "image/png":
  3430. // Allowed
  3431. case "image/webp":
  3432. data, convertErr = portal.convertWebPtoPNG(data)
  3433. content.Info.MimeType = "image/png"
  3434. default:
  3435. return nil, fmt.Errorf("%w %q in image message", errMediaUnsupportedType, mimeType)
  3436. }
  3437. case mediaType == whatsmeow.MediaAudio:
  3438. switch mimeType {
  3439. case "audio/aac", "audio/mp4", "audio/amr", "audio/mpeg", "audio/ogg; codecs=opus":
  3440. // Allowed
  3441. case "audio/ogg":
  3442. // Hopefully it's opus already
  3443. content.Info.MimeType = "audio/ogg; codecs=opus"
  3444. default:
  3445. return nil, fmt.Errorf("%w %q in audio message", errMediaUnsupportedType, mimeType)
  3446. }
  3447. case mediaType == whatsmeow.MediaDocument:
  3448. // Everything is allowed
  3449. }
  3450. if convertErr != nil {
  3451. if content.Info.MimeType != mimeType || data == nil {
  3452. return nil, exerrors.NewDualError(fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, content.Info.MimeType), convertErr)
  3453. } else {
  3454. // If the mime type didn't change and the errored conversion function returned the original data, just log a warning and continue
  3455. portal.log.Warnfln("Failed to re-encode %s media: %v, continuing with original file", mimeType, convertErr)
  3456. }
  3457. }
  3458. uploadResp, err := sender.Client.Upload(ctx, data, mediaType)
  3459. if err != nil {
  3460. return nil, exerrors.NewDualError(errMediaWhatsAppUploadFailed, err)
  3461. }
  3462. // Audio doesn't have thumbnails
  3463. var thumbnail []byte
  3464. if mediaType != whatsmeow.MediaAudio {
  3465. thumbnail, err = portal.downloadThumbnail(ctx, data, content.GetInfo().ThumbnailURL, eventID, isSticker)
  3466. // Ignore format errors for non-image files, we don't care about those thumbnails
  3467. if err != nil && (!errors.Is(err, image.ErrFormat) || mediaType == whatsmeow.MediaImage) {
  3468. portal.log.Warnfln("Failed to generate thumbnail for %s: %v", eventID, err)
  3469. }
  3470. }
  3471. return &MediaUpload{
  3472. UploadResponse: uploadResp,
  3473. FileName: fileName,
  3474. Caption: caption,
  3475. MentionedJIDs: mentionedJIDs,
  3476. Thumbnail: thumbnail,
  3477. FileLength: len(data),
  3478. }, nil
  3479. }
  3480. type MediaUpload struct {
  3481. whatsmeow.UploadResponse
  3482. Caption string
  3483. FileName string
  3484. MentionedJIDs []string
  3485. Thumbnail []byte
  3486. FileLength int
  3487. }
  3488. func (portal *Portal) addRelaybotFormat(userID id.UserID, content *event.MessageEventContent) bool {
  3489. member := portal.MainIntent().Member(portal.MXID, userID)
  3490. if member == nil {
  3491. member = &event.MemberEventContent{}
  3492. }
  3493. content.EnsureHasHTML()
  3494. data, err := portal.bridge.Config.Bridge.Relay.FormatMessage(content, userID, *member)
  3495. if err != nil {
  3496. portal.log.Errorln("Failed to apply relaybot format:", err)
  3497. }
  3498. content.FormattedBody = data
  3499. return true
  3500. }
  3501. func addCodecToMime(mimeType, codec string) string {
  3502. mediaType, params, err := mime.ParseMediaType(mimeType)
  3503. if err != nil {
  3504. return mimeType
  3505. }
  3506. if _, ok := params["codecs"]; !ok {
  3507. params["codecs"] = codec
  3508. }
  3509. return mime.FormatMediaType(mediaType, params)
  3510. }
  3511. func parseGeoURI(uri string) (lat, long float64, err error) {
  3512. if !strings.HasPrefix(uri, "geo:") {
  3513. err = fmt.Errorf("uri doesn't have geo: prefix")
  3514. return
  3515. }
  3516. // Remove geo: prefix and anything after ;
  3517. coordinates := strings.Split(strings.TrimPrefix(uri, "geo:"), ";")[0]
  3518. if splitCoordinates := strings.Split(coordinates, ","); len(splitCoordinates) != 2 {
  3519. err = fmt.Errorf("didn't find exactly two numbers separated by a comma")
  3520. } else if lat, err = strconv.ParseFloat(splitCoordinates[0], 64); err != nil {
  3521. err = fmt.Errorf("latitude is not a number: %w", err)
  3522. } else if long, err = strconv.ParseFloat(splitCoordinates[1], 64); err != nil {
  3523. err = fmt.Errorf("longitude is not a number: %w", err)
  3524. }
  3525. return
  3526. }
  3527. func getUnstableWaveform(content map[string]interface{}) []byte {
  3528. audioInfo, ok := content["org.matrix.msc1767.audio"].(map[string]interface{})
  3529. if !ok {
  3530. return nil
  3531. }
  3532. waveform, ok := audioInfo["waveform"].([]interface{})
  3533. if !ok {
  3534. return nil
  3535. }
  3536. output := make([]byte, len(waveform))
  3537. var val float64
  3538. for i, part := range waveform {
  3539. val, ok = part.(float64)
  3540. if ok {
  3541. output[i] = byte(val / 4)
  3542. }
  3543. }
  3544. return output
  3545. }
  3546. var (
  3547. TypeMSC3381PollStart = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.poll.start"}
  3548. TypeMSC3381PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.poll.response"}
  3549. TypeMSC3381V2PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.v2.poll.response"}
  3550. )
  3551. type PollResponseContent struct {
  3552. RelatesTo event.RelatesTo `json:"m.relates_to"`
  3553. V1Response struct {
  3554. Answers []string `json:"answers"`
  3555. } `json:"org.matrix.msc3381.poll.response"`
  3556. V2Selections []string `json:"org.matrix.msc3381.v2.selections"`
  3557. }
  3558. func (content *PollResponseContent) GetRelatesTo() *event.RelatesTo {
  3559. return &content.RelatesTo
  3560. }
  3561. func (content *PollResponseContent) OptionalGetRelatesTo() *event.RelatesTo {
  3562. if content.RelatesTo.Type == "" {
  3563. return nil
  3564. }
  3565. return &content.RelatesTo
  3566. }
  3567. func (content *PollResponseContent) SetRelatesTo(rel *event.RelatesTo) {
  3568. content.RelatesTo = *rel
  3569. }
  3570. type MSC1767Message struct {
  3571. Text string `json:"org.matrix.msc1767.text,omitempty"`
  3572. HTML string `json:"org.matrix.msc1767.html,omitempty"`
  3573. Message []struct {
  3574. MimeType string `json:"mimetype"`
  3575. Body string `json:"body"`
  3576. } `json:"org.matrix.msc1767.message,omitempty"`
  3577. }
  3578. func (portal *Portal) msc1767ToWhatsApp(msg MSC1767Message, mentions bool) (string, []string) {
  3579. for _, part := range msg.Message {
  3580. if part.MimeType == "text/html" && msg.HTML == "" {
  3581. msg.HTML = part.Body
  3582. } else if part.MimeType == "text/plain" && msg.Text == "" {
  3583. msg.Text = part.Body
  3584. }
  3585. }
  3586. if msg.HTML != "" {
  3587. if mentions {
  3588. return portal.bridge.Formatter.ParseMatrix(msg.HTML, nil)
  3589. } else {
  3590. return portal.bridge.Formatter.ParseMatrixWithoutMentions(msg.HTML), nil
  3591. }
  3592. }
  3593. return msg.Text, nil
  3594. }
  3595. type PollStartContent struct {
  3596. RelatesTo *event.RelatesTo `json:"m.relates_to"`
  3597. PollStart struct {
  3598. Kind string `json:"kind"`
  3599. MaxSelections int `json:"max_selections"`
  3600. Question MSC1767Message `json:"question"`
  3601. Answers []struct {
  3602. ID string `json:"id"`
  3603. MSC1767Message
  3604. } `json:"answers"`
  3605. } `json:"org.matrix.msc3381.poll.start"`
  3606. }
  3607. func (content *PollStartContent) GetRelatesTo() *event.RelatesTo {
  3608. if content.RelatesTo == nil {
  3609. content.RelatesTo = &event.RelatesTo{}
  3610. }
  3611. return content.RelatesTo
  3612. }
  3613. func (content *PollStartContent) OptionalGetRelatesTo() *event.RelatesTo {
  3614. return content.RelatesTo
  3615. }
  3616. func (content *PollStartContent) SetRelatesTo(rel *event.RelatesTo) {
  3617. content.RelatesTo = rel
  3618. }
  3619. func init() {
  3620. event.TypeMap[TypeMSC3381PollResponse] = reflect.TypeOf(PollResponseContent{})
  3621. event.TypeMap[TypeMSC3381V2PollResponse] = reflect.TypeOf(PollResponseContent{})
  3622. event.TypeMap[TypeMSC3381PollStart] = reflect.TypeOf(PollStartContent{})
  3623. }
  3624. func (portal *Portal) convertMatrixPollVote(_ context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3625. content, ok := evt.Content.Parsed.(*PollResponseContent)
  3626. if !ok {
  3627. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3628. }
  3629. var answers []string
  3630. if content.V1Response.Answers != nil {
  3631. answers = content.V1Response.Answers
  3632. } else if content.V2Selections != nil {
  3633. answers = content.V2Selections
  3634. }
  3635. pollMsg := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  3636. if pollMsg == nil {
  3637. return nil, sender, nil, errTargetNotFound
  3638. }
  3639. pollMsgInfo := &types.MessageInfo{
  3640. MessageSource: types.MessageSource{
  3641. Chat: portal.Key.JID,
  3642. Sender: pollMsg.Sender,
  3643. IsFromMe: pollMsg.Sender.User == sender.JID.User,
  3644. IsGroup: portal.IsGroupChat(),
  3645. },
  3646. ID: pollMsg.JID,
  3647. Type: "poll",
  3648. }
  3649. optionHashes := make([][]byte, 0, len(answers))
  3650. if pollMsg.Type == database.MsgMatrixPoll {
  3651. mappedAnswers := pollMsg.GetPollOptionHashes(answers)
  3652. for _, selection := range answers {
  3653. hash, ok := mappedAnswers[selection]
  3654. if ok {
  3655. optionHashes = append(optionHashes, hash[:])
  3656. } else {
  3657. portal.log.Warnfln("Didn't find hash for option %s in %s's vote to %s", selection, evt.Sender, pollMsg.MXID)
  3658. }
  3659. }
  3660. } else {
  3661. for _, selection := range answers {
  3662. hash, _ := hex.DecodeString(selection)
  3663. if hash != nil && len(hash) == 32 {
  3664. optionHashes = append(optionHashes, hash)
  3665. }
  3666. }
  3667. }
  3668. pollUpdate, err := sender.Client.EncryptPollVote(pollMsgInfo, &waProto.PollVoteMessage{
  3669. SelectedOptions: optionHashes,
  3670. })
  3671. return &waProto.Message{PollUpdateMessage: pollUpdate}, sender, nil, err
  3672. }
  3673. func (portal *Portal) convertMatrixPollStart(_ context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3674. content, ok := evt.Content.Parsed.(*PollStartContent)
  3675. if !ok {
  3676. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3677. }
  3678. maxAnswers := content.PollStart.MaxSelections
  3679. if maxAnswers >= len(content.PollStart.Answers) || maxAnswers < 0 {
  3680. maxAnswers = 0
  3681. }
  3682. ctxInfo := portal.generateContextInfo(content.RelatesTo)
  3683. var question string
  3684. question, ctxInfo.MentionedJid = portal.msc1767ToWhatsApp(content.PollStart.Question, true)
  3685. if len(question) == 0 {
  3686. return nil, sender, nil, errPollMissingQuestion
  3687. }
  3688. options := make([]*waProto.PollCreationMessage_Option, len(content.PollStart.Answers))
  3689. optionMap := make(map[[32]byte]string, len(options))
  3690. for i, opt := range content.PollStart.Answers {
  3691. body, _ := portal.msc1767ToWhatsApp(opt.MSC1767Message, false)
  3692. hash := sha256.Sum256([]byte(body))
  3693. if _, alreadyExists := optionMap[hash]; alreadyExists {
  3694. portal.log.Warnfln("Poll %s by %s has option %q more than once, rejecting", evt.ID, evt.Sender, body)
  3695. return nil, sender, nil, errPollDuplicateOption
  3696. }
  3697. optionMap[hash] = opt.ID
  3698. options[i] = &waProto.PollCreationMessage_Option{
  3699. OptionName: proto.String(body),
  3700. }
  3701. }
  3702. secret := make([]byte, 32)
  3703. _, err := rand.Read(secret)
  3704. return &waProto.Message{
  3705. PollCreationMessage: &waProto.PollCreationMessage{
  3706. Name: proto.String(question),
  3707. Options: options,
  3708. SelectableOptionsCount: proto.Uint32(uint32(maxAnswers)),
  3709. ContextInfo: ctxInfo,
  3710. },
  3711. MessageContextInfo: &waProto.MessageContextInfo{
  3712. MessageSecret: secret,
  3713. },
  3714. }, sender, &extraConvertMeta{PollOptions: optionMap}, err
  3715. }
  3716. func (portal *Portal) generateContextInfo(relatesTo *event.RelatesTo) *waProto.ContextInfo {
  3717. var ctxInfo waProto.ContextInfo
  3718. replyToID := relatesTo.GetReplyTo()
  3719. if len(replyToID) > 0 {
  3720. replyToMsg := portal.bridge.DB.Message.GetByMXID(replyToID)
  3721. if replyToMsg != nil && !replyToMsg.IsFakeJID() && (replyToMsg.Type == database.MsgNormal || replyToMsg.Type == database.MsgMatrixPoll || replyToMsg.Type == database.MsgBeeperGallery) {
  3722. ctxInfo.StanzaId = &replyToMsg.JID
  3723. ctxInfo.Participant = proto.String(replyToMsg.Sender.ToNonAD().String())
  3724. // Using blank content here seems to work fine on all official WhatsApp apps.
  3725. //
  3726. // We could probably invent a slightly more accurate version of the quoted message
  3727. // by fetching the Matrix event and converting it to the WhatsApp format, but that's
  3728. // a lot of work and this works fine.
  3729. ctxInfo.QuotedMessage = &waProto.Message{Conversation: proto.String("")}
  3730. }
  3731. }
  3732. if portal.ExpirationTime != 0 {
  3733. ctxInfo.Expiration = proto.Uint32(portal.ExpirationTime)
  3734. }
  3735. return &ctxInfo
  3736. }
  3737. type extraConvertMeta struct {
  3738. PollOptions map[[32]byte]string
  3739. EditRootMsg *database.Message
  3740. }
  3741. func getEditError(rootMsg *database.Message, editer *User) error {
  3742. switch {
  3743. case rootMsg == nil:
  3744. return errEditUnknownTarget
  3745. case rootMsg.Type != database.MsgNormal || rootMsg.IsFakeJID():
  3746. return errEditUnknownTargetType
  3747. case rootMsg.Sender.User != editer.JID.User:
  3748. return errEditDifferentSender
  3749. case time.Since(rootMsg.Timestamp) > whatsmeow.EditWindow:
  3750. return errEditTooOld
  3751. default:
  3752. return nil
  3753. }
  3754. }
  3755. func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3756. if evt.Type == TypeMSC3381PollResponse || evt.Type == TypeMSC3381V2PollResponse {
  3757. return portal.convertMatrixPollVote(ctx, sender, evt)
  3758. } else if evt.Type == TypeMSC3381PollStart {
  3759. return portal.convertMatrixPollStart(ctx, sender, evt)
  3760. }
  3761. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  3762. if !ok {
  3763. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3764. }
  3765. extraMeta := &extraConvertMeta{}
  3766. realSenderMXID := sender.MXID
  3767. isRelay := false
  3768. if !sender.IsLoggedIn() || (portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User) {
  3769. if !portal.HasRelaybot() {
  3770. return nil, sender, extraMeta, errUserNotLoggedIn
  3771. }
  3772. sender = portal.GetRelayUser()
  3773. isRelay = true
  3774. }
  3775. var editRootMsg *database.Message
  3776. if editEventID := content.RelatesTo.GetReplaceID(); editEventID != "" {
  3777. editRootMsg = portal.bridge.DB.Message.GetByMXID(editEventID)
  3778. if editErr := getEditError(editRootMsg, sender); editErr != nil {
  3779. return nil, sender, extraMeta, editErr
  3780. }
  3781. extraMeta.EditRootMsg = editRootMsg
  3782. if content.NewContent != nil {
  3783. content = content.NewContent
  3784. }
  3785. }
  3786. msg := &waProto.Message{}
  3787. ctxInfo := portal.generateContextInfo(content.RelatesTo)
  3788. relaybotFormatted := isRelay && portal.addRelaybotFormat(realSenderMXID, content)
  3789. if evt.Type == event.EventSticker {
  3790. if relaybotFormatted {
  3791. // Stickers can't have captions, so force relaybot stickers to be images
  3792. content.MsgType = event.MsgImage
  3793. } else {
  3794. content.MsgType = event.MessageType(event.EventSticker.Type)
  3795. }
  3796. }
  3797. if content.MsgType == event.MsgImage && content.GetInfo().MimeType == "image/gif" {
  3798. content.MsgType = event.MsgVideo
  3799. }
  3800. if content.MsgType == event.MsgAudio && content.FileName != "" && content.Body != content.FileName {
  3801. // Send audio messages with captions as files since WhatsApp doesn't support captions on audio messages
  3802. content.MsgType = event.MsgFile
  3803. }
  3804. switch content.MsgType {
  3805. case event.MsgText, event.MsgEmote, event.MsgNotice:
  3806. text := content.Body
  3807. if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
  3808. return nil, sender, extraMeta, errMNoticeDisabled
  3809. }
  3810. if content.Format == event.FormatHTML {
  3811. text, ctxInfo.MentionedJid = portal.bridge.Formatter.ParseMatrix(content.FormattedBody, content.Mentions)
  3812. }
  3813. if content.MsgType == event.MsgEmote && !relaybotFormatted {
  3814. text = "/me " + text
  3815. }
  3816. msg.ExtendedTextMessage = &waProto.ExtendedTextMessage{
  3817. Text: &text,
  3818. ContextInfo: ctxInfo,
  3819. }
  3820. hasPreview := portal.convertURLPreviewToWhatsApp(ctx, sender, evt, msg.ExtendedTextMessage)
  3821. if ctx.Err() != nil {
  3822. return nil, sender, extraMeta, ctx.Err()
  3823. }
  3824. if ctxInfo.StanzaId == nil && ctxInfo.MentionedJid == nil && ctxInfo.Expiration == nil && !hasPreview {
  3825. // No need for extended message
  3826. msg.ExtendedTextMessage = nil
  3827. msg.Conversation = &text
  3828. }
  3829. case event.MsgImage:
  3830. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3831. if media == nil {
  3832. return nil, sender, extraMeta, err
  3833. }
  3834. ctxInfo.MentionedJid = media.MentionedJIDs
  3835. msg.ImageMessage = &waProto.ImageMessage{
  3836. ContextInfo: ctxInfo,
  3837. Caption: &media.Caption,
  3838. JpegThumbnail: media.Thumbnail,
  3839. Url: &media.URL,
  3840. DirectPath: &media.DirectPath,
  3841. MediaKey: media.MediaKey,
  3842. Mimetype: &content.GetInfo().MimeType,
  3843. FileEncSha256: media.FileEncSHA256,
  3844. FileSha256: media.FileSHA256,
  3845. FileLength: proto.Uint64(uint64(media.FileLength)),
  3846. }
  3847. case event.MessageType(event.EventSticker.Type):
  3848. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3849. if media == nil {
  3850. return nil, sender, extraMeta, err
  3851. }
  3852. ctxInfo.MentionedJid = media.MentionedJIDs
  3853. msg.StickerMessage = &waProto.StickerMessage{
  3854. ContextInfo: ctxInfo,
  3855. PngThumbnail: media.Thumbnail,
  3856. Url: &media.URL,
  3857. DirectPath: &media.DirectPath,
  3858. MediaKey: media.MediaKey,
  3859. Mimetype: &content.GetInfo().MimeType,
  3860. FileEncSha256: media.FileEncSHA256,
  3861. FileSha256: media.FileSHA256,
  3862. FileLength: proto.Uint64(uint64(media.FileLength)),
  3863. }
  3864. case event.MsgVideo:
  3865. gifPlayback := content.GetInfo().MimeType == "image/gif"
  3866. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaVideo)
  3867. if media == nil {
  3868. return nil, sender, extraMeta, err
  3869. }
  3870. duration := uint32(content.GetInfo().Duration / 1000)
  3871. ctxInfo.MentionedJid = media.MentionedJIDs
  3872. msg.VideoMessage = &waProto.VideoMessage{
  3873. ContextInfo: ctxInfo,
  3874. Caption: &media.Caption,
  3875. JpegThumbnail: media.Thumbnail,
  3876. Url: &media.URL,
  3877. DirectPath: &media.DirectPath,
  3878. MediaKey: media.MediaKey,
  3879. Mimetype: &content.GetInfo().MimeType,
  3880. GifPlayback: &gifPlayback,
  3881. Seconds: &duration,
  3882. FileEncSha256: media.FileEncSHA256,
  3883. FileSha256: media.FileSHA256,
  3884. FileLength: proto.Uint64(uint64(media.FileLength)),
  3885. }
  3886. case event.MsgAudio:
  3887. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaAudio)
  3888. if media == nil {
  3889. return nil, sender, extraMeta, err
  3890. }
  3891. duration := uint32(content.GetInfo().Duration / 1000)
  3892. msg.AudioMessage = &waProto.AudioMessage{
  3893. ContextInfo: ctxInfo,
  3894. Url: &media.URL,
  3895. DirectPath: &media.DirectPath,
  3896. MediaKey: media.MediaKey,
  3897. Mimetype: &content.GetInfo().MimeType,
  3898. Seconds: &duration,
  3899. FileEncSha256: media.FileEncSHA256,
  3900. FileSha256: media.FileSHA256,
  3901. FileLength: proto.Uint64(uint64(media.FileLength)),
  3902. }
  3903. _, isMSC3245Voice := evt.Content.Raw["org.matrix.msc3245.voice"]
  3904. if isMSC3245Voice {
  3905. msg.AudioMessage.Waveform = getUnstableWaveform(evt.Content.Raw)
  3906. msg.AudioMessage.Ptt = proto.Bool(true)
  3907. // hacky hack to add the codecs param that whatsapp seems to require
  3908. msg.AudioMessage.Mimetype = proto.String(addCodecToMime(content.GetInfo().MimeType, "opus"))
  3909. }
  3910. case event.MsgFile:
  3911. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaDocument)
  3912. if media == nil {
  3913. return nil, sender, extraMeta, err
  3914. }
  3915. msg.DocumentMessage = &waProto.DocumentMessage{
  3916. ContextInfo: ctxInfo,
  3917. Caption: &media.Caption,
  3918. JpegThumbnail: media.Thumbnail,
  3919. Url: &media.URL,
  3920. DirectPath: &media.DirectPath,
  3921. Title: &media.FileName,
  3922. FileName: &media.FileName,
  3923. MediaKey: media.MediaKey,
  3924. Mimetype: &content.GetInfo().MimeType,
  3925. FileEncSha256: media.FileEncSHA256,
  3926. FileSha256: media.FileSHA256,
  3927. FileLength: proto.Uint64(uint64(media.FileLength)),
  3928. }
  3929. if media.Caption != "" {
  3930. msg.DocumentWithCaptionMessage = &waProto.FutureProofMessage{
  3931. Message: &waProto.Message{
  3932. DocumentMessage: msg.DocumentMessage,
  3933. },
  3934. }
  3935. msg.DocumentMessage = nil
  3936. }
  3937. case event.MsgLocation:
  3938. lat, long, err := parseGeoURI(content.GeoURI)
  3939. if err != nil {
  3940. return nil, sender, extraMeta, fmt.Errorf("%w: %v", errInvalidGeoURI, err)
  3941. }
  3942. msg.LocationMessage = &waProto.LocationMessage{
  3943. DegreesLatitude: &lat,
  3944. DegreesLongitude: &long,
  3945. Comment: &content.Body,
  3946. ContextInfo: ctxInfo,
  3947. }
  3948. default:
  3949. return nil, sender, extraMeta, fmt.Errorf("%w %q", errUnknownMsgType, content.MsgType)
  3950. }
  3951. if editRootMsg != nil {
  3952. msg = &waProto.Message{
  3953. EditedMessage: &waProto.FutureProofMessage{
  3954. Message: &waProto.Message{
  3955. ProtocolMessage: &waProto.ProtocolMessage{
  3956. Key: &waProto.MessageKey{
  3957. FromMe: proto.Bool(true),
  3958. Id: proto.String(editRootMsg.JID),
  3959. RemoteJid: proto.String(portal.Key.JID.String()),
  3960. },
  3961. Type: waProto.ProtocolMessage_MESSAGE_EDIT.Enum(),
  3962. EditedMessage: msg,
  3963. TimestampMs: proto.Int64(evt.Timestamp),
  3964. },
  3965. },
  3966. },
  3967. }
  3968. }
  3969. return msg, sender, extraMeta, nil
  3970. }
  3971. func (portal *Portal) generateMessageInfo(sender *User) *types.MessageInfo {
  3972. return &types.MessageInfo{
  3973. ID: sender.Client.GenerateMessageID(),
  3974. Timestamp: time.Now(),
  3975. MessageSource: types.MessageSource{
  3976. Sender: sender.JID,
  3977. Chat: portal.Key.JID,
  3978. IsFromMe: true,
  3979. IsGroup: portal.Key.JID.Server == types.GroupServer || portal.Key.JID.Server == types.BroadcastServer,
  3980. },
  3981. }
  3982. }
  3983. func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event, timings messageTimings) {
  3984. start := time.Now()
  3985. ms := metricSender{portal: portal, timings: &timings}
  3986. log := portal.zlog.With().
  3987. Str("event_id", evt.ID.String()).
  3988. Str("action", "handle matrix message").
  3989. Logger()
  3990. allowRelay := evt.Type != TypeMSC3381PollResponse && evt.Type != TypeMSC3381V2PollResponse && evt.Type != TypeMSC3381PollStart
  3991. if err := portal.canBridgeFrom(sender, allowRelay, true); err != nil {
  3992. go ms.sendMessageMetrics(evt, err, "Ignoring", true)
  3993. return
  3994. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  3995. go ms.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", true)
  3996. return
  3997. }
  3998. messageAge := timings.totalReceive
  3999. origEvtID := evt.ID
  4000. var dbMsg *database.Message
  4001. if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
  4002. origEvtID = retryMeta.OriginalEventID
  4003. dbMsg = portal.bridge.DB.Message.GetByMXID(origEvtID)
  4004. if dbMsg != nil && dbMsg.Sent {
  4005. portal.log.Debugfln("Ignoring retry request %s (#%d, age: %s) for %s/%s from %s as message was already sent", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
  4006. go ms.sendMessageMetrics(evt, nil, "", true)
  4007. return
  4008. } else if dbMsg != nil {
  4009. portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s/%s from %s", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
  4010. } else {
  4011. portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s from %s (original message not known)", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, evt.Sender)
  4012. }
  4013. } else {
  4014. portal.log.Debugfln("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
  4015. }
  4016. errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
  4017. deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
  4018. isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
  4019. if isScheduled {
  4020. portal.log.Debugfln("%s is a scheduled message, extending handling timeouts", evt.ID)
  4021. errorAfter *= 10
  4022. deadline *= 10
  4023. }
  4024. if errorAfter > 0 {
  4025. remainingTime := errorAfter - messageAge
  4026. if remainingTime < 0 {
  4027. go ms.sendMessageMetrics(evt, errTimeoutBeforeHandling, "Timeout handling", true)
  4028. return
  4029. } else if remainingTime < 1*time.Second {
  4030. portal.log.Warnfln("Message %s was delayed before reaching the bridge, only have %s (of %s timeout) until delay warning", evt.ID, remainingTime, errorAfter)
  4031. }
  4032. go func() {
  4033. time.Sleep(remainingTime)
  4034. ms.sendMessageMetrics(evt, errMessageTakingLong, "Timeout handling", false)
  4035. }()
  4036. }
  4037. ctx := context.Background()
  4038. if deadline > 0 {
  4039. var cancel context.CancelFunc
  4040. ctx, cancel = context.WithTimeout(ctx, deadline)
  4041. defer cancel()
  4042. }
  4043. ctx = log.WithContext(ctx)
  4044. timings.preproc = time.Since(start)
  4045. start = time.Now()
  4046. msg, sender, extraMeta, err := portal.convertMatrixMessage(ctx, sender, evt)
  4047. timings.convert = time.Since(start)
  4048. if msg == nil {
  4049. go ms.sendMessageMetrics(evt, err, "Error converting", true)
  4050. return
  4051. }
  4052. dbMsgType := database.MsgNormal
  4053. if msg.PollCreationMessage != nil || msg.PollCreationMessageV2 != nil || msg.PollCreationMessageV3 != nil {
  4054. dbMsgType = database.MsgMatrixPoll
  4055. } else if msg.EditedMessage == nil {
  4056. portal.MarkDisappearing(nil, origEvtID, time.Duration(portal.ExpirationTime)*time.Second, time.Now())
  4057. } else {
  4058. dbMsgType = database.MsgEdit
  4059. }
  4060. info := portal.generateMessageInfo(sender)
  4061. if dbMsg == nil {
  4062. dbMsg = portal.markHandled(nil, nil, info, evt.ID, evt.Sender, false, true, dbMsgType, 0, database.MsgNoError)
  4063. } else {
  4064. info.ID = dbMsg.JID
  4065. }
  4066. if dbMsgType == database.MsgMatrixPoll && extraMeta != nil && extraMeta.PollOptions != nil {
  4067. dbMsg.PutPollOptions(extraMeta.PollOptions)
  4068. }
  4069. portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info.ID)
  4070. start = time.Now()
  4071. resp, err := sender.Client.SendMessage(ctx, portal.Key.JID, msg, whatsmeow.SendRequestExtra{ID: info.ID})
  4072. timings.totalSend = time.Since(start)
  4073. timings.whatsmeow = resp.DebugTimings
  4074. go ms.sendMessageMetrics(evt, err, "Error sending", true)
  4075. if err == nil {
  4076. dbMsg.MarkSent(resp.Timestamp)
  4077. }
  4078. }
  4079. func (portal *Portal) HandleMatrixReaction(sender *User, evt *event.Event) {
  4080. if err := portal.canBridgeFrom(sender, false, true); err != nil {
  4081. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  4082. return
  4083. } else if portal.Key.JID.Server == types.BroadcastServer {
  4084. // TODO implement this, probably by only sending the reaction to the sender of the status message?
  4085. // (whatsapp hasn't published the feature yet)
  4086. go portal.sendMessageMetrics(evt, errBroadcastReactionNotSupported, "Ignoring", nil)
  4087. return
  4088. }
  4089. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  4090. if ok && strings.Contains(content.RelatesTo.Key, "retry") || strings.HasPrefix(content.RelatesTo.Key, "\u267b") { // ♻️
  4091. if retryRequested, _ := portal.requestMediaRetry(sender, content.RelatesTo.EventID, nil); retryRequested {
  4092. _, _ = portal.MainIntent().RedactEvent(portal.MXID, evt.ID, mautrix.ReqRedact{
  4093. Reason: "requested media from phone",
  4094. })
  4095. // Errored media, don't try to send as reaction
  4096. return
  4097. }
  4098. }
  4099. portal.log.Debugfln("Received reaction event %s from %s", evt.ID, evt.Sender)
  4100. err := portal.handleMatrixReaction(sender, evt)
  4101. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  4102. }
  4103. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) error {
  4104. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  4105. if !ok {
  4106. return fmt.Errorf("unexpected parsed content type %T", evt.Content.Parsed)
  4107. }
  4108. target := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  4109. if target == nil || target.Type == database.MsgReaction {
  4110. return fmt.Errorf("unknown target event %s", content.RelatesTo.EventID)
  4111. }
  4112. info := portal.generateMessageInfo(sender)
  4113. dbMsg := portal.markHandled(nil, nil, info, evt.ID, evt.Sender, false, true, database.MsgReaction, 0, database.MsgNoError)
  4114. portal.upsertReaction(nil, nil, target.JID, sender.JID, evt.ID, info.ID)
  4115. portal.log.Debugln("Sending reaction", evt.ID, "to WhatsApp", info.ID)
  4116. resp, err := portal.sendReactionToWhatsApp(sender, info.ID, target, content.RelatesTo.Key, evt.Timestamp)
  4117. if err == nil {
  4118. dbMsg.MarkSent(resp.Timestamp)
  4119. }
  4120. return err
  4121. }
  4122. func (portal *Portal) sendReactionToWhatsApp(sender *User, id types.MessageID, target *database.Message, key string, timestamp int64) (whatsmeow.SendResponse, error) {
  4123. var messageKeyParticipant *string
  4124. if !portal.IsPrivateChat() {
  4125. messageKeyParticipant = proto.String(target.Sender.ToNonAD().String())
  4126. }
  4127. key = variationselector.Remove(key)
  4128. return sender.Client.SendMessage(context.TODO(), portal.Key.JID, &waProto.Message{
  4129. ReactionMessage: &waProto.ReactionMessage{
  4130. Key: &waProto.MessageKey{
  4131. RemoteJid: proto.String(portal.Key.JID.String()),
  4132. FromMe: proto.Bool(target.Sender.User == sender.JID.User),
  4133. Id: proto.String(target.JID),
  4134. Participant: messageKeyParticipant,
  4135. },
  4136. Text: proto.String(key),
  4137. SenderTimestampMs: proto.Int64(timestamp),
  4138. },
  4139. }, whatsmeow.SendRequestExtra{ID: id})
  4140. }
  4141. func (portal *Portal) upsertReaction(txn dbutil.Transaction, intent *appservice.IntentAPI, targetJID types.MessageID, senderJID types.JID, mxid id.EventID, jid types.MessageID) {
  4142. dbReaction := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, senderJID)
  4143. if dbReaction == nil {
  4144. dbReaction = portal.bridge.DB.Reaction.New()
  4145. dbReaction.Chat = portal.Key
  4146. dbReaction.TargetJID = targetJID
  4147. dbReaction.Sender = senderJID
  4148. } else if intent != nil {
  4149. portal.log.Debugfln("Redacting old Matrix reaction %s after new one (%s) was sent", dbReaction.MXID, mxid)
  4150. var err error
  4151. if intent != nil {
  4152. _, err = intent.RedactEvent(portal.MXID, dbReaction.MXID)
  4153. }
  4154. if intent == nil || errors.Is(err, mautrix.MForbidden) {
  4155. _, err = portal.MainIntent().RedactEvent(portal.MXID, dbReaction.MXID)
  4156. }
  4157. if err != nil {
  4158. portal.log.Warnfln("Failed to remove old reaction %s: %v", dbReaction.MXID, err)
  4159. }
  4160. }
  4161. dbReaction.MXID = mxid
  4162. dbReaction.JID = jid
  4163. dbReaction.Upsert(txn)
  4164. }
  4165. func (portal *Portal) HandleMatrixRedaction(sender *User, evt *event.Event) {
  4166. if err := portal.canBridgeFrom(sender, true, true); err != nil {
  4167. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  4168. return
  4169. }
  4170. portal.log.Debugfln("Received redaction %s from %s", evt.ID, evt.Sender)
  4171. senderLogIdentifier := sender.MXID
  4172. if !sender.HasSession() {
  4173. sender = portal.GetRelayUser()
  4174. senderLogIdentifier += " (through relaybot)"
  4175. }
  4176. msg := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
  4177. if msg == nil {
  4178. go portal.sendMessageMetrics(evt, errTargetNotFound, "Ignoring", nil)
  4179. } else if msg.IsFakeJID() {
  4180. go portal.sendMessageMetrics(evt, errTargetIsFake, "Ignoring", nil)
  4181. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  4182. go portal.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", nil)
  4183. } else if msg.Type == database.MsgReaction {
  4184. if msg.Sender.User != sender.JID.User {
  4185. go portal.sendMessageMetrics(evt, errReactionSentBySomeoneElse, "Ignoring", nil)
  4186. } else if reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts); reaction == nil {
  4187. go portal.sendMessageMetrics(evt, errReactionDatabaseNotFound, "Ignoring", nil)
  4188. } else if reactionTarget := reaction.GetTarget(); reactionTarget == nil {
  4189. go portal.sendMessageMetrics(evt, errReactionTargetNotFound, "Ignoring", nil)
  4190. } else {
  4191. portal.log.Debugfln("Sending redaction reaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  4192. _, err := portal.sendReactionToWhatsApp(sender, "", reactionTarget, "", evt.Timestamp)
  4193. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  4194. }
  4195. } else {
  4196. key := &waProto.MessageKey{
  4197. FromMe: proto.Bool(true),
  4198. Id: proto.String(msg.JID),
  4199. RemoteJid: proto.String(portal.Key.JID.String()),
  4200. }
  4201. if msg.Sender.User != sender.JID.User {
  4202. if portal.IsPrivateChat() {
  4203. go portal.sendMessageMetrics(evt, errDMSentByOtherUser, "Ignoring", nil)
  4204. return
  4205. }
  4206. key.FromMe = proto.Bool(false)
  4207. key.Participant = proto.String(msg.Sender.ToNonAD().String())
  4208. }
  4209. portal.log.Debugfln("Sending redaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  4210. _, err := sender.Client.SendMessage(context.TODO(), portal.Key.JID, &waProto.Message{
  4211. ProtocolMessage: &waProto.ProtocolMessage{
  4212. Type: waProto.ProtocolMessage_REVOKE.Enum(),
  4213. Key: key,
  4214. },
  4215. })
  4216. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  4217. }
  4218. }
  4219. func (portal *Portal) HandleMatrixReadReceipt(sender bridge.User, eventID id.EventID, receipt event.ReadReceipt) {
  4220. portal.handleMatrixReadReceipt(sender.(*User), eventID, receipt.Timestamp, true)
  4221. }
  4222. func (portal *Portal) handleMatrixReadReceipt(sender *User, eventID id.EventID, receiptTimestamp time.Time, isExplicit bool) {
  4223. if !sender.IsLoggedIn() {
  4224. if isExplicit {
  4225. portal.log.Debugfln("Ignoring read receipt by %s/%s: user is not connected to WhatsApp", sender.MXID, sender.JID)
  4226. }
  4227. return
  4228. }
  4229. maxTimestamp := receiptTimestamp
  4230. // Implicit read receipts don't have an event ID that's already bridged
  4231. if isExplicit {
  4232. if message := portal.bridge.DB.Message.GetByMXID(eventID); message != nil {
  4233. maxTimestamp = message.Timestamp
  4234. }
  4235. }
  4236. prevTimestamp := sender.GetLastReadTS(portal.Key)
  4237. lastReadIsZero := false
  4238. if prevTimestamp.IsZero() {
  4239. prevTimestamp = maxTimestamp.Add(-2 * time.Second)
  4240. lastReadIsZero = true
  4241. }
  4242. messages := portal.bridge.DB.Message.GetMessagesBetween(portal.Key, prevTimestamp, maxTimestamp)
  4243. if len(messages) > 0 {
  4244. sender.SetLastReadTS(portal.Key, messages[len(messages)-1].Timestamp)
  4245. }
  4246. groupedMessages := make(map[types.JID][]types.MessageID)
  4247. for _, msg := range messages {
  4248. var key types.JID
  4249. if msg.IsFakeJID() || msg.Sender.User == sender.JID.User {
  4250. // Don't send read receipts for own messages or fake messages
  4251. continue
  4252. } else if !portal.IsPrivateChat() {
  4253. key = msg.Sender
  4254. } else if !msg.BroadcastListJID.IsEmpty() {
  4255. key = msg.BroadcastListJID
  4256. } // else: blank key (participant field isn't needed in direct chat read receipts)
  4257. groupedMessages[key] = append(groupedMessages[key], msg.JID)
  4258. }
  4259. // For explicit read receipts, log even if there are no targets. For implicit ones only log when there are targets
  4260. if len(groupedMessages) > 0 || isExplicit {
  4261. portal.log.Debugfln("Sending read receipts by %s (last read: %d, was zero: %t, explicit: %t): %v",
  4262. sender.JID, prevTimestamp.Unix(), lastReadIsZero, isExplicit, groupedMessages)
  4263. }
  4264. for messageSender, ids := range groupedMessages {
  4265. chatJID := portal.Key.JID
  4266. if messageSender.Server == types.BroadcastServer {
  4267. chatJID = messageSender
  4268. messageSender = portal.Key.JID
  4269. }
  4270. err := sender.Client.MarkRead(ids, receiptTimestamp, chatJID, messageSender)
  4271. if err != nil {
  4272. portal.log.Warnfln("Failed to mark %v as read by %s: %v", ids, sender.JID, err)
  4273. }
  4274. }
  4275. }
  4276. func typingDiff(prev, new []id.UserID) (started, stopped []id.UserID) {
  4277. OuterNew:
  4278. for _, userID := range new {
  4279. for _, previousUserID := range prev {
  4280. if userID == previousUserID {
  4281. continue OuterNew
  4282. }
  4283. }
  4284. started = append(started, userID)
  4285. }
  4286. OuterPrev:
  4287. for _, userID := range prev {
  4288. for _, previousUserID := range new {
  4289. if userID == previousUserID {
  4290. continue OuterPrev
  4291. }
  4292. }
  4293. stopped = append(stopped, userID)
  4294. }
  4295. return
  4296. }
  4297. func (portal *Portal) setTyping(userIDs []id.UserID, state types.ChatPresence) {
  4298. for _, userID := range userIDs {
  4299. user := portal.bridge.GetUserByMXIDIfExists(userID)
  4300. if user == nil || !user.IsLoggedIn() {
  4301. continue
  4302. }
  4303. portal.log.Debugfln("Bridging typing change from %s to chat presence %s", state, user.MXID)
  4304. err := user.Client.SendChatPresence(portal.Key.JID, state, types.ChatPresenceMediaText)
  4305. if err != nil {
  4306. portal.log.Warnln("Error sending chat presence:", err)
  4307. }
  4308. if portal.bridge.Config.Bridge.SendPresenceOnTyping {
  4309. err = user.Client.SendPresence(types.PresenceAvailable)
  4310. if err != nil {
  4311. user.log.Warnln("Failed to set presence:", err)
  4312. }
  4313. }
  4314. }
  4315. }
  4316. func (portal *Portal) HandleMatrixTyping(newTyping []id.UserID) {
  4317. portal.currentlyTypingLock.Lock()
  4318. defer portal.currentlyTypingLock.Unlock()
  4319. startedTyping, stoppedTyping := typingDiff(portal.currentlyTyping, newTyping)
  4320. portal.currentlyTyping = newTyping
  4321. portal.setTyping(startedTyping, types.ChatPresenceComposing)
  4322. portal.setTyping(stoppedTyping, types.ChatPresencePaused)
  4323. }
  4324. func (portal *Portal) canBridgeFrom(sender *User, allowRelay, reconnectWait bool) error {
  4325. if !sender.IsLoggedIn() {
  4326. if allowRelay && portal.HasRelaybot() {
  4327. return nil
  4328. } else if sender.Session != nil {
  4329. return errUserNotConnected
  4330. } else if reconnectWait {
  4331. // If a message was received exactly during a disconnection, wait a second for the socket to reconnect
  4332. time.Sleep(1 * time.Second)
  4333. return portal.canBridgeFrom(sender, allowRelay, false)
  4334. } else {
  4335. return errUserNotLoggedIn
  4336. }
  4337. } else if portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User && (!allowRelay || !portal.HasRelaybot()) {
  4338. return errDifferentUser
  4339. }
  4340. return nil
  4341. }
  4342. func (portal *Portal) resetChildSpaceStatus() {
  4343. for _, childPortal := range portal.bridge.portalsByJID {
  4344. if childPortal.ParentGroup == portal.Key.JID {
  4345. if portal.MXID != "" && childPortal.InSpace {
  4346. go childPortal.removeSpaceParentEvent(portal.MXID)
  4347. }
  4348. childPortal.InSpace = false
  4349. if childPortal.parentPortal == portal {
  4350. childPortal.parentPortal = nil
  4351. }
  4352. }
  4353. }
  4354. }
  4355. func (portal *Portal) Delete() {
  4356. portal.Portal.Delete()
  4357. portal.bridge.portalsLock.Lock()
  4358. delete(portal.bridge.portalsByJID, portal.Key)
  4359. if len(portal.MXID) > 0 {
  4360. delete(portal.bridge.portalsByMXID, portal.MXID)
  4361. }
  4362. portal.resetChildSpaceStatus()
  4363. portal.bridge.portalsLock.Unlock()
  4364. }
  4365. func (portal *Portal) GetMatrixUsers() ([]id.UserID, error) {
  4366. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  4367. if err != nil {
  4368. return nil, fmt.Errorf("failed to get member list: %w", err)
  4369. }
  4370. var users []id.UserID
  4371. for userID := range members.Joined {
  4372. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  4373. if !isPuppet && userID != portal.bridge.Bot.UserID {
  4374. users = append(users, userID)
  4375. }
  4376. }
  4377. return users, nil
  4378. }
  4379. func (portal *Portal) CleanupIfEmpty() {
  4380. users, err := portal.GetMatrixUsers()
  4381. if err != nil {
  4382. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  4383. return
  4384. }
  4385. if len(users) == 0 {
  4386. portal.log.Infoln("Room seems to be empty, cleaning up...")
  4387. portal.Delete()
  4388. portal.Cleanup(false)
  4389. }
  4390. }
  4391. func (portal *Portal) Cleanup(puppetsOnly bool) {
  4392. if len(portal.MXID) == 0 {
  4393. return
  4394. }
  4395. intent := portal.MainIntent()
  4396. if portal.bridge.SpecVersions.Supports(mautrix.BeeperFeatureRoomYeeting) {
  4397. err := intent.BeeperDeleteRoom(portal.MXID)
  4398. if err == nil || errors.Is(err, mautrix.MNotFound) {
  4399. return
  4400. }
  4401. portal.log.Warnfln("Failed to delete %s using hungryserv yeet endpoint, falling back to normal behavior: %v", portal.MXID, err)
  4402. }
  4403. members, err := intent.JoinedMembers(portal.MXID)
  4404. if err != nil {
  4405. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  4406. return
  4407. }
  4408. for member := range members.Joined {
  4409. if member == intent.UserID {
  4410. continue
  4411. }
  4412. puppet := portal.bridge.GetPuppetByMXID(member)
  4413. if puppet != nil {
  4414. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  4415. if err != nil {
  4416. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  4417. }
  4418. } else if !puppetsOnly {
  4419. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  4420. if err != nil {
  4421. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  4422. }
  4423. }
  4424. }
  4425. _, err = intent.LeaveRoom(portal.MXID)
  4426. if err != nil {
  4427. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  4428. }
  4429. }
  4430. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  4431. sender := brSender.(*User)
  4432. if portal.IsPrivateChat() {
  4433. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  4434. portal.Delete()
  4435. portal.Cleanup(false)
  4436. return
  4437. } else if portal.bridge.Config.Bridge.BridgeMatrixLeave {
  4438. err := sender.Client.LeaveGroup(portal.Key.JID)
  4439. if err != nil {
  4440. portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err)
  4441. return
  4442. }
  4443. //portal.log.Infoln("Leave response:", <-resp)
  4444. }
  4445. portal.CleanupIfEmpty()
  4446. }
  4447. func (portal *Portal) HandleMatrixKick(brSender bridge.User, brTarget bridge.Ghost) {
  4448. sender := brSender.(*User)
  4449. target := brTarget.(*Puppet)
  4450. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  4451. target.JID: whatsmeow.ParticipantChangeRemove,
  4452. })
  4453. if err != nil {
  4454. portal.log.Errorfln("Failed to kick %s from group as %s: %v", target.JID, sender.MXID, err)
  4455. return
  4456. }
  4457. //portal.log.Infoln("Kick %s response: %s", puppet.JID, <-resp)
  4458. }
  4459. func (portal *Portal) HandleMatrixInvite(brSender bridge.User, brTarget bridge.Ghost) {
  4460. sender := brSender.(*User)
  4461. target := brTarget.(*Puppet)
  4462. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  4463. target.JID: whatsmeow.ParticipantChangeAdd,
  4464. })
  4465. if err != nil {
  4466. portal.log.Errorfln("Failed to add %s to group as %s: %v", target.JID, sender.MXID, err)
  4467. return
  4468. }
  4469. //portal.log.Infofln("Add %s response: %s", puppet.JID, <-resp)
  4470. }
  4471. func (portal *Portal) HandleMatrixMeta(brSender bridge.User, evt *event.Event) {
  4472. sender := brSender.(*User)
  4473. if !sender.Whitelisted || !sender.IsLoggedIn() {
  4474. return
  4475. }
  4476. switch content := evt.Content.Parsed.(type) {
  4477. case *event.RoomNameEventContent:
  4478. if content.Name == portal.Name {
  4479. return
  4480. }
  4481. portal.Name = content.Name
  4482. err := sender.Client.SetGroupName(portal.Key.JID, content.Name)
  4483. if err != nil {
  4484. portal.log.Errorln("Failed to update group name:", err)
  4485. }
  4486. case *event.TopicEventContent:
  4487. if content.Topic == portal.Topic {
  4488. return
  4489. }
  4490. portal.Topic = content.Topic
  4491. err := sender.Client.SetGroupTopic(portal.Key.JID, "", "", content.Topic)
  4492. if err != nil {
  4493. portal.log.Errorln("Failed to update group description:", err)
  4494. }
  4495. case *event.RoomAvatarEventContent:
  4496. portal.avatarLock.Lock()
  4497. defer portal.avatarLock.Unlock()
  4498. if content.URL == portal.AvatarURL || (content.URL.IsEmpty() && portal.Avatar == "remove") {
  4499. return
  4500. }
  4501. var data []byte
  4502. var err error
  4503. if !content.URL.IsEmpty() {
  4504. data, err = portal.MainIntent().DownloadBytes(content.URL)
  4505. if err != nil {
  4506. portal.log.Errorfln("Failed to download updated avatar %s: %v", content.URL, err)
  4507. return
  4508. }
  4509. portal.log.Debugfln("%s set the group avatar to %s", sender.MXID, content.URL)
  4510. } else {
  4511. portal.log.Debugfln("%s removed the group avatar", sender.MXID)
  4512. }
  4513. newID, err := sender.Client.SetGroupPhoto(portal.Key.JID, data)
  4514. if err != nil {
  4515. portal.log.Errorfln("Failed to update group avatar: %v", err)
  4516. return
  4517. }
  4518. portal.log.Debugfln("Successfully updated group avatar to %s", newID)
  4519. portal.Avatar = newID
  4520. portal.AvatarURL = content.URL
  4521. portal.UpdateBridgeInfo()
  4522. portal.Update(nil)
  4523. }
  4524. }