portal.go 161 KB

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