portal.go 158 KB

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