portal.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. package bridge
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "time"
  7. "github.com/bwmarrin/discordgo"
  8. log "maunium.net/go/maulogger/v2"
  9. "maunium.net/go/mautrix"
  10. "maunium.net/go/mautrix/appservice"
  11. "maunium.net/go/mautrix/event"
  12. "maunium.net/go/mautrix/id"
  13. "gitlab.com/beeper/discord/database"
  14. )
  15. type portalDiscordMessage struct {
  16. msg interface{}
  17. user *User
  18. }
  19. type portalMatrixMessage struct {
  20. evt *event.Event
  21. user *User
  22. }
  23. type Portal struct {
  24. *database.Portal
  25. bridge *Bridge
  26. log log.Logger
  27. roomCreateLock sync.Mutex
  28. discordMessages chan portalDiscordMessage
  29. matrixMessages chan portalMatrixMessage
  30. }
  31. var (
  32. portalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  33. )
  34. func (b *Bridge) loadPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
  35. // If we weren't given a portal we'll attempt to create it if a key was
  36. // provided.
  37. if dbPortal == nil {
  38. if key == nil {
  39. return nil
  40. }
  41. dbPortal = b.db.Portal.New()
  42. dbPortal.Key = *key
  43. dbPortal.Insert()
  44. }
  45. portal := b.NewPortal(dbPortal)
  46. // No need to lock, it is assumed that our callers have already acquired
  47. // the lock.
  48. b.portalsByID[portal.Key] = portal
  49. if portal.MXID != "" {
  50. b.portalsByMXID[portal.MXID] = portal
  51. }
  52. return portal
  53. }
  54. func (b *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  55. b.portalsLock.Lock()
  56. defer b.portalsLock.Unlock()
  57. portal, ok := b.portalsByMXID[mxid]
  58. if !ok {
  59. return b.loadPortal(b.db.Portal.GetByMXID(mxid), nil)
  60. }
  61. return portal
  62. }
  63. func (b *Bridge) GetPortalByID(key database.PortalKey) *Portal {
  64. b.portalsLock.Lock()
  65. defer b.portalsLock.Unlock()
  66. portal, ok := b.portalsByID[key]
  67. if !ok {
  68. return b.loadPortal(b.db.Portal.GetByID(key), &key)
  69. }
  70. return portal
  71. }
  72. func (b *Bridge) GetAllPortals() []*Portal {
  73. return b.dbPortalsToPortals(b.db.Portal.GetAll())
  74. }
  75. func (b *Bridge) GetAllPortalsByID(id string) []*Portal {
  76. return b.dbPortalsToPortals(b.db.Portal.GetAllByID(id))
  77. }
  78. func (b *Bridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  79. b.portalsLock.Lock()
  80. defer b.portalsLock.Unlock()
  81. output := make([]*Portal, len(dbPortals))
  82. for index, dbPortal := range dbPortals {
  83. if dbPortal == nil {
  84. continue
  85. }
  86. portal, ok := b.portalsByID[dbPortal.Key]
  87. if !ok {
  88. portal = b.loadPortal(dbPortal, nil)
  89. }
  90. output[index] = portal
  91. }
  92. return output
  93. }
  94. func (b *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
  95. portal := &Portal{
  96. Portal: dbPortal,
  97. bridge: b,
  98. log: b.log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
  99. discordMessages: make(chan portalDiscordMessage, b.Config.Bridge.PortalMessageBuffer),
  100. matrixMessages: make(chan portalMatrixMessage, b.Config.Bridge.PortalMessageBuffer),
  101. }
  102. go portal.messageLoop()
  103. return portal
  104. }
  105. func (p *Portal) handleMatrixInvite(sender *User, evt *event.Event) {
  106. // Look up an existing puppet or create a new one.
  107. puppet := p.bridge.GetPuppetByMXID(id.UserID(evt.GetStateKey()))
  108. if puppet != nil {
  109. p.log.Infoln("no puppet for %v", sender)
  110. // Open a conversation on the discord side?
  111. }
  112. p.log.Infoln("puppet:", puppet)
  113. }
  114. func (p *Portal) messageLoop() {
  115. for {
  116. select {
  117. case msg := <-p.matrixMessages:
  118. p.handleMatrixMessages(msg)
  119. case msg := <-p.discordMessages:
  120. p.handleDiscordMessages(msg)
  121. }
  122. }
  123. }
  124. func (p *Portal) IsPrivateChat() bool {
  125. return p.Type == discordgo.ChannelTypeDM
  126. }
  127. func (p *Portal) MainIntent() *appservice.IntentAPI {
  128. if p.IsPrivateChat() && p.DMUser != "" {
  129. return p.bridge.GetPuppetByID(p.DMUser).DefaultIntent()
  130. }
  131. return p.bridge.bot
  132. }
  133. func (p *Portal) createMatrixRoom(user *User, channel *discordgo.Channel) error {
  134. p.Type = channel.Type
  135. if p.Type == discordgo.ChannelTypeDM {
  136. p.DMUser = channel.Recipients[0].ID
  137. }
  138. p.roomCreateLock.Lock()
  139. defer p.roomCreateLock.Unlock()
  140. // If we have a matrix id the room should exist so we have nothing to do.
  141. if p.MXID != "" {
  142. return nil
  143. }
  144. intent := p.MainIntent()
  145. if err := intent.EnsureRegistered(); err != nil {
  146. return err
  147. }
  148. // if p.IsPrivateChat() {
  149. p.Name = channel.Name
  150. p.Topic = channel.Topic
  151. // TODO: get avatars figured out
  152. // p.Avatar = puppet.Avatar
  153. // p.AvatarURL = puppet.AvatarURL
  154. // }
  155. p.log.Infoln("Creating Matrix room for channel:", p.Portal.Key.ChannelID)
  156. initialState := []*event.Event{}
  157. creationContent := make(map[string]interface{})
  158. // if !portal.bridge.Config.Bridge.FederateRooms {
  159. creationContent["m.federate"] = false
  160. // }
  161. var invite []id.UserID
  162. if p.IsPrivateChat() {
  163. invite = append(invite, p.bridge.bot.UserID)
  164. }
  165. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  166. Visibility: "private",
  167. Name: p.Name,
  168. Topic: p.Topic,
  169. Preset: "private_chat",
  170. IsDirect: p.IsPrivateChat(),
  171. InitialState: initialState,
  172. CreationContent: creationContent,
  173. })
  174. if err != nil {
  175. return err
  176. }
  177. p.MXID = resp.RoomID
  178. p.Update()
  179. p.bridge.portalsLock.Lock()
  180. p.bridge.portalsByMXID[p.MXID] = p
  181. p.bridge.portalsLock.Unlock()
  182. p.log.Debugln("inviting user", user)
  183. p.ensureUserInvited(user)
  184. if p.IsPrivateChat() {
  185. p.syncParticipants(user, channel.Recipients)
  186. }
  187. firstEventResp, err := p.MainIntent().SendMessageEvent(p.MXID, portalCreationDummyEvent, struct{}{})
  188. if err != nil {
  189. p.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  190. } else {
  191. p.FirstEventID = firstEventResp.EventID
  192. p.Update()
  193. }
  194. return nil
  195. }
  196. func (p *Portal) handleDiscordMessages(msg portalDiscordMessage) {
  197. if p.MXID == "" {
  198. p.log.Debugln("Creating Matrix room from incoming message")
  199. discordMsg := msg.msg.(*discordgo.MessageCreate)
  200. channel, err := msg.user.Session.Channel(discordMsg.ChannelID)
  201. if err != nil {
  202. p.log.Errorln("Failed to find channel for message:", err)
  203. return
  204. }
  205. if err := p.createMatrixRoom(msg.user, channel); err != nil {
  206. p.log.Errorln("Failed to create portal room:", err)
  207. return
  208. }
  209. }
  210. switch msg.msg.(type) {
  211. case *discordgo.MessageCreate:
  212. p.handleDiscordMessageCreate(msg.user, msg.msg.(*discordgo.MessageCreate).Message)
  213. case *discordgo.MessageUpdate:
  214. p.handleDiscordMessagesUpdate(msg.user, msg.msg.(*discordgo.MessageUpdate).Message)
  215. case *discordgo.MessageDelete:
  216. p.handleDiscordMessageDelete(msg.user, msg.msg.(*discordgo.MessageDelete).Message)
  217. case *discordgo.MessageReactionAdd:
  218. p.handleDiscordReaction(msg.user, msg.msg.(*discordgo.MessageReactionAdd).MessageReaction, true)
  219. case *discordgo.MessageReactionRemove:
  220. p.handleDiscordReaction(msg.user, msg.msg.(*discordgo.MessageReactionRemove).MessageReaction, false)
  221. default:
  222. p.log.Warnln("unknown message type")
  223. }
  224. }
  225. func (p *Portal) ensureUserInvited(user *User) bool {
  226. return user.ensureInvited(p.MainIntent(), p.MXID, p.IsPrivateChat())
  227. }
  228. func (p *Portal) markMessageHandled(msg *database.Message, discordID string, mxid id.EventID, authorID string, timestamp time.Time) *database.Message {
  229. if msg == nil {
  230. msg := p.bridge.db.Message.New()
  231. msg.Channel = p.Key
  232. msg.DiscordID = discordID
  233. msg.MatrixID = mxid
  234. msg.AuthorID = authorID
  235. msg.Timestamp = timestamp
  236. msg.Insert()
  237. } else {
  238. msg.UpdateMatrixID(mxid)
  239. }
  240. return msg
  241. }
  242. func (p *Portal) sendMediaFailedMessage(intent *appservice.IntentAPI, bridgeErr error) {
  243. content := &event.MessageEventContent{
  244. Body: fmt.Sprintf("Failed to bridge media: %v", bridgeErr),
  245. MsgType: event.MsgNotice,
  246. }
  247. _, err := intent.SendMessageEvent(p.MXID, event.EventMessage, content)
  248. if err != nil {
  249. p.log.Warnfln("failed to send error message to matrix: %v", err)
  250. }
  251. }
  252. func (p *Portal) handleDiscordAttachment(intent *appservice.IntentAPI, msgID string, attachment *discordgo.MessageAttachment) {
  253. // var captionContent *event.MessageEventContent
  254. // if attachment.Description != "" {
  255. // captionContent = &event.MessageEventContent{
  256. // Body: attachment.Description,
  257. // MsgType: event.MsgNotice,
  258. // }
  259. // }
  260. // p.log.Debugfln("captionContent: %#v", captionContent)
  261. content := &event.MessageEventContent{
  262. Body: attachment.Filename,
  263. Info: &event.FileInfo{
  264. Height: attachment.Height,
  265. MimeType: attachment.ContentType,
  266. Width: attachment.Width,
  267. // This gets overwritten later after the file is uploaded to the homeserver
  268. Size: attachment.Size,
  269. },
  270. }
  271. switch strings.ToLower(strings.Split(attachment.ContentType, "/")[0]) {
  272. case "audio":
  273. content.MsgType = event.MsgAudio
  274. case "image":
  275. content.MsgType = event.MsgImage
  276. case "video":
  277. content.MsgType = event.MsgVideo
  278. default:
  279. content.MsgType = event.MsgFile
  280. }
  281. data, err := p.downloadDiscordAttachment(attachment.URL)
  282. if err != nil {
  283. p.sendMediaFailedMessage(intent, err)
  284. return
  285. }
  286. err = p.uploadMatrixAttachment(intent, data, content)
  287. if err != nil {
  288. p.sendMediaFailedMessage(intent, err)
  289. return
  290. }
  291. resp, err := intent.SendMessageEvent(p.MXID, event.EventMessage, content)
  292. if err != nil {
  293. p.log.Warnfln("failed to send media message to matrix: %v", err)
  294. }
  295. dbAttachment := p.bridge.db.Attachment.New()
  296. dbAttachment.Channel = p.Key
  297. dbAttachment.DiscordMessageID = msgID
  298. dbAttachment.DiscordAttachmentID = attachment.ID
  299. dbAttachment.MatrixEventID = resp.EventID
  300. dbAttachment.Insert()
  301. }
  302. func (p *Portal) handleDiscordMessageCreate(user *User, msg *discordgo.Message) {
  303. if msg.Author != nil && user.ID == msg.Author.ID {
  304. return
  305. }
  306. if p.MXID == "" {
  307. p.log.Warnln("handle message called without a valid portal")
  308. return
  309. }
  310. existing := p.bridge.db.Message.GetByDiscordID(p.Key, msg.ID)
  311. if existing != nil {
  312. p.log.Debugln("not handling duplicate message", msg.ID)
  313. return
  314. }
  315. intent := p.bridge.GetPuppetByID(msg.Author.ID).IntentFor(p)
  316. if msg.Content != "" {
  317. content := &event.MessageEventContent{
  318. Body: msg.Content,
  319. MsgType: event.MsgText,
  320. }
  321. resp, err := intent.SendMessageEvent(p.MXID, event.EventMessage, content)
  322. if err != nil {
  323. p.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  324. return
  325. }
  326. ts, _ := msg.Timestamp.Parse()
  327. p.markMessageHandled(existing, msg.ID, resp.EventID, msg.Author.ID, ts)
  328. }
  329. // now run through any attachments the message has
  330. for _, attachment := range msg.Attachments {
  331. p.handleDiscordAttachment(intent, msg.ID, attachment)
  332. }
  333. }
  334. func (p *Portal) handleDiscordMessagesUpdate(user *User, msg *discordgo.Message) {
  335. if msg.Author != nil && user.ID == msg.Author.ID {
  336. return
  337. }
  338. if p.MXID == "" {
  339. p.log.Warnln("handle message called without a valid portal")
  340. return
  341. }
  342. intent := p.bridge.GetPuppetByID(msg.Author.ID).IntentFor(p)
  343. existing := p.bridge.db.Message.GetByDiscordID(p.Key, msg.ID)
  344. if existing == nil {
  345. // Due to the differences in Discord and Matrix attachment handling,
  346. // existing will return nil if the original message was empty as we
  347. // don't store/save those messages so we can determine when we're
  348. // working against an attachment and do the attachment lookup instead.
  349. // Find all the existing attachments and drop them in a map so we can
  350. // figure out which, if any have been deleted and clean them up on the
  351. // matrix side.
  352. attachmentMap := map[string]*database.Attachment{}
  353. attachments := p.bridge.db.Attachment.GetAllByDiscordMessageID(p.Key, msg.ID)
  354. for _, attachment := range attachments {
  355. attachmentMap[attachment.DiscordAttachmentID] = attachment
  356. }
  357. // Now run through the list of attachments on this message and remove
  358. // them from the map.
  359. for _, attachment := range msg.Attachments {
  360. if _, found := attachmentMap[attachment.ID]; found {
  361. delete(attachmentMap, attachment.ID)
  362. }
  363. }
  364. // Finally run through any attachments still in the map and delete them
  365. // on the matrix side and our database.
  366. for _, attachment := range attachmentMap {
  367. _, err := intent.RedactEvent(p.MXID, attachment.MatrixEventID)
  368. if err != nil {
  369. p.log.Warnfln("Failed to remove attachment %s: %v", attachment.MatrixEventID, err)
  370. }
  371. attachment.Delete()
  372. }
  373. return
  374. }
  375. content := &event.MessageEventContent{
  376. Body: msg.Content,
  377. MsgType: event.MsgText,
  378. }
  379. content.SetEdit(existing.MatrixID)
  380. _, err := intent.SendMessageEvent(p.MXID, event.EventMessage, content)
  381. if err != nil {
  382. p.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  383. return
  384. }
  385. // It appears that matrix updates only work against the original event id
  386. // so updating it to the new one from an edit makes it so you can't update
  387. // it anyways. So we just don't update anything and we can keep updating
  388. // the message.
  389. }
  390. func (p *Portal) handleDiscordMessageDelete(user *User, msg *discordgo.Message) {
  391. // The discord delete message object is pretty empty and doesn't include
  392. // the author so we have to use the DMUser from the portal that was added
  393. // at creation time if we're a DM. We'll might have similar issues when we
  394. // add guild message support, but we'll cross that bridge when we get
  395. // there.
  396. // Find the message that we're working with. This could correctly return
  397. // nil if the message was just one or more attachments.
  398. existing := p.bridge.db.Message.GetByDiscordID(p.Key, msg.ID)
  399. var intent *appservice.IntentAPI
  400. if p.Type == discordgo.ChannelTypeDM {
  401. intent = p.bridge.GetPuppetByID(p.DMUser).IntentFor(p)
  402. } else {
  403. p.log.Errorfln("no guilds yet...")
  404. }
  405. if existing != nil {
  406. _, err := intent.RedactEvent(p.MXID, existing.MatrixID)
  407. if err != nil {
  408. p.log.Warnfln("Failed to remove message %s: %v", existing.MatrixID, err)
  409. }
  410. existing.Delete()
  411. }
  412. // Now delete all of the existing attachments.
  413. attachments := p.bridge.db.Attachment.GetAllByDiscordMessageID(p.Key, msg.ID)
  414. for _, attachment := range attachments {
  415. _, err := intent.RedactEvent(p.MXID, attachment.MatrixEventID)
  416. if err != nil {
  417. p.log.Warnfln("Failed to remove attachment %s: %v", attachment.MatrixEventID, err)
  418. }
  419. attachment.Delete()
  420. }
  421. }
  422. func (p *Portal) syncParticipants(source *User, participants []*discordgo.User) {
  423. for _, participant := range participants {
  424. puppet := p.bridge.GetPuppetByID(participant.ID)
  425. puppet.SyncContact(source)
  426. user := p.bridge.GetUserByID(participant.ID)
  427. if user != nil {
  428. p.ensureUserInvited(user)
  429. }
  430. if user == nil || !puppet.IntentFor(p).IsCustomPuppet {
  431. if err := puppet.IntentFor(p).EnsureJoined(p.MXID); err != nil {
  432. p.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, p.MXID, err)
  433. }
  434. }
  435. }
  436. }
  437. func (p *Portal) handleMatrixMessages(msg portalMatrixMessage) {
  438. switch msg.evt.Type {
  439. case event.EventMessage:
  440. p.handleMatrixMessage(msg.user, msg.evt)
  441. default:
  442. p.log.Debugln("unknown event type", msg.evt.Type)
  443. }
  444. }
  445. func (p *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
  446. if p.IsPrivateChat() && sender.ID != p.Key.Receiver {
  447. return
  448. }
  449. existing := p.bridge.db.Message.GetByMatrixID(p.Key, evt.ID)
  450. if existing != nil {
  451. p.log.Debugln("not handling duplicate message", evt.ID)
  452. return
  453. }
  454. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  455. if !ok {
  456. p.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  457. return
  458. }
  459. if content.RelatesTo != nil && content.RelatesTo.Type == event.RelReplace {
  460. existing := p.bridge.db.Message.GetByMatrixID(p.Key, content.RelatesTo.EventID)
  461. if existing != nil && existing.DiscordID != "" {
  462. // we don't have anything to save for the update message right now
  463. // as we're not tracking edited timestamps.
  464. _, err := sender.Session.ChannelMessageEdit(p.Key.ChannelID,
  465. existing.DiscordID, content.NewContent.Body)
  466. if err != nil {
  467. p.log.Errorln("Failed to update message %s: %v", existing.DiscordID, err)
  468. return
  469. }
  470. }
  471. } else {
  472. msg, err := sender.Session.ChannelMessageSend(p.Key.ChannelID, content.Body)
  473. if err != nil {
  474. p.log.Errorfln("Failed to send message: %v", err)
  475. return
  476. }
  477. dbMsg := p.bridge.db.Message.New()
  478. dbMsg.Channel = p.Key
  479. dbMsg.DiscordID = msg.ID
  480. dbMsg.MatrixID = evt.ID
  481. dbMsg.AuthorID = sender.ID
  482. dbMsg.Timestamp = time.Now()
  483. dbMsg.Insert()
  484. }
  485. }
  486. func (p *Portal) handleMatrixLeave(sender *User) {
  487. if p.IsPrivateChat() {
  488. p.log.Debugln("User left private chat portal, cleaning up and deleting...")
  489. p.delete()
  490. p.cleanup(false)
  491. return
  492. }
  493. // TODO: figure out how to close a dm from the API.
  494. p.cleanupIfEmpty()
  495. }
  496. func (p *Portal) delete() {
  497. p.Portal.Delete()
  498. p.bridge.portalsLock.Lock()
  499. delete(p.bridge.portalsByID, p.Key)
  500. if p.MXID != "" {
  501. delete(p.bridge.portalsByMXID, p.MXID)
  502. }
  503. p.bridge.portalsLock.Unlock()
  504. }
  505. func (p *Portal) cleanupIfEmpty() {
  506. users, err := p.getMatrixUsers()
  507. if err != nil {
  508. p.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  509. return
  510. }
  511. if len(users) == 0 {
  512. p.log.Infoln("Room seems to be empty, cleaning up...")
  513. p.delete()
  514. p.cleanup(false)
  515. }
  516. }
  517. func (p *Portal) cleanup(puppetsOnly bool) {
  518. if p.MXID != "" {
  519. return
  520. }
  521. if p.IsPrivateChat() {
  522. _, err := p.MainIntent().LeaveRoom(p.MXID)
  523. if err != nil {
  524. p.log.Warnln("Failed to leave private chat portal with main intent:", err)
  525. }
  526. return
  527. }
  528. intent := p.MainIntent()
  529. members, err := intent.JoinedMembers(p.MXID)
  530. if err != nil {
  531. p.log.Errorln("Failed to get portal members for cleanup:", err)
  532. return
  533. }
  534. for member := range members.Joined {
  535. if member == intent.UserID {
  536. continue
  537. }
  538. puppet := p.bridge.GetPuppetByMXID(member)
  539. if p != nil {
  540. _, err = puppet.DefaultIntent().LeaveRoom(p.MXID)
  541. if err != nil {
  542. p.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  543. }
  544. } else if !puppetsOnly {
  545. _, err = intent.KickUser(p.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  546. if err != nil {
  547. p.log.Errorln("Error kicking user while cleaning up portal:", err)
  548. }
  549. }
  550. }
  551. _, err = intent.LeaveRoom(p.MXID)
  552. if err != nil {
  553. p.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  554. }
  555. }
  556. func (p *Portal) getMatrixUsers() ([]id.UserID, error) {
  557. members, err := p.MainIntent().JoinedMembers(p.MXID)
  558. if err != nil {
  559. return nil, fmt.Errorf("failed to get member list: %w", err)
  560. }
  561. var users []id.UserID
  562. for userID := range members.Joined {
  563. _, isPuppet := p.bridge.ParsePuppetMXID(userID)
  564. if !isPuppet && userID != p.bridge.bot.UserID {
  565. users = append(users, userID)
  566. }
  567. }
  568. return users, nil
  569. }
  570. func (p *Portal) handleMatrixKick(sender *User, target *Puppet) {
  571. // TODO: need to learn how to make this happen as discordgo proper doesn't
  572. // support group dms and it looks like it's a binary blob.
  573. }
  574. func (p *Portal) handleMatrixReaction(evt *event.Event) {
  575. user := p.bridge.GetUserByMXID(evt.Sender)
  576. if user == nil {
  577. p.log.Errorf("failed to find user for %s", evt.Sender)
  578. return
  579. }
  580. if user.ID != p.Key.Receiver {
  581. return
  582. }
  583. reaction := evt.Content.AsReaction()
  584. if reaction.RelatesTo.Type != event.RelAnnotation {
  585. p.log.Errorfln("Ignoring reaction %s due to unknown m.relates_to data", evt.ID)
  586. return
  587. }
  588. var discordID string
  589. msg := p.bridge.db.Message.GetByMatrixID(p.Key, reaction.RelatesTo.EventID)
  590. // Due to the differences in attachments between Discord and Matrix, if a
  591. // user reacts to a media message on discord our lookup above will fail
  592. // because the relation of matrix media messages to attachments in handled
  593. // in the attachments table instead of messages so we need to check that
  594. // before continuing.
  595. //
  596. // This also leads to interesting problems when a Discord message comes in
  597. // with multiple attachments. A user can react to each one individually on
  598. // Matrix, which will cause us to send it twice. Discord tends to ignore
  599. // this, but if the user removes one of them, discord removes it and now
  600. // they're out of sync. Perhaps we should add a counter to the reactions
  601. // table to keep them in sync and to avoid sending duplicates to Discord.
  602. if msg == nil {
  603. attachment := p.bridge.db.Attachment.GetByMatrixID(p.Key, reaction.RelatesTo.EventID)
  604. discordID = attachment.DiscordMessageID
  605. } else {
  606. if msg.DiscordID == "" {
  607. p.log.Debugf("Message %s has not yet been sent to discord", reaction.RelatesTo.EventID)
  608. return
  609. }
  610. discordID = msg.DiscordID
  611. }
  612. err := user.Session.MessageReactionAdd(p.Key.ChannelID, discordID, reaction.RelatesTo.Key)
  613. if err != nil {
  614. p.log.Debugf("Failed to send reaction %s@%s: %v", p.Key, discordID, err)
  615. return
  616. }
  617. dbReaction := p.bridge.db.Reaction.New()
  618. dbReaction.Channel.ChannelID = p.Key.ChannelID
  619. dbReaction.Channel.Receiver = p.Key.Receiver
  620. dbReaction.MatrixEventID = evt.ID
  621. dbReaction.DiscordMessageID = discordID
  622. dbReaction.AuthorID = user.ID
  623. dbReaction.MatrixName = reaction.RelatesTo.Key
  624. dbReaction.DiscordID = reaction.RelatesTo.Key
  625. dbReaction.Insert()
  626. }
  627. func (p *Portal) handleDiscordReaction(user *User, reaction *discordgo.MessageReaction, add bool) {
  628. if user.ID == reaction.UserID {
  629. return
  630. }
  631. // This is temporary until we add support for custom emoji.
  632. if reaction.Emoji.ID != "" {
  633. p.log.Debugln("ignoring non-unicode reaction")
  634. return
  635. }
  636. emoteID := reaction.Emoji.ID
  637. if reaction.Emoji.Name != "" {
  638. emoteID = reaction.Emoji.Name
  639. }
  640. // Find the message that we're working with.
  641. message := p.bridge.db.Message.GetByDiscordID(p.Key, reaction.MessageID)
  642. if message == nil {
  643. p.log.Debugfln("failed to add reaction to message %s: message not found", reaction.MessageID)
  644. return
  645. }
  646. intent := p.bridge.GetPuppetByID(reaction.UserID).IntentFor(p)
  647. // Lookup an existing reaction
  648. existing := p.bridge.db.Reaction.GetByDiscordID(p.Key, message.DiscordID, emoteID)
  649. if !add {
  650. if existing == nil {
  651. p.log.Debugln("Failed to remove reaction for unknown message", reaction.MessageID)
  652. return
  653. }
  654. _, err := intent.RedactEvent(p.MXID, existing.MatrixEventID)
  655. if err != nil {
  656. p.log.Warnfln("Failed to remove reaction from %s: %v", p.MXID, err)
  657. }
  658. existing.Delete()
  659. return
  660. }
  661. content := event.Content{Parsed: &event.ReactionEventContent{
  662. RelatesTo: event.RelatesTo{
  663. EventID: message.MatrixID,
  664. Type: event.RelAnnotation,
  665. Key: reaction.Emoji.Name,
  666. },
  667. }}
  668. resp, err := intent.Client.SendMessageEvent(p.MXID, event.EventReaction, &content)
  669. if err != nil {
  670. p.log.Errorfln("failed to send reaction from %s: %v", reaction.MessageID, err)
  671. return
  672. }
  673. if existing == nil {
  674. dbReaction := p.bridge.db.Reaction.New()
  675. dbReaction.Channel = p.Key
  676. dbReaction.DiscordMessageID = message.DiscordID
  677. dbReaction.MatrixEventID = resp.EventID
  678. dbReaction.AuthorID = reaction.UserID
  679. dbReaction.MatrixName = reaction.Emoji.Name
  680. dbReaction.DiscordID = emoteID
  681. dbReaction.Insert()
  682. }
  683. }
  684. func (p *Portal) handleMatrixRedaction(evt *event.Event) {
  685. user := p.bridge.GetUserByMXID(evt.Sender)
  686. if user.ID != p.Key.Receiver {
  687. return
  688. }
  689. // First look if we're redacting a message
  690. message := p.bridge.db.Message.GetByMatrixID(p.Key, evt.Redacts)
  691. if message != nil {
  692. if message.DiscordID != "" {
  693. err := user.Session.ChannelMessageDelete(p.Key.ChannelID, message.DiscordID)
  694. if err != nil {
  695. p.log.Debugfln("Failed to delete discord message %s: %v", message.DiscordID, err)
  696. } else {
  697. message.Delete()
  698. }
  699. }
  700. return
  701. }
  702. // Now check if it's a reaction.
  703. reaction := p.bridge.db.Reaction.GetByMatrixID(p.Key, evt.Redacts)
  704. if reaction != nil {
  705. if reaction.DiscordID != "" {
  706. err := user.Session.MessageReactionRemove(p.Key.ChannelID, reaction.DiscordMessageID, reaction.DiscordID, reaction.AuthorID)
  707. if err != nil {
  708. p.log.Debugfln("Failed to delete reaction %s for message %s: %v", reaction.DiscordID, reaction.DiscordMessageID, err)
  709. } else {
  710. reaction.Delete()
  711. }
  712. }
  713. return
  714. }
  715. p.log.Warnfln("Failed to redact %s@%s: no event found", p.Key, evt.Redacts)
  716. }