portal.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "encoding/gob"
  20. "encoding/hex"
  21. "fmt"
  22. "html"
  23. "image"
  24. "image/gif"
  25. "image/jpeg"
  26. "image/png"
  27. "math"
  28. "math/rand"
  29. "mime"
  30. "net/http"
  31. "reflect"
  32. "strings"
  33. "sync"
  34. "time"
  35. "github.com/pkg/errors"
  36. log "maunium.net/go/maulogger/v2"
  37. "maunium.net/go/mautrix/crypto/attachment"
  38. "github.com/Rhymen/go-whatsapp"
  39. waProto "github.com/Rhymen/go-whatsapp/binary/proto"
  40. "maunium.net/go/mautrix"
  41. "maunium.net/go/mautrix/appservice"
  42. "maunium.net/go/mautrix/event"
  43. "maunium.net/go/mautrix/format"
  44. "maunium.net/go/mautrix/id"
  45. "maunium.net/go/mautrix/pushrules"
  46. "maunium.net/go/mautrix-whatsapp/database"
  47. "maunium.net/go/mautrix-whatsapp/types"
  48. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  49. )
  50. func (bridge *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  51. bridge.portalsLock.Lock()
  52. defer bridge.portalsLock.Unlock()
  53. portal, ok := bridge.portalsByMXID[mxid]
  54. if !ok {
  55. return bridge.loadDBPortal(bridge.DB.Portal.GetByMXID(mxid), nil)
  56. }
  57. return portal
  58. }
  59. func (bridge *Bridge) GetPortalByJID(key database.PortalKey) *Portal {
  60. bridge.portalsLock.Lock()
  61. defer bridge.portalsLock.Unlock()
  62. portal, ok := bridge.portalsByJID[key]
  63. if !ok {
  64. return bridge.loadDBPortal(bridge.DB.Portal.GetByJID(key), &key)
  65. }
  66. return portal
  67. }
  68. func (bridge *Bridge) GetAllPortals() []*Portal {
  69. return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAll())
  70. }
  71. func (bridge *Bridge) GetAllPortalsByJID(jid types.WhatsAppID) []*Portal {
  72. return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAllByJID(jid))
  73. }
  74. func (bridge *Bridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  75. bridge.portalsLock.Lock()
  76. defer bridge.portalsLock.Unlock()
  77. output := make([]*Portal, len(dbPortals))
  78. for index, dbPortal := range dbPortals {
  79. if dbPortal == nil {
  80. continue
  81. }
  82. portal, ok := bridge.portalsByJID[dbPortal.Key]
  83. if !ok {
  84. portal = bridge.loadDBPortal(dbPortal, nil)
  85. }
  86. output[index] = portal
  87. }
  88. return output
  89. }
  90. func (bridge *Bridge) loadDBPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
  91. if dbPortal == nil {
  92. if key == nil {
  93. return nil
  94. }
  95. dbPortal = bridge.DB.Portal.New()
  96. dbPortal.Key = *key
  97. dbPortal.Insert()
  98. }
  99. portal := bridge.NewPortal(dbPortal)
  100. bridge.portalsByJID[portal.Key] = portal
  101. if len(portal.MXID) > 0 {
  102. bridge.portalsByMXID[portal.MXID] = portal
  103. }
  104. return portal
  105. }
  106. func (portal *Portal) GetUsers() []*User {
  107. return nil
  108. }
  109. func (bridge *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
  110. portal := &Portal{
  111. Portal: dbPortal,
  112. bridge: bridge,
  113. log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
  114. recentlyHandled: [recentlyHandledLength]types.WhatsAppMessageID{},
  115. messages: make(chan PortalMessage, 128),
  116. }
  117. go portal.handleMessageLoop()
  118. return portal
  119. }
  120. const recentlyHandledLength = 100
  121. type PortalMessage struct {
  122. chat string
  123. source *User
  124. data interface{}
  125. timestamp uint64
  126. }
  127. type Portal struct {
  128. *database.Portal
  129. bridge *Bridge
  130. log log.Logger
  131. roomCreateLock sync.Mutex
  132. recentlyHandled [recentlyHandledLength]types.WhatsAppMessageID
  133. recentlyHandledLock sync.Mutex
  134. recentlyHandledIndex uint8
  135. backfillLock sync.Mutex
  136. backfilling bool
  137. lastMessageTs uint64
  138. privateChatBackfillInvitePuppet func()
  139. messages chan PortalMessage
  140. isPrivate *bool
  141. hasRelaybot *bool
  142. }
  143. const MaxMessageAgeToCreatePortal = 5 * 60 // 5 minutes
  144. func (portal *Portal) handleMessageLoop() {
  145. for msg := range portal.messages {
  146. if len(portal.MXID) == 0 {
  147. if msg.timestamp+MaxMessageAgeToCreatePortal < uint64(time.Now().Unix()) {
  148. portal.log.Debugln("Not creating portal room for incoming message as the message is too old.")
  149. continue
  150. }
  151. portal.log.Debugln("Creating Matrix room from incoming message")
  152. err := portal.CreateMatrixRoom(msg.source)
  153. if err != nil {
  154. portal.log.Errorln("Failed to create portal room:", err)
  155. return
  156. }
  157. }
  158. portal.backfillLock.Lock()
  159. portal.handleMessage(msg)
  160. portal.backfillLock.Unlock()
  161. }
  162. }
  163. func (portal *Portal) handleMessage(msg PortalMessage) {
  164. if len(portal.MXID) == 0 {
  165. portal.log.Warnln("handleMessage called even though portal.MXID is empty")
  166. return
  167. }
  168. switch data := msg.data.(type) {
  169. case whatsapp.TextMessage:
  170. portal.HandleTextMessage(msg.source, data)
  171. case whatsapp.ImageMessage:
  172. portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, 0, false)
  173. case whatsapp.StickerMessage:
  174. portal.HandleMediaMessage(msg.source, data.Download, nil, data.Info, data.ContextInfo, data.Type, "", 0, true)
  175. case whatsapp.VideoMessage:
  176. portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, data.Length, false)
  177. case whatsapp.AudioMessage:
  178. portal.HandleMediaMessage(msg.source, data.Download, nil, data.Info, data.ContextInfo, data.Type, "", data.Length, false)
  179. case whatsapp.DocumentMessage:
  180. portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Title, 0, false)
  181. case whatsapp.ContactMessage:
  182. portal.HandleContactMessage(msg.source, data)
  183. case whatsapp.LocationMessage:
  184. portal.HandleLocationMessage(msg.source, data)
  185. case whatsappExt.MessageRevocation:
  186. portal.HandleMessageRevoke(msg.source, data)
  187. case FakeMessage:
  188. portal.HandleFakeMessage(msg.source, data)
  189. default:
  190. portal.log.Warnln("Unknown message type:", reflect.TypeOf(msg.data))
  191. }
  192. }
  193. func (portal *Portal) isRecentlyHandled(id types.WhatsAppMessageID) bool {
  194. start := portal.recentlyHandledIndex
  195. for i := start; i != start; i = (i - 1) % recentlyHandledLength {
  196. if portal.recentlyHandled[i] == id {
  197. return true
  198. }
  199. }
  200. return false
  201. }
  202. func (portal *Portal) isDuplicate(id types.WhatsAppMessageID) bool {
  203. msg := portal.bridge.DB.Message.GetByJID(portal.Key, id)
  204. if msg != nil {
  205. return true
  206. }
  207. return false
  208. }
  209. func init() {
  210. gob.Register(&waProto.Message{})
  211. }
  212. func (portal *Portal) markHandled(source *User, message *waProto.WebMessageInfo, mxid id.EventID) {
  213. msg := portal.bridge.DB.Message.New()
  214. msg.Chat = portal.Key
  215. msg.JID = message.GetKey().GetId()
  216. msg.MXID = mxid
  217. msg.Timestamp = message.GetMessageTimestamp()
  218. if message.GetKey().GetFromMe() {
  219. msg.Sender = source.JID
  220. } else if portal.IsPrivateChat() {
  221. msg.Sender = portal.Key.JID
  222. } else {
  223. msg.Sender = message.GetKey().GetParticipant()
  224. if len(msg.Sender) == 0 {
  225. msg.Sender = message.GetParticipant()
  226. }
  227. }
  228. msg.Content = message.Message
  229. msg.Insert()
  230. portal.recentlyHandledLock.Lock()
  231. index := portal.recentlyHandledIndex
  232. portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
  233. portal.recentlyHandledLock.Unlock()
  234. portal.recentlyHandled[index] = msg.JID
  235. }
  236. func (portal *Portal) getMessageIntent(user *User, info whatsapp.MessageInfo) *appservice.IntentAPI {
  237. if info.FromMe {
  238. return portal.bridge.GetPuppetByJID(user.JID).IntentFor(portal)
  239. } else if portal.IsPrivateChat() {
  240. return portal.MainIntent()
  241. } else if len(info.SenderJid) == 0 {
  242. if len(info.Source.GetParticipant()) != 0 {
  243. info.SenderJid = info.Source.GetParticipant()
  244. } else {
  245. return nil
  246. }
  247. }
  248. return portal.bridge.GetPuppetByJID(info.SenderJid).IntentFor(portal)
  249. }
  250. func (portal *Portal) startHandling(source *User, info whatsapp.MessageInfo) *appservice.IntentAPI {
  251. // TODO these should all be trace logs
  252. if portal.lastMessageTs > info.Timestamp+1 {
  253. portal.log.Debugfln("Not handling %s: message is older (%d) than last bridge message (%d)", info.Id, info.Timestamp, portal.lastMessageTs)
  254. } else if portal.isRecentlyHandled(info.Id) {
  255. portal.log.Debugfln("Not handling %s: message was recently handled", info.Id)
  256. } else if portal.isDuplicate(info.Id) {
  257. portal.log.Debugfln("Not handling %s: message is duplicate", info.Id)
  258. } else {
  259. portal.log.Debugfln("Starting handling of %s (ts: %d)", info.Id, info.Timestamp)
  260. portal.lastMessageTs = info.Timestamp
  261. return portal.getMessageIntent(source, info)
  262. }
  263. return nil
  264. }
  265. func (portal *Portal) finishHandling(source *User, message *waProto.WebMessageInfo, mxid id.EventID) {
  266. portal.markHandled(source, message, mxid)
  267. portal.sendDeliveryReceipt(mxid)
  268. portal.log.Debugln("Handled message", message.GetKey().GetId(), "->", mxid)
  269. }
  270. func (portal *Portal) SyncParticipants(metadata *whatsappExt.GroupInfo) {
  271. changed := false
  272. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  273. if err != nil {
  274. levels = portal.GetBasePowerLevels()
  275. changed = true
  276. }
  277. for _, participant := range metadata.Participants {
  278. user := portal.bridge.GetUserByJID(participant.JID)
  279. portal.userMXIDAction(user, portal.ensureMXIDInvited)
  280. puppet := portal.bridge.GetPuppetByJID(participant.JID)
  281. err := puppet.IntentFor(portal).EnsureJoined(portal.MXID)
  282. if err != nil {
  283. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.JID, portal.MXID, err)
  284. }
  285. expectedLevel := 0
  286. if participant.IsSuperAdmin {
  287. expectedLevel = 95
  288. } else if participant.IsAdmin {
  289. expectedLevel = 50
  290. }
  291. changed = levels.EnsureUserLevel(puppet.MXID, expectedLevel) || changed
  292. if user != nil {
  293. changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed
  294. }
  295. }
  296. if changed {
  297. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  298. if err != nil {
  299. portal.log.Errorln("Failed to change power levels:", err)
  300. }
  301. }
  302. }
  303. func (portal *Portal) UpdateAvatar(user *User, avatar *whatsappExt.ProfilePicInfo, updateInfo bool) bool {
  304. if avatar == nil {
  305. var err error
  306. avatar, err = user.Conn.GetProfilePicThumb(portal.Key.JID)
  307. if err != nil {
  308. portal.log.Errorln(err)
  309. return false
  310. }
  311. }
  312. if avatar.Status != 0 {
  313. return false
  314. }
  315. if portal.Avatar == avatar.Tag {
  316. return false
  317. }
  318. data, err := avatar.DownloadBytes()
  319. if err != nil {
  320. portal.log.Warnln("Failed to download avatar:", err)
  321. return false
  322. }
  323. mimeType := http.DetectContentType(data)
  324. resp, err := portal.MainIntent().UploadBytes(data, mimeType)
  325. if err != nil {
  326. portal.log.Warnln("Failed to upload avatar:", err)
  327. return false
  328. }
  329. portal.AvatarURL = resp.ContentURI
  330. if len(portal.MXID) > 0 {
  331. _, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI)
  332. if err != nil {
  333. portal.log.Warnln("Failed to set room topic:", err)
  334. return false
  335. }
  336. }
  337. portal.Avatar = avatar.Tag
  338. if updateInfo {
  339. portal.UpdateBridgeInfo()
  340. }
  341. return true
  342. }
  343. func (portal *Portal) UpdateName(name string, setBy types.WhatsAppID, updateInfo bool) bool {
  344. if portal.Name != name {
  345. intent := portal.MainIntent()
  346. if len(setBy) > 0 {
  347. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  348. }
  349. _, err := intent.SetRoomName(portal.MXID, name)
  350. if err == nil {
  351. portal.Name = name
  352. if updateInfo {
  353. portal.UpdateBridgeInfo()
  354. }
  355. return true
  356. }
  357. portal.log.Warnln("Failed to set room name:", err)
  358. }
  359. return false
  360. }
  361. func (portal *Portal) UpdateTopic(topic string, setBy types.WhatsAppID, updateInfo bool) bool {
  362. if portal.Topic != topic {
  363. intent := portal.MainIntent()
  364. if len(setBy) > 0 {
  365. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  366. }
  367. _, err := intent.SetRoomTopic(portal.MXID, topic)
  368. if err == nil {
  369. portal.Topic = topic
  370. if updateInfo {
  371. portal.UpdateBridgeInfo()
  372. }
  373. return true
  374. }
  375. portal.log.Warnln("Failed to set room topic:", err)
  376. }
  377. return false
  378. }
  379. func (portal *Portal) UpdateMetadata(user *User) bool {
  380. if portal.IsPrivateChat() {
  381. return false
  382. } else if portal.IsStatusBroadcastRoom() {
  383. update := false
  384. update = portal.UpdateName("WhatsApp Status Broadcast", "", false) || update
  385. update = portal.UpdateTopic("WhatsApp status updates from your contacts", "", false) || update
  386. return update
  387. }
  388. metadata, err := user.Conn.GetGroupMetaData(portal.Key.JID)
  389. if err != nil {
  390. portal.log.Errorln(err)
  391. return false
  392. }
  393. if metadata.Status != 0 {
  394. // 401: access denied
  395. // 404: group does (no longer) exist
  396. // 500: ??? happens with status@broadcast
  397. // TODO: update the room, e.g. change priority level
  398. // to send messages to moderator
  399. return false
  400. }
  401. portal.SyncParticipants(metadata)
  402. update := false
  403. update = portal.UpdateName(metadata.Name, metadata.NameSetBy, false) || update
  404. update = portal.UpdateTopic(metadata.Topic, metadata.TopicSetBy, false) || update
  405. return update
  406. }
  407. func (portal *Portal) userMXIDAction(user *User, fn func(mxid id.UserID)) {
  408. if user == nil {
  409. return
  410. }
  411. if user == portal.bridge.Relaybot {
  412. for _, mxid := range portal.bridge.Config.Bridge.Relaybot.InviteUsers {
  413. fn(mxid)
  414. }
  415. } else {
  416. fn(user.MXID)
  417. }
  418. }
  419. func (portal *Portal) ensureMXIDInvited(mxid id.UserID) {
  420. err := portal.MainIntent().EnsureInvited(portal.MXID, mxid)
  421. if err != nil {
  422. portal.log.Warnfln("Failed to ensure %s is invited to %s: %v", mxid, portal.MXID, err)
  423. }
  424. }
  425. func (portal *Portal) ensureUserInvited(user *User) {
  426. portal.userMXIDAction(user, portal.ensureMXIDInvited)
  427. customPuppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
  428. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  429. _ = customPuppet.CustomIntent().EnsureJoined(portal.MXID)
  430. }
  431. }
  432. func (portal *Portal) Sync(user *User, contact whatsapp.Contact) {
  433. portal.log.Infoln("Syncing portal for", user.MXID)
  434. if user.IsRelaybot {
  435. yes := true
  436. portal.hasRelaybot = &yes
  437. }
  438. if len(portal.MXID) == 0 {
  439. if !portal.IsPrivateChat() {
  440. portal.Name = contact.Name
  441. }
  442. err := portal.CreateMatrixRoom(user)
  443. if err != nil {
  444. portal.log.Errorln("Failed to create portal room:", err)
  445. return
  446. }
  447. } else {
  448. portal.ensureUserInvited(user)
  449. }
  450. if portal.IsPrivateChat() {
  451. return
  452. }
  453. update := false
  454. update = portal.UpdateMetadata(user) || update
  455. if !portal.IsStatusBroadcastRoom() {
  456. update = portal.UpdateAvatar(user, nil, false) || update
  457. }
  458. if update {
  459. portal.Update()
  460. portal.UpdateBridgeInfo()
  461. }
  462. }
  463. func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
  464. anyone := 0
  465. nope := 99
  466. invite := 99
  467. if portal.bridge.Config.Bridge.AllowUserInvite {
  468. invite = 0
  469. }
  470. return &event.PowerLevelsEventContent{
  471. UsersDefault: anyone,
  472. EventsDefault: anyone,
  473. RedactPtr: &anyone,
  474. StateDefaultPtr: &nope,
  475. BanPtr: &nope,
  476. InvitePtr: &invite,
  477. Users: map[id.UserID]int{
  478. portal.MainIntent().UserID: 100,
  479. },
  480. Events: map[string]int{
  481. event.StateRoomName.Type: anyone,
  482. event.StateRoomAvatar.Type: anyone,
  483. event.StateTopic.Type: anyone,
  484. },
  485. }
  486. }
  487. func (portal *Portal) ChangeAdminStatus(jids []string, setAdmin bool) {
  488. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  489. if err != nil {
  490. levels = portal.GetBasePowerLevels()
  491. }
  492. newLevel := 0
  493. if setAdmin {
  494. newLevel = 50
  495. }
  496. changed := false
  497. for _, jid := range jids {
  498. puppet := portal.bridge.GetPuppetByJID(jid)
  499. changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
  500. user := portal.bridge.GetUserByJID(jid)
  501. if user != nil {
  502. changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
  503. }
  504. }
  505. if changed {
  506. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  507. if err != nil {
  508. portal.log.Errorln("Failed to change power levels:", err)
  509. }
  510. }
  511. }
  512. func (portal *Portal) RestrictMessageSending(restrict bool) {
  513. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  514. if err != nil {
  515. levels = portal.GetBasePowerLevels()
  516. }
  517. if restrict {
  518. levels.EventsDefault = 50
  519. } else {
  520. levels.EventsDefault = 0
  521. }
  522. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  523. if err != nil {
  524. portal.log.Errorln("Failed to change power levels:", err)
  525. }
  526. }
  527. func (portal *Portal) RestrictMetadataChanges(restrict bool) {
  528. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  529. if err != nil {
  530. levels = portal.GetBasePowerLevels()
  531. }
  532. newLevel := 0
  533. if restrict {
  534. newLevel = 50
  535. }
  536. changed := false
  537. changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
  538. changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
  539. changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
  540. if changed {
  541. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  542. if err != nil {
  543. portal.log.Errorln("Failed to change power levels:", err)
  544. }
  545. }
  546. }
  547. func (portal *Portal) BackfillHistory(user *User, lastMessageTime uint64) error {
  548. if !portal.bridge.Config.Bridge.RecoverHistory {
  549. return nil
  550. }
  551. endBackfill := portal.beginBackfill()
  552. defer endBackfill()
  553. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  554. if lastMessage == nil {
  555. return nil
  556. }
  557. if lastMessage.Timestamp >= lastMessageTime {
  558. portal.log.Debugln("Not backfilling: no new messages")
  559. return nil
  560. }
  561. lastMessageID := lastMessage.JID
  562. lastMessageFromMe := lastMessage.Sender == user.JID
  563. portal.log.Infoln("Backfilling history since", lastMessageID, "for", user.MXID)
  564. for len(lastMessageID) > 0 {
  565. portal.log.Debugln("Backfilling history: 50 messages after", lastMessageID)
  566. resp, err := user.Conn.LoadMessagesAfter(portal.Key.JID, lastMessageID, lastMessageFromMe, 50)
  567. if err != nil {
  568. return err
  569. }
  570. messages, ok := resp.Content.([]interface{})
  571. if !ok || len(messages) == 0 {
  572. break
  573. }
  574. portal.handleHistory(user, messages)
  575. lastMessageProto, ok := messages[len(messages)-1].(*waProto.WebMessageInfo)
  576. if ok {
  577. lastMessageID = lastMessageProto.GetKey().GetId()
  578. lastMessageFromMe = lastMessageProto.GetKey().GetFromMe()
  579. }
  580. }
  581. portal.log.Infoln("Backfilling finished")
  582. return nil
  583. }
  584. func (portal *Portal) beginBackfill() func() {
  585. portal.backfillLock.Lock()
  586. portal.backfilling = true
  587. var privateChatPuppetInvited bool
  588. var privateChatPuppet *Puppet
  589. if portal.IsPrivateChat() && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling {
  590. privateChatPuppet = portal.bridge.GetPuppetByJID(portal.Key.Receiver)
  591. portal.privateChatBackfillInvitePuppet = func() {
  592. if privateChatPuppetInvited {
  593. return
  594. }
  595. privateChatPuppetInvited = true
  596. _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: privateChatPuppet.MXID})
  597. _ = privateChatPuppet.DefaultIntent().EnsureJoined(portal.MXID)
  598. }
  599. }
  600. return func() {
  601. portal.backfilling = false
  602. portal.privateChatBackfillInvitePuppet = nil
  603. portal.backfillLock.Unlock()
  604. if privateChatPuppet != nil && privateChatPuppetInvited {
  605. _, _ = privateChatPuppet.DefaultIntent().LeaveRoom(portal.MXID)
  606. }
  607. }
  608. }
  609. func (portal *Portal) disableNotifications(user *User) {
  610. if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
  611. return
  612. }
  613. puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
  614. if puppet == nil || puppet.customIntent == nil {
  615. return
  616. }
  617. portal.log.Debugfln("Disabling notifications for %s for backfilling", user.MXID)
  618. ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
  619. err := puppet.customIntent.PutPushRule("global", pushrules.OverrideRule, ruleID, &mautrix.ReqPutPushRule{
  620. Actions: []pushrules.PushActionType{pushrules.ActionDontNotify},
  621. Conditions: []pushrules.PushCondition{{
  622. Kind: pushrules.KindEventMatch,
  623. Key: "room_id",
  624. Pattern: string(portal.MXID),
  625. }},
  626. })
  627. if err != nil {
  628. portal.log.Warnfln("Failed to disable notifications for %s while backfilling: %v", user.MXID, err)
  629. }
  630. }
  631. func (portal *Portal) enableNotifications(user *User) {
  632. if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
  633. return
  634. }
  635. puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
  636. if puppet == nil || puppet.customIntent == nil {
  637. return
  638. }
  639. portal.log.Debugfln("Re-enabling notifications for %s after backfilling", user.MXID)
  640. ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
  641. err := puppet.customIntent.DeletePushRule("global", pushrules.OverrideRule, ruleID)
  642. if err != nil {
  643. portal.log.Warnfln("Failed to re-enable notifications for %s after backfilling: %v", user.MXID, err)
  644. }
  645. }
  646. func (portal *Portal) FillInitialHistory(user *User) error {
  647. if portal.bridge.Config.Bridge.InitialHistoryFill == 0 {
  648. return nil
  649. }
  650. endBackfill := portal.beginBackfill()
  651. defer endBackfill()
  652. if portal.privateChatBackfillInvitePuppet != nil {
  653. portal.privateChatBackfillInvitePuppet()
  654. }
  655. n := portal.bridge.Config.Bridge.InitialHistoryFill
  656. portal.log.Infoln("Filling initial history, maximum", n, "messages")
  657. var messages []interface{}
  658. before := ""
  659. fromMe := true
  660. chunkNum := 1
  661. for n > 0 {
  662. count := 50
  663. if n < count {
  664. count = n
  665. }
  666. portal.log.Debugfln("Fetching chunk %d (%d messages / %d cap) before message %s", chunkNum, count, n, before)
  667. resp, err := user.Conn.LoadMessagesBefore(portal.Key.JID, before, fromMe, count)
  668. if err != nil {
  669. return err
  670. }
  671. chunk, ok := resp.Content.([]interface{})
  672. if !ok || len(chunk) == 0 {
  673. portal.log.Infoln("Chunk empty, starting handling of loaded messages")
  674. break
  675. }
  676. messages = append(chunk, messages...)
  677. portal.log.Debugfln("Fetched chunk and received %d messages", len(chunk))
  678. n -= len(chunk)
  679. key := chunk[0].(*waProto.WebMessageInfo).GetKey()
  680. before = key.GetId()
  681. fromMe = key.GetFromMe()
  682. if len(before) == 0 {
  683. portal.log.Infoln("No message ID for first message, starting handling of loaded messages")
  684. break
  685. }
  686. }
  687. portal.disableNotifications(user)
  688. portal.handleHistory(user, messages)
  689. portal.enableNotifications(user)
  690. portal.log.Infoln("Initial history fill complete")
  691. return nil
  692. }
  693. func (portal *Portal) handleHistory(user *User, messages []interface{}) {
  694. portal.log.Infoln("Handling", len(messages), "messages of history")
  695. for _, rawMessage := range messages {
  696. message, ok := rawMessage.(*waProto.WebMessageInfo)
  697. if !ok {
  698. portal.log.Warnln("Unexpected non-WebMessageInfo item in history response:", rawMessage)
  699. continue
  700. }
  701. data := whatsapp.ParseProtoMessage(message)
  702. if data == nil {
  703. portal.log.Warnln("Message", message.GetKey().GetId(), "failed to parse during backfilling")
  704. continue
  705. }
  706. if portal.privateChatBackfillInvitePuppet != nil && message.GetKey().GetFromMe() && portal.IsPrivateChat() {
  707. portal.privateChatBackfillInvitePuppet()
  708. }
  709. portal.handleMessage(PortalMessage{portal.Key.JID, user, data, message.GetMessageTimestamp()})
  710. }
  711. }
  712. type BridgeInfoSection struct {
  713. ID string `json:"id"`
  714. DisplayName string `json:"display_name,omitempty"`
  715. AvatarURL id.ContentURIString `json:"avatar_url,omitempty"`
  716. ExternalURL string `json:"external_url,omitempty"`
  717. }
  718. type BridgeInfoContent struct {
  719. BridgeBot id.UserID `json:"bridgebot"`
  720. Creator id.UserID `json:"creator,omitempty"`
  721. Protocol BridgeInfoSection `json:"protocol"`
  722. Network *BridgeInfoSection `json:"network,omitempty"`
  723. Channel BridgeInfoSection `json:"channel"`
  724. }
  725. var (
  726. StateBridgeInfo = event.Type{Type: "m.bridge", Class: event.StateEventType}
  727. StateHalfShotBridgeInfo = event.Type{Type: "uk.half-shot.bridge", Class: event.StateEventType}
  728. )
  729. func (portal *Portal) getBridgeInfo() (string, event.Content) {
  730. bridgeInfo := event.Content{
  731. Parsed: BridgeInfoContent{
  732. BridgeBot: portal.bridge.Bot.UserID,
  733. Creator: portal.MainIntent().UserID,
  734. Protocol: BridgeInfoSection{
  735. ID: "whatsapp",
  736. DisplayName: "WhatsApp",
  737. AvatarURL: id.ContentURIString(portal.bridge.Config.AppService.Bot.Avatar),
  738. ExternalURL: "https://www.whatsapp.com/",
  739. },
  740. Channel: BridgeInfoSection{
  741. ID: portal.Key.JID,
  742. DisplayName: portal.Name,
  743. AvatarURL: portal.AvatarURL.CUString(),
  744. },
  745. },
  746. }
  747. bridgeInfoStateKey := fmt.Sprintf("net.maunium.whatsapp://whatsapp/%s", portal.Key.JID)
  748. return bridgeInfoStateKey, bridgeInfo
  749. }
  750. func (portal *Portal) UpdateBridgeInfo() {
  751. if len(portal.MXID) == 0 {
  752. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  753. return
  754. }
  755. portal.log.Debugln("Updating bridge info...")
  756. stateKey, content := portal.getBridgeInfo()
  757. _, err := portal.MainIntent().SendStateEvent(portal.MXID, StateBridgeInfo, stateKey, content)
  758. if err != nil {
  759. portal.log.Warnln("Failed to update m.bridge:", err)
  760. }
  761. _, err = portal.MainIntent().SendStateEvent(portal.MXID, StateHalfShotBridgeInfo, stateKey, content)
  762. if err != nil {
  763. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  764. }
  765. }
  766. func (portal *Portal) CreateMatrixRoom(user *User) error {
  767. portal.roomCreateLock.Lock()
  768. defer portal.roomCreateLock.Unlock()
  769. if len(portal.MXID) > 0 {
  770. return nil
  771. }
  772. intent := portal.MainIntent()
  773. if err := intent.EnsureRegistered(); err != nil {
  774. return err
  775. }
  776. portal.log.Infoln("Creating Matrix room. Info source:", user.MXID)
  777. var metadata *whatsappExt.GroupInfo
  778. if portal.IsPrivateChat() {
  779. puppet := portal.bridge.GetPuppetByJID(portal.Key.JID)
  780. if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
  781. portal.Name = puppet.Displayname
  782. portal.AvatarURL = puppet.AvatarURL
  783. portal.Avatar = puppet.Avatar
  784. } else {
  785. portal.Name = ""
  786. }
  787. portal.Topic = "WhatsApp private chat"
  788. } else if portal.IsStatusBroadcastRoom() {
  789. portal.Name = "WhatsApp Status Broadcast"
  790. portal.Topic = "WhatsApp status updates from your contacts"
  791. } else {
  792. var err error
  793. metadata, err = user.Conn.GetGroupMetaData(portal.Key.JID)
  794. if err == nil && metadata.Status == 0 {
  795. portal.Name = metadata.Name
  796. portal.Topic = metadata.Topic
  797. }
  798. portal.UpdateAvatar(user, nil, false)
  799. }
  800. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  801. initialState := []*event.Event{{
  802. Type: event.StatePowerLevels,
  803. Content: event.Content{
  804. Parsed: portal.GetBasePowerLevels(),
  805. },
  806. }, {
  807. Type: StateBridgeInfo,
  808. Content: bridgeInfo,
  809. StateKey: &bridgeInfoStateKey,
  810. }, {
  811. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  812. Type: StateHalfShotBridgeInfo,
  813. Content: bridgeInfo,
  814. StateKey: &bridgeInfoStateKey,
  815. }}
  816. if !portal.AvatarURL.IsEmpty() {
  817. initialState = append(initialState, &event.Event{
  818. Type: event.StateRoomAvatar,
  819. Content: event.Content{
  820. Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL},
  821. },
  822. })
  823. }
  824. invite := []id.UserID{user.MXID}
  825. if user.IsRelaybot {
  826. invite = portal.bridge.Config.Bridge.Relaybot.InviteUsers
  827. }
  828. if portal.bridge.Config.Bridge.Encryption.Default {
  829. initialState = append(initialState, &event.Event{
  830. Type: event.StateEncryption,
  831. Content: event.Content{
  832. Parsed: event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1},
  833. },
  834. })
  835. portal.Encrypted = true
  836. if portal.IsPrivateChat() {
  837. invite = append(invite, portal.bridge.Bot.UserID)
  838. }
  839. }
  840. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  841. Visibility: "private",
  842. Name: portal.Name,
  843. Topic: portal.Topic,
  844. Invite: invite,
  845. Preset: "private_chat",
  846. IsDirect: portal.IsPrivateChat(),
  847. InitialState: initialState,
  848. })
  849. if err != nil {
  850. return err
  851. }
  852. portal.MXID = resp.RoomID
  853. portal.Update()
  854. portal.bridge.portalsLock.Lock()
  855. portal.bridge.portalsByMXID[portal.MXID] = portal
  856. portal.bridge.portalsLock.Unlock()
  857. // We set the memberships beforehand to make sure the encryption key exchange in initial backfill knows the users are here.
  858. for _, user := range invite {
  859. portal.bridge.StateStore.SetMembership(portal.MXID, user, event.MembershipInvite)
  860. }
  861. if metadata != nil {
  862. portal.SyncParticipants(metadata)
  863. } else {
  864. customPuppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
  865. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  866. _ = customPuppet.CustomIntent().EnsureJoined(portal.MXID)
  867. }
  868. }
  869. user.addPortalToCommunity(portal)
  870. if portal.IsPrivateChat() {
  871. puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
  872. user.addPuppetToCommunity(puppet)
  873. if portal.bridge.Config.Bridge.Encryption.Default {
  874. err = portal.bridge.Bot.EnsureJoined(portal.MXID)
  875. if err != nil {
  876. portal.log.Errorln("Failed to join created portal with bridge bot for e2be:", err)
  877. }
  878. }
  879. }
  880. err = portal.FillInitialHistory(user)
  881. if err != nil {
  882. portal.log.Errorln("Failed to fill history:", err)
  883. }
  884. return nil
  885. }
  886. func (portal *Portal) IsPrivateChat() bool {
  887. if portal.isPrivate == nil {
  888. val := strings.HasSuffix(portal.Key.JID, whatsappExt.NewUserSuffix)
  889. portal.isPrivate = &val
  890. }
  891. return *portal.isPrivate
  892. }
  893. func (portal *Portal) HasRelaybot() bool {
  894. if portal.bridge.Relaybot == nil {
  895. return false
  896. } else if portal.hasRelaybot == nil {
  897. val := portal.bridge.Relaybot.IsInPortal(portal.Key)
  898. portal.hasRelaybot = &val
  899. }
  900. return *portal.hasRelaybot
  901. }
  902. func (portal *Portal) IsStatusBroadcastRoom() bool {
  903. return portal.Key.JID == "status@broadcast"
  904. }
  905. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  906. if portal.IsPrivateChat() {
  907. return portal.bridge.GetPuppetByJID(portal.Key.JID).DefaultIntent()
  908. }
  909. return portal.bridge.Bot
  910. }
  911. func (portal *Portal) SetReply(content *event.MessageEventContent, info whatsapp.ContextInfo) {
  912. if len(info.QuotedMessageID) == 0 {
  913. return
  914. }
  915. message := portal.bridge.DB.Message.GetByJID(portal.Key, info.QuotedMessageID)
  916. if message != nil {
  917. evt, err := portal.MainIntent().GetEvent(portal.MXID, message.MXID)
  918. if err != nil {
  919. portal.log.Warnln("Failed to get reply target:", err)
  920. return
  921. }
  922. content.SetReply(evt)
  923. }
  924. return
  925. }
  926. func (portal *Portal) HandleMessageRevoke(user *User, message whatsappExt.MessageRevocation) {
  927. msg := portal.bridge.DB.Message.GetByJID(portal.Key, message.Id)
  928. if msg == nil {
  929. return
  930. }
  931. var intent *appservice.IntentAPI
  932. if message.FromMe {
  933. if portal.IsPrivateChat() {
  934. intent = portal.bridge.GetPuppetByJID(user.JID).CustomIntent()
  935. } else {
  936. intent = portal.bridge.GetPuppetByJID(user.JID).IntentFor(portal)
  937. }
  938. } else if len(message.Participant) > 0 {
  939. intent = portal.bridge.GetPuppetByJID(message.Participant).IntentFor(portal)
  940. }
  941. if intent == nil {
  942. intent = portal.MainIntent()
  943. }
  944. _, err := intent.RedactEvent(portal.MXID, msg.MXID)
  945. if err != nil {
  946. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  947. return
  948. }
  949. msg.Delete()
  950. }
  951. func (portal *Portal) HandleFakeMessage(source *User, message FakeMessage) {
  952. if portal.isRecentlyHandled(message.ID) {
  953. return
  954. }
  955. content := event.MessageEventContent{
  956. MsgType: event.MsgNotice,
  957. Body: message.Text,
  958. }
  959. if message.Alert {
  960. content.MsgType = event.MsgText
  961. }
  962. _, err := portal.sendMainIntentMessage(content)
  963. if err != nil {
  964. portal.log.Errorfln("Failed to handle fake message %s: %v", message.ID, err)
  965. return
  966. }
  967. portal.recentlyHandledLock.Lock()
  968. index := portal.recentlyHandledIndex
  969. portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
  970. portal.recentlyHandledLock.Unlock()
  971. portal.recentlyHandled[index] = message.ID
  972. }
  973. func (portal *Portal) sendMainIntentMessage(content interface{}) (*mautrix.RespSendEvent, error) {
  974. return portal.sendMessage(portal.MainIntent(), event.EventMessage, content, 0)
  975. }
  976. func (portal *Portal) sendMessage(intent *appservice.IntentAPI, eventType event.Type, content interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  977. wrappedContent := event.Content{Parsed: content}
  978. if timestamp != 0 && intent.IsCustomPuppet {
  979. wrappedContent.Raw = map[string]interface{}{
  980. "net.maunium.whatsapp.puppet": intent.IsCustomPuppet,
  981. }
  982. }
  983. if portal.Encrypted && portal.bridge.Crypto != nil {
  984. encrypted, err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, wrappedContent)
  985. if err != nil {
  986. return nil, errors.Wrap(err, "failed to encrypt event")
  987. }
  988. eventType = event.EventEncrypted
  989. wrappedContent.Parsed = encrypted
  990. }
  991. if timestamp == 0 {
  992. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  993. } else {
  994. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  995. }
  996. }
  997. func (portal *Portal) HandleTextMessage(source *User, message whatsapp.TextMessage) {
  998. intent := portal.startHandling(source, message.Info)
  999. if intent == nil {
  1000. return
  1001. }
  1002. content := &event.MessageEventContent{
  1003. Body: message.Text,
  1004. MsgType: event.MsgText,
  1005. }
  1006. portal.bridge.Formatter.ParseWhatsApp(content)
  1007. portal.SetReply(content, message.ContextInfo)
  1008. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1009. resp, err := portal.sendMessage(intent, event.EventMessage, content, int64(message.Info.Timestamp*1000))
  1010. if err != nil {
  1011. portal.log.Errorfln("Failed to handle message %s: %v", message.Info.Id, err)
  1012. return
  1013. }
  1014. portal.finishHandling(source, message.Info.Source, resp.EventID)
  1015. }
  1016. func (portal *Portal) HandleLocationMessage(source *User, message whatsapp.LocationMessage) {
  1017. intent := portal.startHandling(source, message.Info)
  1018. if intent == nil {
  1019. return
  1020. }
  1021. url := message.Url
  1022. if len(url) == 0 {
  1023. url = fmt.Sprintf("https://maps.google.com/?q=%.5f,%.5f", message.DegreesLatitude, message.DegreesLongitude)
  1024. }
  1025. name := message.Name
  1026. if len(name) == 0 {
  1027. latChar := 'N'
  1028. if message.DegreesLatitude < 0 {
  1029. latChar = 'S'
  1030. }
  1031. longChar := 'E'
  1032. if message.DegreesLongitude < 0 {
  1033. longChar = 'W'
  1034. }
  1035. name = fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(message.DegreesLatitude), latChar, math.Abs(message.DegreesLongitude), longChar)
  1036. }
  1037. content := &event.MessageEventContent{
  1038. MsgType: event.MsgLocation,
  1039. Body: fmt.Sprintf("Location: %s\n%s\n%s", name, message.Address, url),
  1040. Format: event.FormatHTML,
  1041. FormattedBody: fmt.Sprintf("Location: <a href='%s'>%s</a><br>%s", url, name, message.Address),
  1042. GeoURI: fmt.Sprintf("geo:%.5f,%.5f", message.DegreesLatitude, message.DegreesLongitude),
  1043. }
  1044. if len(message.JpegThumbnail) > 0 {
  1045. thumbnailMime := http.DetectContentType(message.JpegThumbnail)
  1046. uploadedThumbnail, _ := intent.UploadBytes(message.JpegThumbnail, thumbnailMime)
  1047. if uploadedThumbnail != nil {
  1048. cfg, _, _ := image.DecodeConfig(bytes.NewReader(message.JpegThumbnail))
  1049. content.Info = &event.FileInfo{
  1050. ThumbnailInfo: &event.FileInfo{
  1051. Size: len(message.JpegThumbnail),
  1052. Width: cfg.Width,
  1053. Height: cfg.Height,
  1054. MimeType: thumbnailMime,
  1055. },
  1056. ThumbnailURL: uploadedThumbnail.ContentURI.CUString(),
  1057. }
  1058. }
  1059. }
  1060. portal.SetReply(content, message.ContextInfo)
  1061. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1062. resp, err := portal.sendMessage(intent, event.EventMessage, content, int64(message.Info.Timestamp*1000))
  1063. if err != nil {
  1064. portal.log.Errorfln("Failed to handle message %s: %v", message.Info.Id, err)
  1065. return
  1066. }
  1067. portal.finishHandling(source, message.Info.Source, resp.EventID)
  1068. }
  1069. func (portal *Portal) HandleContactMessage(source *User, message whatsapp.ContactMessage) {
  1070. intent := portal.startHandling(source, message.Info)
  1071. if intent == nil {
  1072. return
  1073. }
  1074. fileName := fmt.Sprintf("%s.vcf", message.DisplayName)
  1075. data := []byte(message.Vcard)
  1076. mimeType := "text/vcard"
  1077. data, uploadMimeType, file := portal.encryptFile(data, mimeType)
  1078. uploadResp, err := intent.UploadBytesWithName(data, uploadMimeType, fileName)
  1079. if err != nil {
  1080. portal.log.Errorfln("Failed to upload vcard of %s: %v", message.DisplayName, err)
  1081. return
  1082. }
  1083. content := &event.MessageEventContent{
  1084. Body: fileName,
  1085. MsgType: event.MsgFile,
  1086. File: file,
  1087. Info: &event.FileInfo{
  1088. MimeType: mimeType,
  1089. Size: len(message.Vcard),
  1090. },
  1091. }
  1092. if content.File != nil {
  1093. content.File.URL = uploadResp.ContentURI.CUString()
  1094. } else {
  1095. content.URL = uploadResp.ContentURI.CUString()
  1096. }
  1097. portal.SetReply(content, message.ContextInfo)
  1098. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1099. resp, err := portal.sendMessage(intent, event.EventMessage, content, int64(message.Info.Timestamp*1000))
  1100. if err != nil {
  1101. portal.log.Errorfln("Failed to handle message %s: %v", message.Info.Id, err)
  1102. return
  1103. }
  1104. portal.finishHandling(source, message.Info.Source, resp.EventID)
  1105. }
  1106. func (portal *Portal) sendMediaBridgeFailure(source *User, intent *appservice.IntentAPI, info whatsapp.MessageInfo, downloadErr error) {
  1107. portal.log.Errorfln("Failed to download media for %s: %v", info.Id, downloadErr)
  1108. resp, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  1109. MsgType: event.MsgNotice,
  1110. Body: "Failed to bridge media",
  1111. }, int64(info.Timestamp*1000))
  1112. if err != nil {
  1113. portal.log.Errorfln("Failed to send media download error message for %s: %v", info.Id, err)
  1114. } else {
  1115. portal.finishHandling(source, info.Source, resp.EventID)
  1116. }
  1117. }
  1118. func (portal *Portal) encryptFile(data []byte, mimeType string) ([]byte, string, *event.EncryptedFileInfo) {
  1119. if !portal.Encrypted {
  1120. return data, mimeType, nil
  1121. }
  1122. file := &event.EncryptedFileInfo{
  1123. EncryptedFile: *attachment.NewEncryptedFile(),
  1124. URL: "",
  1125. }
  1126. return file.Encrypt(data), "application/octet-stream", file
  1127. }
  1128. func (portal *Portal) HandleMediaMessage(source *User, download func() ([]byte, error), thumbnail []byte, info whatsapp.MessageInfo, context whatsapp.ContextInfo, mimeType, caption string, length uint32, sendAsSticker bool) {
  1129. intent := portal.startHandling(source, info)
  1130. if intent == nil {
  1131. return
  1132. }
  1133. data, err := download()
  1134. if err == whatsapp.ErrMediaDownloadFailedWith404 || err == whatsapp.ErrMediaDownloadFailedWith410 {
  1135. portal.log.Warnfln("Failed to download media for %s: %v. Calling LoadMediaInfo and retrying download...", info.Id, err)
  1136. _, err = source.Conn.LoadMediaInfo(info.RemoteJid, info.Id, info.FromMe)
  1137. if err != nil {
  1138. portal.sendMediaBridgeFailure(source, intent, info, errors.Wrap(err, "failed to load media info"))
  1139. return
  1140. }
  1141. data, err = download()
  1142. }
  1143. if err == whatsapp.ErrNoURLPresent {
  1144. portal.log.Debugfln("No URL present error for media message %s, ignoring...", info.Id)
  1145. return
  1146. } else if err != nil {
  1147. portal.sendMediaBridgeFailure(source, intent, info, err)
  1148. return
  1149. }
  1150. // synapse doesn't handle webp well, so we convert it. This can be dropped once https://github.com/matrix-org/synapse/issues/4382 is fixed
  1151. if mimeType == "image/webp" {
  1152. img, err := decodeWebp(bytes.NewReader(data))
  1153. if err != nil {
  1154. portal.log.Errorfln("Failed to decode media for %s: %v", err)
  1155. return
  1156. }
  1157. var buf bytes.Buffer
  1158. err = png.Encode(&buf, img)
  1159. if err != nil {
  1160. portal.log.Errorfln("Failed to convert media for %s: %v", err)
  1161. return
  1162. }
  1163. data = buf.Bytes()
  1164. mimeType = "image/png"
  1165. }
  1166. var width, height int
  1167. if strings.HasPrefix(mimeType, "image/") {
  1168. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  1169. width, height = cfg.Width, cfg.Height
  1170. }
  1171. data, uploadMimeType, file := portal.encryptFile(data, mimeType)
  1172. uploaded, err := intent.UploadBytes(data, uploadMimeType)
  1173. if err != nil {
  1174. portal.log.Errorfln("Failed to upload media for %s: %v", err)
  1175. return
  1176. }
  1177. fileName := info.Id
  1178. exts, _ := mime.ExtensionsByType(mimeType)
  1179. if exts != nil && len(exts) > 0 {
  1180. fileName += exts[0]
  1181. }
  1182. content := &event.MessageEventContent{
  1183. Body: fileName,
  1184. File: file,
  1185. Info: &event.FileInfo{
  1186. Size: len(data),
  1187. MimeType: mimeType,
  1188. Width: width,
  1189. Height: height,
  1190. Duration: int(length),
  1191. },
  1192. }
  1193. if content.File != nil {
  1194. content.File.URL = uploaded.ContentURI.CUString()
  1195. } else {
  1196. content.URL = uploaded.ContentURI.CUString()
  1197. }
  1198. portal.SetReply(content, context)
  1199. if thumbnail != nil && portal.bridge.Config.Bridge.WhatsappThumbnail {
  1200. thumbnailMime := http.DetectContentType(thumbnail)
  1201. thumbnailCfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnail))
  1202. thumbnailSize := len(thumbnail)
  1203. thumbnail, thumbnailUploadMime, thumbnailFile := portal.encryptFile(thumbnail, thumbnailMime)
  1204. uploadedThumbnail, err := intent.UploadBytes(thumbnail, thumbnailUploadMime)
  1205. if err != nil {
  1206. portal.log.Warnfln("Failed to upload thumbnail for %s: %v", info.Id, err)
  1207. } else if uploadedThumbnail != nil {
  1208. if thumbnailFile != nil {
  1209. thumbnailFile.URL = uploadedThumbnail.ContentURI.CUString()
  1210. content.Info.ThumbnailFile = thumbnailFile
  1211. } else {
  1212. content.Info.ThumbnailURL = uploadedThumbnail.ContentURI.CUString()
  1213. }
  1214. content.Info.ThumbnailInfo = &event.FileInfo{
  1215. Size: thumbnailSize,
  1216. Width: thumbnailCfg.Width,
  1217. Height: thumbnailCfg.Height,
  1218. MimeType: thumbnailMime,
  1219. }
  1220. }
  1221. }
  1222. switch strings.ToLower(strings.Split(mimeType, "/")[0]) {
  1223. case "image":
  1224. if !sendAsSticker {
  1225. content.MsgType = event.MsgImage
  1226. }
  1227. case "video":
  1228. content.MsgType = event.MsgVideo
  1229. case "audio":
  1230. content.MsgType = event.MsgAudio
  1231. default:
  1232. content.MsgType = event.MsgFile
  1233. }
  1234. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1235. ts := int64(info.Timestamp * 1000)
  1236. eventType := event.EventMessage
  1237. if sendAsSticker {
  1238. eventType = event.EventSticker
  1239. }
  1240. resp, err := portal.sendMessage(intent, eventType, content, ts)
  1241. if err != nil {
  1242. portal.log.Errorfln("Failed to handle message %s: %v", info.Id, err)
  1243. return
  1244. }
  1245. if len(caption) > 0 {
  1246. captionContent := &event.MessageEventContent{
  1247. Body: caption,
  1248. MsgType: event.MsgNotice,
  1249. }
  1250. portal.bridge.Formatter.ParseWhatsApp(captionContent)
  1251. _, err := portal.sendMessage(intent, event.EventMessage, captionContent, ts)
  1252. if err != nil {
  1253. portal.log.Warnfln("Failed to handle caption of message %s: %v", info.Id, err)
  1254. }
  1255. // TODO store caption mxid?
  1256. }
  1257. portal.finishHandling(source, info.Source, resp.EventID)
  1258. }
  1259. func makeMessageID() *string {
  1260. b := make([]byte, 10)
  1261. rand.Read(b)
  1262. str := strings.ToUpper(hex.EncodeToString(b))
  1263. return &str
  1264. }
  1265. func (portal *Portal) downloadThumbnail(content *event.MessageEventContent, id id.EventID) []byte {
  1266. if len(content.GetInfo().ThumbnailURL) == 0 {
  1267. return nil
  1268. }
  1269. mxc, err := content.GetInfo().ThumbnailURL.Parse()
  1270. if err != nil {
  1271. portal.log.Errorln("Malformed thumbnail URL in %s: %v", id, err)
  1272. }
  1273. thumbnail, err := portal.MainIntent().DownloadBytes(mxc)
  1274. if err != nil {
  1275. portal.log.Errorln("Failed to download thumbnail in %s: %v", id, err)
  1276. return nil
  1277. }
  1278. thumbnailType := http.DetectContentType(thumbnail)
  1279. var img image.Image
  1280. switch thumbnailType {
  1281. case "image/png":
  1282. img, err = png.Decode(bytes.NewReader(thumbnail))
  1283. case "image/gif":
  1284. img, err = gif.Decode(bytes.NewReader(thumbnail))
  1285. case "image/jpeg":
  1286. return thumbnail
  1287. default:
  1288. return nil
  1289. }
  1290. var buf bytes.Buffer
  1291. err = jpeg.Encode(&buf, img, &jpeg.Options{
  1292. Quality: jpeg.DefaultQuality,
  1293. })
  1294. if err != nil {
  1295. portal.log.Errorln("Failed to re-encode thumbnail in %s: %v", id, err)
  1296. return nil
  1297. }
  1298. return buf.Bytes()
  1299. }
  1300. func (portal *Portal) preprocessMatrixMedia(sender *User, relaybotFormatted bool, content *event.MessageEventContent, eventID id.EventID, mediaType whatsapp.MediaType) *MediaUpload {
  1301. var caption string
  1302. if relaybotFormatted {
  1303. caption = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  1304. }
  1305. var file *event.EncryptedFileInfo
  1306. rawMXC := content.URL
  1307. if content.File != nil {
  1308. file = content.File
  1309. rawMXC = file.URL
  1310. }
  1311. mxc, err := rawMXC.Parse()
  1312. if err != nil {
  1313. portal.log.Errorln("Malformed content URL in %s: %v", eventID, err)
  1314. return nil
  1315. }
  1316. data, err := portal.MainIntent().DownloadBytes(mxc)
  1317. if err != nil {
  1318. portal.log.Errorfln("Failed to download media in %s: %v", eventID, err)
  1319. return nil
  1320. }
  1321. if file != nil {
  1322. data, err = file.Decrypt(data)
  1323. if err != nil {
  1324. portal.log.Errorfln("Failed to decrypt media in %s: %v", eventID, err)
  1325. return nil
  1326. }
  1327. }
  1328. url, mediaKey, fileEncSHA256, fileSHA256, fileLength, err := sender.Conn.Upload(bytes.NewReader(data), mediaType)
  1329. if err != nil {
  1330. portal.log.Errorfln("Failed to upload media in %s: %v", eventID, err)
  1331. return nil
  1332. }
  1333. return &MediaUpload{
  1334. Caption: caption,
  1335. URL: url,
  1336. MediaKey: mediaKey,
  1337. FileEncSHA256: fileEncSHA256,
  1338. FileSHA256: fileSHA256,
  1339. FileLength: fileLength,
  1340. Thumbnail: portal.downloadThumbnail(content, eventID),
  1341. }
  1342. }
  1343. type MediaUpload struct {
  1344. Caption string
  1345. URL string
  1346. MediaKey []byte
  1347. FileEncSHA256 []byte
  1348. FileSHA256 []byte
  1349. FileLength uint64
  1350. Thumbnail []byte
  1351. }
  1352. func (portal *Portal) sendMatrixConnectionError(sender *User, eventID id.EventID) bool {
  1353. if !sender.HasSession() {
  1354. portal.log.Debugln("Ignoring event", eventID, "from", sender.MXID, "as user has no session")
  1355. return true
  1356. } else if !sender.IsConnected() {
  1357. portal.log.Debugln("Ignoring event", eventID, "from", sender.MXID, "as user is not connected")
  1358. inRoom := ""
  1359. if portal.IsPrivateChat() {
  1360. inRoom = " in your management room"
  1361. }
  1362. reconnect := fmt.Sprintf("Use `%s reconnect`%s to reconnect.", portal.bridge.Config.Bridge.CommandPrefix, inRoom)
  1363. if sender.IsLoginInProgress() {
  1364. reconnect = "You have a login attempt in progress, please wait."
  1365. }
  1366. msg := format.RenderMarkdown("\u26a0 You are not connected to WhatsApp, so your message was not bridged. "+reconnect, true, false)
  1367. msg.MsgType = event.MsgNotice
  1368. _, err := portal.sendMainIntentMessage(msg)
  1369. if err != nil {
  1370. portal.log.Errorln("Failed to send bridging failure message:", err)
  1371. }
  1372. return true
  1373. }
  1374. return false
  1375. }
  1376. func (portal *Portal) addRelaybotFormat(sender *User, content *event.MessageEventContent) bool {
  1377. member := portal.MainIntent().Member(portal.MXID, sender.MXID)
  1378. if len(member.Displayname) == 0 {
  1379. member.Displayname = string(sender.MXID)
  1380. }
  1381. if content.Format != event.FormatHTML {
  1382. content.FormattedBody = strings.Replace(html.EscapeString(content.Body), "\n", "<br/>", -1)
  1383. content.Format = event.FormatHTML
  1384. }
  1385. data, err := portal.bridge.Config.Bridge.Relaybot.FormatMessage(content, sender.MXID, member)
  1386. if err != nil {
  1387. portal.log.Errorln("Failed to apply relaybot format:", err)
  1388. }
  1389. content.FormattedBody = data
  1390. return true
  1391. }
  1392. func (portal *Portal) convertMatrixMessage(sender *User, evt *event.Event) (*waProto.WebMessageInfo, *User) {
  1393. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  1394. if !ok {
  1395. portal.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  1396. return nil, sender
  1397. }
  1398. ts := uint64(evt.Timestamp / 1000)
  1399. status := waProto.WebMessageInfo_ERROR
  1400. fromMe := true
  1401. info := &waProto.WebMessageInfo{
  1402. Key: &waProto.MessageKey{
  1403. FromMe: &fromMe,
  1404. Id: makeMessageID(),
  1405. RemoteJid: &portal.Key.JID,
  1406. },
  1407. MessageTimestamp: &ts,
  1408. Message: &waProto.Message{},
  1409. Status: &status,
  1410. }
  1411. ctxInfo := &waProto.ContextInfo{}
  1412. replyToID := content.GetReplyTo()
  1413. if len(replyToID) > 0 {
  1414. content.RemoveReplyFallback()
  1415. msg := portal.bridge.DB.Message.GetByMXID(replyToID)
  1416. if msg != nil && msg.Content != nil {
  1417. ctxInfo.StanzaId = &msg.JID
  1418. ctxInfo.Participant = &msg.Sender
  1419. ctxInfo.QuotedMessage = msg.Content
  1420. }
  1421. }
  1422. relaybotFormatted := false
  1423. if sender.NeedsRelaybot(portal) {
  1424. if !portal.HasRelaybot() {
  1425. if sender.HasSession() {
  1426. portal.log.Debugln("Database says", sender.MXID, "not in chat and no relaybot, but trying to send anyway")
  1427. } else {
  1428. portal.log.Debugln("Ignoring message from", sender.MXID, "in chat with no relaybot")
  1429. return nil, sender
  1430. }
  1431. } else {
  1432. relaybotFormatted = portal.addRelaybotFormat(sender, content)
  1433. sender = portal.bridge.Relaybot
  1434. }
  1435. }
  1436. if evt.Type == event.EventSticker {
  1437. content.MsgType = event.MsgImage
  1438. }
  1439. switch content.MsgType {
  1440. case event.MsgText, event.MsgEmote, event.MsgNotice:
  1441. text := content.Body
  1442. if content.Format == event.FormatHTML {
  1443. text = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  1444. }
  1445. if content.MsgType == event.MsgEmote && !relaybotFormatted {
  1446. text = "/me " + text
  1447. }
  1448. ctxInfo.MentionedJid = mentionRegex.FindAllString(text, -1)
  1449. for index, mention := range ctxInfo.MentionedJid {
  1450. ctxInfo.MentionedJid[index] = mention[1:] + whatsappExt.NewUserSuffix
  1451. }
  1452. if ctxInfo.StanzaId != nil || ctxInfo.MentionedJid != nil {
  1453. info.Message.ExtendedTextMessage = &waProto.ExtendedTextMessage{
  1454. Text: &text,
  1455. ContextInfo: ctxInfo,
  1456. }
  1457. } else {
  1458. info.Message.Conversation = &text
  1459. }
  1460. case event.MsgImage:
  1461. media := portal.preprocessMatrixMedia(sender, relaybotFormatted, content, evt.ID, whatsapp.MediaImage)
  1462. if media == nil {
  1463. return nil, sender
  1464. }
  1465. info.Message.ImageMessage = &waProto.ImageMessage{
  1466. Caption: &media.Caption,
  1467. JpegThumbnail: media.Thumbnail,
  1468. Url: &media.URL,
  1469. MediaKey: media.MediaKey,
  1470. Mimetype: &content.GetInfo().MimeType,
  1471. FileEncSha256: media.FileEncSHA256,
  1472. FileSha256: media.FileSHA256,
  1473. FileLength: &media.FileLength,
  1474. }
  1475. case event.MsgVideo:
  1476. media := portal.preprocessMatrixMedia(sender, relaybotFormatted, content, evt.ID, whatsapp.MediaVideo)
  1477. if media == nil {
  1478. return nil, sender
  1479. }
  1480. duration := uint32(content.GetInfo().Duration)
  1481. info.Message.VideoMessage = &waProto.VideoMessage{
  1482. Caption: &media.Caption,
  1483. JpegThumbnail: media.Thumbnail,
  1484. Url: &media.URL,
  1485. MediaKey: media.MediaKey,
  1486. Mimetype: &content.GetInfo().MimeType,
  1487. Seconds: &duration,
  1488. FileEncSha256: media.FileEncSHA256,
  1489. FileSha256: media.FileSHA256,
  1490. FileLength: &media.FileLength,
  1491. }
  1492. case event.MsgAudio:
  1493. media := portal.preprocessMatrixMedia(sender, relaybotFormatted, content, evt.ID, whatsapp.MediaAudio)
  1494. if media == nil {
  1495. return nil, sender
  1496. }
  1497. duration := uint32(content.GetInfo().Duration)
  1498. info.Message.AudioMessage = &waProto.AudioMessage{
  1499. Url: &media.URL,
  1500. MediaKey: media.MediaKey,
  1501. Mimetype: &content.GetInfo().MimeType,
  1502. Seconds: &duration,
  1503. FileEncSha256: media.FileEncSHA256,
  1504. FileSha256: media.FileSHA256,
  1505. FileLength: &media.FileLength,
  1506. }
  1507. case event.MsgFile:
  1508. media := portal.preprocessMatrixMedia(sender, relaybotFormatted, content, evt.ID, whatsapp.MediaDocument)
  1509. if media == nil {
  1510. return nil, sender
  1511. }
  1512. info.Message.DocumentMessage = &waProto.DocumentMessage{
  1513. Url: &media.URL,
  1514. FileName: &content.Body,
  1515. MediaKey: media.MediaKey,
  1516. Mimetype: &content.GetInfo().MimeType,
  1517. FileEncSha256: media.FileEncSHA256,
  1518. FileSha256: media.FileSHA256,
  1519. FileLength: &media.FileLength,
  1520. }
  1521. default:
  1522. portal.log.Debugln("Unhandled Matrix event %s: unknown msgtype %s", evt.ID, content.MsgType)
  1523. return nil, sender
  1524. }
  1525. return info, sender
  1526. }
  1527. func (portal *Portal) wasMessageSent(sender *User, id string) bool {
  1528. _, err := sender.Conn.LoadMessagesAfter(portal.Key.JID, id, true, 0)
  1529. if err != nil {
  1530. if err != whatsapp.ErrServerRespondedWith404 {
  1531. portal.log.Warnfln("Failed to check if message was bridged without response: %v", err)
  1532. }
  1533. return false
  1534. }
  1535. return true
  1536. }
  1537. func (portal *Portal) sendErrorMessage(sendErr error) id.EventID {
  1538. resp, err := portal.sendMainIntentMessage(event.MessageEventContent{
  1539. MsgType: event.MsgNotice,
  1540. Body: fmt.Sprintf("\u26a0 Your message may not have been bridged: %v", sendErr),
  1541. })
  1542. if err != nil {
  1543. portal.log.Warnfln("Failed to send bridging error message:", err)
  1544. return ""
  1545. }
  1546. return resp.EventID
  1547. }
  1548. func (portal *Portal) sendDeliveryReceipt(eventID id.EventID) {
  1549. if portal.bridge.Config.Bridge.DeliveryReceipts {
  1550. err := portal.bridge.Bot.MarkRead(portal.MXID, eventID)
  1551. if err != nil {
  1552. portal.log.Debugfln("Failed to send delivery receipt for %s: %v", eventID, err)
  1553. }
  1554. }
  1555. }
  1556. var timeout = errors.New("message sending timed out")
  1557. func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event) {
  1558. if !portal.HasRelaybot() && (
  1559. (portal.IsPrivateChat() && sender.JID != portal.Key.Receiver) ||
  1560. portal.sendMatrixConnectionError(sender, evt.ID)) {
  1561. return
  1562. }
  1563. portal.log.Debugfln("Received event %s", evt.ID)
  1564. info, sender := portal.convertMatrixMessage(sender, evt)
  1565. if info == nil {
  1566. return
  1567. }
  1568. portal.markHandled(sender, info, evt.ID)
  1569. portal.log.Debugln("Sending event", evt.ID, "to WhatsApp")
  1570. errChan := make(chan error, 1)
  1571. go sender.Conn.SendRaw(info, errChan)
  1572. var err error
  1573. var errorEventID id.EventID
  1574. select {
  1575. case err = <-errChan:
  1576. case <-time.After(time.Duration(portal.bridge.Config.Bridge.ConnectionTimeout) * time.Second):
  1577. if portal.bridge.Config.Bridge.FetchMessageOnTimeout && portal.wasMessageSent(sender, info.Key.GetId()) {
  1578. portal.log.Debugln("Matrix event %s was bridged, but response didn't arrive within timeout")
  1579. portal.sendDeliveryReceipt(evt.ID)
  1580. } else {
  1581. portal.log.Warnfln("Response when bridging Matrix event %s is taking long to arrive", evt.ID)
  1582. errorEventID = portal.sendErrorMessage(timeout)
  1583. }
  1584. err = <-errChan
  1585. }
  1586. if err != nil {
  1587. portal.log.Errorfln("Error handling Matrix event %s: %v", evt.ID, err)
  1588. portal.sendErrorMessage(err)
  1589. } else {
  1590. portal.log.Debugfln("Handled Matrix event %s", evt.ID)
  1591. portal.sendDeliveryReceipt(evt.ID)
  1592. }
  1593. if errorEventID != "" {
  1594. _, err = portal.MainIntent().RedactEvent(portal.MXID, errorEventID)
  1595. if err != nil {
  1596. portal.log.Warnfln("Failed to redact timeout warning message %s: %v", errorEventID, err)
  1597. }
  1598. }
  1599. }
  1600. func (portal *Portal) HandleMatrixRedaction(sender *User, evt *event.Event) {
  1601. if portal.IsPrivateChat() && sender.JID != portal.Key.Receiver {
  1602. return
  1603. }
  1604. msg := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
  1605. if msg == nil || msg.Sender != sender.JID {
  1606. return
  1607. }
  1608. ts := uint64(evt.Timestamp / 1000)
  1609. status := waProto.WebMessageInfo_PENDING
  1610. protoMsgType := waProto.ProtocolMessage_REVOKE
  1611. fromMe := true
  1612. info := &waProto.WebMessageInfo{
  1613. Key: &waProto.MessageKey{
  1614. FromMe: &fromMe,
  1615. Id: makeMessageID(),
  1616. RemoteJid: &portal.Key.JID,
  1617. },
  1618. MessageTimestamp: &ts,
  1619. Message: &waProto.Message{
  1620. ProtocolMessage: &waProto.ProtocolMessage{
  1621. Type: &protoMsgType,
  1622. Key: &waProto.MessageKey{
  1623. FromMe: &fromMe,
  1624. Id: &msg.JID,
  1625. RemoteJid: &portal.Key.JID,
  1626. },
  1627. },
  1628. },
  1629. Status: &status,
  1630. }
  1631. errChan := make(chan error, 1)
  1632. go sender.Conn.SendRaw(info, errChan)
  1633. var err error
  1634. select {
  1635. case err = <-errChan:
  1636. case <-time.After(time.Duration(portal.bridge.Config.Bridge.ConnectionTimeout) * time.Second):
  1637. portal.log.Warnfln("Response when bridging Matrix redaction %s is taking long to arrive", evt.ID)
  1638. err = <-errChan
  1639. }
  1640. if err != nil {
  1641. portal.log.Errorfln("Error handling Matrix redaction %s: %v", evt.ID, err)
  1642. } else {
  1643. portal.log.Debugln("Handled Matrix redaction %s of %s", evt.ID, evt.Redacts)
  1644. portal.sendDeliveryReceipt(evt.ID)
  1645. }
  1646. }
  1647. func (portal *Portal) Delete() {
  1648. portal.Portal.Delete()
  1649. portal.bridge.portalsLock.Lock()
  1650. delete(portal.bridge.portalsByJID, portal.Key)
  1651. if len(portal.MXID) > 0 {
  1652. delete(portal.bridge.portalsByMXID, portal.MXID)
  1653. }
  1654. portal.bridge.portalsLock.Unlock()
  1655. }
  1656. func (portal *Portal) Cleanup(puppetsOnly bool) {
  1657. if len(portal.MXID) == 0 {
  1658. return
  1659. }
  1660. if portal.IsPrivateChat() {
  1661. _, err := portal.MainIntent().LeaveRoom(portal.MXID)
  1662. if err != nil {
  1663. portal.log.Warnln("Failed to leave private chat portal with main intent:", err)
  1664. }
  1665. return
  1666. }
  1667. intent := portal.MainIntent()
  1668. members, err := intent.JoinedMembers(portal.MXID)
  1669. if err != nil {
  1670. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  1671. return
  1672. }
  1673. for member, _ := range members.Joined {
  1674. if member == intent.UserID {
  1675. continue
  1676. }
  1677. puppet := portal.bridge.GetPuppetByMXID(member)
  1678. if puppet != nil {
  1679. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  1680. if err != nil {
  1681. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  1682. }
  1683. } else if !puppetsOnly {
  1684. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  1685. if err != nil {
  1686. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  1687. }
  1688. }
  1689. }
  1690. _, err = intent.LeaveRoom(portal.MXID)
  1691. if err != nil {
  1692. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  1693. }
  1694. }
  1695. func (portal *Portal) HandleMatrixLeave(sender *User) {
  1696. if portal.IsPrivateChat() {
  1697. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  1698. portal.Delete()
  1699. portal.Cleanup(false)
  1700. return
  1701. }
  1702. }
  1703. func (portal *Portal) HandleMatrixKick(sender *User, event *event.Event) {
  1704. // TODO
  1705. }