portal.go 158 KB

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