portal.go 155 KB

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