portal.go 162 KB

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