portal.go 154 KB

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