portal.go 152 KB

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