portal.go 147 KB

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