portal.go 122 KB

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