portal.go 161 KB

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