portal.go 157 KB

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