portal.go 25 KB

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