portal.go 160 KB

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