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