portal.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. 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.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. intent := p.bridge.GetPuppetByID(msg.Author.ID).IntentFor(p)
  389. existing := p.bridge.db.Message.GetByDiscordID(p.Key, msg.ID)
  390. if existing == nil {
  391. // Due to the differences in Discord and Matrix attachment handling,
  392. // existing will return nil if the original message was empty as we
  393. // don't store/save those messages so we can determine when we're
  394. // working against an attachment and do the attachment lookup instead.
  395. // Find all the existing attachments and drop them in a map so we can
  396. // figure out which, if any have been deleted and clean them up on the
  397. // matrix side.
  398. attachmentMap := map[string]*database.Attachment{}
  399. attachments := p.bridge.db.Attachment.GetAllByDiscordMessageID(p.Key, msg.ID)
  400. for _, attachment := range attachments {
  401. attachmentMap[attachment.DiscordAttachmentID] = attachment
  402. }
  403. // Now run through the list of attachments on this message and remove
  404. // them from the map.
  405. for _, attachment := range msg.Attachments {
  406. if _, found := attachmentMap[attachment.ID]; found {
  407. delete(attachmentMap, attachment.ID)
  408. }
  409. }
  410. // Finally run through any attachments still in the map and delete them
  411. // on the matrix side and our database.
  412. for _, attachment := range attachmentMap {
  413. _, err := intent.RedactEvent(p.MXID, attachment.MatrixEventID)
  414. if err != nil {
  415. p.log.Warnfln("Failed to remove attachment %s: %v", attachment.MatrixEventID, err)
  416. }
  417. attachment.Delete()
  418. }
  419. return
  420. }
  421. content := &event.MessageEventContent{
  422. Body: msg.Content,
  423. MsgType: event.MsgText,
  424. }
  425. content.SetEdit(existing.MatrixID)
  426. resp, err := p.sendMatrixMessage(intent, event.EventMessage, content, nil, time.Now().UTC().UnixMilli())
  427. if err != nil {
  428. p.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  429. return
  430. }
  431. ts, _ := msg.Timestamp.Parse()
  432. p.markMessageHandled(existing, msg.ID, resp.EventID, msg.Author.ID, ts)
  433. }
  434. func (p *Portal) handleDiscordMessageDelete(user *User, msg *discordgo.Message) {
  435. // The discord delete message object is pretty empty and doesn't include
  436. // the author so we have to use the DMUser from the portal that was added
  437. // at creation time if we're a DM. We'll might have similar issues when we
  438. // add guild message support, but we'll cross that bridge when we get
  439. // there.
  440. // Find the message that we're working with. This could correctly return
  441. // nil if the message was just one or more attachments.
  442. existing := p.bridge.db.Message.GetByDiscordID(p.Key, msg.ID)
  443. var intent *appservice.IntentAPI
  444. if p.Type == discordgo.ChannelTypeDM {
  445. intent = p.bridge.GetPuppetByID(p.DMUser).IntentFor(p)
  446. } else {
  447. intent = p.MainIntent()
  448. }
  449. if existing != nil {
  450. _, err := intent.RedactEvent(p.MXID, existing.MatrixID)
  451. if err != nil {
  452. p.log.Warnfln("Failed to remove message %s: %v", existing.MatrixID, err)
  453. }
  454. existing.Delete()
  455. }
  456. // Now delete all of the existing attachments.
  457. attachments := p.bridge.db.Attachment.GetAllByDiscordMessageID(p.Key, msg.ID)
  458. for _, attachment := range attachments {
  459. _, err := intent.RedactEvent(p.MXID, attachment.MatrixEventID)
  460. if err != nil {
  461. p.log.Warnfln("Failed to remove attachment %s: %v", attachment.MatrixEventID, err)
  462. }
  463. attachment.Delete()
  464. }
  465. }
  466. func (p *Portal) syncParticipants(source *User, participants []*discordgo.User) {
  467. for _, participant := range participants {
  468. puppet := p.bridge.GetPuppetByID(participant.ID)
  469. puppet.SyncContact(source)
  470. user := p.bridge.GetUserByID(participant.ID)
  471. if user != nil {
  472. p.ensureUserInvited(user)
  473. }
  474. if user == nil || !puppet.IntentFor(p).IsCustomPuppet {
  475. if err := puppet.IntentFor(p).EnsureJoined(p.MXID); err != nil {
  476. p.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, p.MXID, err)
  477. }
  478. }
  479. }
  480. }
  481. func (portal *Portal) encrypt(content *event.Content, eventType event.Type) (event.Type, error) {
  482. if portal.Encrypted && portal.bridge.crypto != nil {
  483. // TODO maybe the locking should be inside mautrix-go?
  484. portal.encryptLock.Lock()
  485. encrypted, err := portal.bridge.crypto.Encrypt(portal.MXID, eventType, *content)
  486. portal.encryptLock.Unlock()
  487. if err != nil {
  488. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  489. }
  490. eventType = event.EventEncrypted
  491. content.Parsed = encrypted
  492. }
  493. return eventType, nil
  494. }
  495. const doublePuppetKey = "fi.mau.double_puppet_source"
  496. const doublePuppetValue = "mautrix-discord"
  497. func (portal *Portal) sendMatrixMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  498. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  499. if timestamp != 0 && intent.IsCustomPuppet {
  500. if wrappedContent.Raw == nil {
  501. wrappedContent.Raw = map[string]interface{}{}
  502. }
  503. if intent.IsCustomPuppet {
  504. wrappedContent.Raw[doublePuppetKey] = doublePuppetValue
  505. }
  506. }
  507. var err error
  508. eventType, err = portal.encrypt(&wrappedContent, eventType)
  509. if err != nil {
  510. return nil, err
  511. }
  512. if eventType == event.EventEncrypted {
  513. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  514. if intent.IsCustomPuppet {
  515. wrappedContent.Raw = map[string]interface{}{doublePuppetKey: doublePuppetValue}
  516. } else {
  517. wrappedContent.Raw = nil
  518. }
  519. }
  520. _, _ = intent.UserTyping(portal.MXID, false, 0)
  521. if timestamp == 0 {
  522. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  523. } else {
  524. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  525. }
  526. }
  527. func (p *Portal) handleMatrixMessages(msg portalMatrixMessage) {
  528. switch msg.evt.Type {
  529. case event.EventMessage:
  530. p.handleMatrixMessage(msg.user, msg.evt)
  531. default:
  532. p.log.Debugln("unknown event type", msg.evt.Type)
  533. }
  534. }
  535. func (p *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
  536. if p.IsPrivateChat() && sender.ID != p.Key.Receiver {
  537. return
  538. }
  539. existing := p.bridge.db.Message.GetByMatrixID(p.Key, evt.ID)
  540. if existing != nil {
  541. p.log.Debugln("not handling duplicate message", evt.ID)
  542. return
  543. }
  544. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  545. if !ok {
  546. p.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  547. return
  548. }
  549. if content.RelatesTo != nil && content.RelatesTo.Type == event.RelReplace {
  550. existing := p.bridge.db.Message.GetByMatrixID(p.Key, content.RelatesTo.EventID)
  551. if existing != nil && existing.DiscordID != "" {
  552. // we don't have anything to save for the update message right now
  553. // as we're not tracking edited timestamps.
  554. _, err := sender.Session.ChannelMessageEdit(p.Key.ChannelID,
  555. existing.DiscordID, content.NewContent.Body)
  556. if err != nil {
  557. p.log.Errorln("Failed to update message %s: %v", existing.DiscordID, err)
  558. return
  559. }
  560. }
  561. return
  562. }
  563. var msg *discordgo.Message
  564. var err error
  565. switch content.MsgType {
  566. case event.MsgText, event.MsgEmote, event.MsgNotice:
  567. sent := false
  568. if content.RelatesTo != nil && content.RelatesTo.Type == event.RelReply {
  569. existing := p.bridge.db.Message.GetByMatrixID(
  570. p.Key,
  571. content.RelatesTo.EventID,
  572. )
  573. if existing != nil && existing.DiscordID != "" {
  574. msg, err = sender.Session.ChannelMessageSendReply(
  575. p.Key.ChannelID,
  576. content.Body,
  577. &discordgo.MessageReference{
  578. ChannelID: p.Key.ChannelID,
  579. MessageID: existing.DiscordID,
  580. },
  581. )
  582. if err == nil {
  583. sent = true
  584. }
  585. }
  586. }
  587. if !sent {
  588. msg, err = sender.Session.ChannelMessageSend(p.Key.ChannelID, content.Body)
  589. }
  590. case event.MsgAudio, event.MsgFile, event.MsgImage, event.MsgVideo:
  591. data, err := p.downloadMatrixAttachment(evt.ID, content)
  592. if err != nil {
  593. p.log.Errorfln("Failed to download matrix attachment: %v", err)
  594. return
  595. }
  596. msgSend := &discordgo.MessageSend{
  597. Files: []*discordgo.File{
  598. &discordgo.File{
  599. Name: content.Body,
  600. ContentType: content.Info.MimeType,
  601. Reader: bytes.NewReader(data),
  602. },
  603. },
  604. }
  605. msg, err = sender.Session.ChannelMessageSendComplex(p.Key.ChannelID, msgSend)
  606. default:
  607. p.log.Warnln("unknown message type:", content.MsgType)
  608. return
  609. }
  610. if err != nil {
  611. p.log.Errorfln("Failed to send message: %v", err)
  612. return
  613. }
  614. if msg != nil {
  615. dbMsg := p.bridge.db.Message.New()
  616. dbMsg.Channel = p.Key
  617. dbMsg.DiscordID = msg.ID
  618. dbMsg.MatrixID = evt.ID
  619. dbMsg.AuthorID = sender.ID
  620. dbMsg.Timestamp = time.Now()
  621. dbMsg.Insert()
  622. }
  623. }
  624. func (p *Portal) handleMatrixLeave(sender *User) {
  625. p.log.Debugln("User left private chat portal, cleaning up and deleting...")
  626. p.delete()
  627. p.cleanup(false)
  628. // TODO: figure out how to close a dm from the API.
  629. p.cleanupIfEmpty()
  630. }
  631. func (p *Portal) leave(sender *User) {
  632. if p.MXID == "" {
  633. return
  634. }
  635. intent := p.bridge.GetPuppetByID(sender.ID).IntentFor(p)
  636. intent.LeaveRoom(p.MXID)
  637. }
  638. func (p *Portal) delete() {
  639. p.Portal.Delete()
  640. p.bridge.portalsLock.Lock()
  641. delete(p.bridge.portalsByID, p.Key)
  642. if p.MXID != "" {
  643. delete(p.bridge.portalsByMXID, p.MXID)
  644. }
  645. p.bridge.portalsLock.Unlock()
  646. }
  647. func (p *Portal) cleanupIfEmpty() {
  648. users, err := p.getMatrixUsers()
  649. if err != nil {
  650. p.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  651. return
  652. }
  653. if len(users) == 0 {
  654. p.log.Infoln("Room seems to be empty, cleaning up...")
  655. p.delete()
  656. p.cleanup(false)
  657. }
  658. }
  659. func (p *Portal) cleanup(puppetsOnly bool) {
  660. if p.MXID != "" {
  661. return
  662. }
  663. if p.IsPrivateChat() {
  664. _, err := p.MainIntent().LeaveRoom(p.MXID)
  665. if err != nil {
  666. p.log.Warnln("Failed to leave private chat portal with main intent:", err)
  667. }
  668. return
  669. }
  670. intent := p.MainIntent()
  671. members, err := intent.JoinedMembers(p.MXID)
  672. if err != nil {
  673. p.log.Errorln("Failed to get portal members for cleanup:", err)
  674. return
  675. }
  676. for member := range members.Joined {
  677. if member == intent.UserID {
  678. continue
  679. }
  680. puppet := p.bridge.GetPuppetByMXID(member)
  681. if p != nil {
  682. _, err = puppet.DefaultIntent().LeaveRoom(p.MXID)
  683. if err != nil {
  684. p.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  685. }
  686. } else if !puppetsOnly {
  687. _, err = intent.KickUser(p.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  688. if err != nil {
  689. p.log.Errorln("Error kicking user while cleaning up portal:", err)
  690. }
  691. }
  692. }
  693. _, err = intent.LeaveRoom(p.MXID)
  694. if err != nil {
  695. p.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  696. }
  697. }
  698. func (p *Portal) getMatrixUsers() ([]id.UserID, error) {
  699. members, err := p.MainIntent().JoinedMembers(p.MXID)
  700. if err != nil {
  701. return nil, fmt.Errorf("failed to get member list: %w", err)
  702. }
  703. var users []id.UserID
  704. for userID := range members.Joined {
  705. _, isPuppet := p.bridge.ParsePuppetMXID(userID)
  706. if !isPuppet && userID != p.bridge.bot.UserID {
  707. users = append(users, userID)
  708. }
  709. }
  710. return users, nil
  711. }
  712. func (p *Portal) handleMatrixKick(sender *User, target *Puppet) {
  713. // TODO: need to learn how to make this happen as discordgo proper doesn't
  714. // support group dms and it looks like it's a binary blob.
  715. }
  716. func (p *Portal) handleMatrixReaction(evt *event.Event) {
  717. user := p.bridge.GetUserByMXID(evt.Sender)
  718. if user == nil {
  719. p.log.Errorf("failed to find user for %s", evt.Sender)
  720. return
  721. }
  722. if user.ID != p.Key.Receiver {
  723. return
  724. }
  725. reaction := evt.Content.AsReaction()
  726. if reaction.RelatesTo.Type != event.RelAnnotation {
  727. p.log.Errorfln("Ignoring reaction %s due to unknown m.relates_to data", evt.ID)
  728. return
  729. }
  730. var discordID string
  731. msg := p.bridge.db.Message.GetByMatrixID(p.Key, reaction.RelatesTo.EventID)
  732. // Due to the differences in attachments between Discord and Matrix, if a
  733. // user reacts to a media message on discord our lookup above will fail
  734. // because the relation of matrix media messages to attachments in handled
  735. // in the attachments table instead of messages so we need to check that
  736. // before continuing.
  737. //
  738. // This also leads to interesting problems when a Discord message comes in
  739. // with multiple attachments. A user can react to each one individually on
  740. // Matrix, which will cause us to send it twice. Discord tends to ignore
  741. // this, but if the user removes one of them, discord removes it and now
  742. // they're out of sync. Perhaps we should add a counter to the reactions
  743. // table to keep them in sync and to avoid sending duplicates to Discord.
  744. if msg == nil {
  745. attachment := p.bridge.db.Attachment.GetByMatrixID(p.Key, reaction.RelatesTo.EventID)
  746. discordID = attachment.DiscordMessageID
  747. } else {
  748. if msg.DiscordID == "" {
  749. p.log.Debugf("Message %s has not yet been sent to discord", reaction.RelatesTo.EventID)
  750. return
  751. }
  752. discordID = msg.DiscordID
  753. }
  754. // Figure out if this is a custom emoji or not.
  755. emojiID := reaction.RelatesTo.Key
  756. if strings.HasPrefix(emojiID, "mxc://") {
  757. uri, _ := id.ParseContentURI(emojiID)
  758. emoji := p.bridge.db.Emoji.GetByMatrixURL(uri)
  759. if emoji == nil {
  760. p.log.Errorfln("failed to find emoji for %s", emojiID)
  761. return
  762. }
  763. emojiID = emoji.APIName()
  764. }
  765. err := user.Session.MessageReactionAdd(p.Key.ChannelID, discordID, emojiID)
  766. if err != nil {
  767. p.log.Debugf("Failed to send reaction %s id:%s: %v", p.Key, discordID, err)
  768. return
  769. }
  770. dbReaction := p.bridge.db.Reaction.New()
  771. dbReaction.Channel.ChannelID = p.Key.ChannelID
  772. dbReaction.Channel.Receiver = p.Key.Receiver
  773. dbReaction.MatrixEventID = evt.ID
  774. dbReaction.DiscordMessageID = discordID
  775. dbReaction.AuthorID = user.ID
  776. dbReaction.MatrixName = reaction.RelatesTo.Key
  777. dbReaction.DiscordID = emojiID
  778. dbReaction.Insert()
  779. }
  780. func (p *Portal) handleDiscordReaction(user *User, reaction *discordgo.MessageReaction, add bool) {
  781. intent := p.bridge.GetPuppetByID(reaction.UserID).IntentFor(p)
  782. var discordID string
  783. var matrixID string
  784. if reaction.Emoji.ID != "" {
  785. dbEmoji := p.bridge.db.Emoji.GetByDiscordID(reaction.Emoji.ID)
  786. if dbEmoji == nil {
  787. data, mimeType, err := p.downloadDiscordEmoji(reaction.Emoji.ID, reaction.Emoji.Animated)
  788. if err != nil {
  789. p.log.Warnfln("Failed to download emoji %s from discord: %v", reaction.Emoji.ID, err)
  790. return
  791. }
  792. uri, err := p.uploadMatrixEmoji(intent, data, mimeType)
  793. if err != nil {
  794. p.log.Warnfln("Failed to upload discord emoji %s to homeserver: %v", reaction.Emoji.ID, err)
  795. return
  796. }
  797. dbEmoji = p.bridge.db.Emoji.New()
  798. dbEmoji.DiscordID = reaction.Emoji.ID
  799. dbEmoji.DiscordName = reaction.Emoji.Name
  800. dbEmoji.MatrixURL = uri
  801. dbEmoji.Insert()
  802. }
  803. discordID = dbEmoji.DiscordID
  804. matrixID = dbEmoji.MatrixURL.String()
  805. } else {
  806. discordID = reaction.Emoji.Name
  807. matrixID = reaction.Emoji.Name
  808. }
  809. // Find the message that we're working with.
  810. message := p.bridge.db.Message.GetByDiscordID(p.Key, reaction.MessageID)
  811. if message == nil {
  812. p.log.Debugfln("failed to add reaction to message %s: message not found", reaction.MessageID)
  813. return
  814. }
  815. // Lookup an existing reaction
  816. existing := p.bridge.db.Reaction.GetByDiscordID(p.Key, message.DiscordID, discordID)
  817. if !add {
  818. if existing == nil {
  819. p.log.Debugln("Failed to remove reaction for unknown message", reaction.MessageID)
  820. return
  821. }
  822. _, err := intent.RedactEvent(p.MXID, existing.MatrixEventID)
  823. if err != nil {
  824. p.log.Warnfln("Failed to remove reaction from %s: %v", p.MXID, err)
  825. }
  826. existing.Delete()
  827. return
  828. }
  829. content := event.Content{Parsed: &event.ReactionEventContent{
  830. RelatesTo: event.RelatesTo{
  831. EventID: message.MatrixID,
  832. Type: event.RelAnnotation,
  833. Key: matrixID,
  834. },
  835. }}
  836. resp, err := intent.Client.SendMessageEvent(p.MXID, event.EventReaction, &content)
  837. if err != nil {
  838. p.log.Errorfln("failed to send reaction from %s: %v", reaction.MessageID, err)
  839. return
  840. }
  841. if existing == nil {
  842. dbReaction := p.bridge.db.Reaction.New()
  843. dbReaction.Channel = p.Key
  844. dbReaction.DiscordMessageID = message.DiscordID
  845. dbReaction.MatrixEventID = resp.EventID
  846. dbReaction.AuthorID = reaction.UserID
  847. dbReaction.MatrixName = matrixID
  848. dbReaction.DiscordID = discordID
  849. dbReaction.Insert()
  850. }
  851. }
  852. func (p *Portal) handleMatrixRedaction(evt *event.Event) {
  853. user := p.bridge.GetUserByMXID(evt.Sender)
  854. if user.ID != p.Key.Receiver {
  855. return
  856. }
  857. // First look if we're redacting a message
  858. message := p.bridge.db.Message.GetByMatrixID(p.Key, evt.Redacts)
  859. if message != nil {
  860. if message.DiscordID != "" {
  861. err := user.Session.ChannelMessageDelete(p.Key.ChannelID, message.DiscordID)
  862. if err != nil {
  863. p.log.Debugfln("Failed to delete discord message %s: %v", message.DiscordID, err)
  864. } else {
  865. message.Delete()
  866. }
  867. }
  868. return
  869. }
  870. // Now check if it's a reaction.
  871. reaction := p.bridge.db.Reaction.GetByMatrixID(p.Key, evt.Redacts)
  872. if reaction != nil {
  873. if reaction.DiscordID != "" {
  874. err := user.Session.MessageReactionRemove(p.Key.ChannelID, reaction.DiscordMessageID, reaction.DiscordID, reaction.AuthorID)
  875. if err != nil {
  876. p.log.Debugfln("Failed to delete reaction %s for message %s: %v", reaction.DiscordID, reaction.DiscordMessageID, err)
  877. } else {
  878. reaction.Delete()
  879. }
  880. }
  881. return
  882. }
  883. p.log.Warnfln("Failed to redact %s@%s: no event found", p.Key, evt.Redacts)
  884. }
  885. func (p *Portal) update(user *User, channel *discordgo.Channel) {
  886. name, err := p.bridge.Config.Bridge.FormatChannelname(channel, user.Session)
  887. if err != nil {
  888. p.log.Warnln("Failed to format channel name, using existing:", err)
  889. } else {
  890. p.Name = name
  891. }
  892. intent := p.MainIntent()
  893. if p.Name != name {
  894. _, err = intent.SetRoomName(p.MXID, p.Name)
  895. if err != nil {
  896. p.log.Warnln("Failed to update room name:", err)
  897. }
  898. }
  899. if p.Topic != channel.Topic {
  900. p.Topic = channel.Topic
  901. _, err = intent.SetRoomTopic(p.MXID, p.Topic)
  902. if err != nil {
  903. p.log.Warnln("Failed to update room topic:", err)
  904. }
  905. }
  906. if p.Avatar != channel.Icon {
  907. p.Avatar = channel.Icon
  908. var url string
  909. if p.Type == discordgo.ChannelTypeDM {
  910. dmUser, err := user.Session.User(p.DMUser)
  911. if err != nil {
  912. p.log.Warnln("failed to lookup the dmuser", err)
  913. } else {
  914. url = dmUser.AvatarURL("")
  915. }
  916. } else {
  917. url = discordgo.EndpointGroupIcon(channel.ID, channel.Icon)
  918. }
  919. p.AvatarURL = id.ContentURI{}
  920. if url != "" {
  921. uri, err := uploadAvatar(intent, url)
  922. if err != nil {
  923. p.log.Warnf("failed to upload avatar", err)
  924. } else {
  925. p.AvatarURL = uri
  926. }
  927. }
  928. intent.SetRoomAvatar(p.MXID, p.AvatarURL)
  929. }
  930. p.Update()
  931. p.log.Debugln("portal updated")
  932. }