portal.go 146 KB

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