portal.go 31 KB

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