portal.go 161 KB

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