portal.go 25 KB

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