portal.go 160 KB

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