portal.go 154 KB

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