portal.go 156 KB

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