portal.go 25 KB

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