portal.go 165 KB

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