portal.go 153 KB

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