portal.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "maunium.net/go/mautrix/util/variationselector"
  10. "github.com/bwmarrin/discordgo"
  11. log "maunium.net/go/maulogger/v2"
  12. "maunium.net/go/mautrix"
  13. "maunium.net/go/mautrix/appservice"
  14. "maunium.net/go/mautrix/bridge"
  15. "maunium.net/go/mautrix/bridge/bridgeconfig"
  16. "maunium.net/go/mautrix/event"
  17. "maunium.net/go/mautrix/id"
  18. "go.mau.fi/mautrix-discord/database"
  19. )
  20. type portalDiscordMessage struct {
  21. msg interface{}
  22. user *User
  23. thread *Thread
  24. }
  25. type portalMatrixMessage struct {
  26. evt *event.Event
  27. user *User
  28. }
  29. type Portal struct {
  30. *database.Portal
  31. Parent *Portal
  32. Guild *Guild
  33. bridge *DiscordBridge
  34. log log.Logger
  35. roomCreateLock sync.Mutex
  36. encryptLock sync.Mutex
  37. discordMessages chan portalDiscordMessage
  38. matrixMessages chan portalMatrixMessage
  39. }
  40. func (portal *Portal) IsEncrypted() bool {
  41. return portal.Encrypted
  42. }
  43. func (portal *Portal) MarkEncrypted() {
  44. portal.Encrypted = true
  45. portal.Update()
  46. }
  47. func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
  48. if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser /*|| portal.HasRelaybot()*/ {
  49. portal.matrixMessages <- portalMatrixMessage{user: user.(*User), evt: evt}
  50. }
  51. }
  52. var _ bridge.Portal = (*Portal)(nil)
  53. var (
  54. portalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  55. )
  56. func (br *DiscordBridge) loadPortal(dbPortal *database.Portal, key *database.PortalKey, chanType discordgo.ChannelType) *Portal {
  57. if dbPortal == nil {
  58. if key == nil || chanType < 0 {
  59. return nil
  60. }
  61. dbPortal = br.DB.Portal.New()
  62. dbPortal.Key = *key
  63. dbPortal.Type = chanType
  64. dbPortal.Insert()
  65. }
  66. portal := br.NewPortal(dbPortal)
  67. br.portalsByID[portal.Key] = portal
  68. if portal.MXID != "" {
  69. br.portalsByMXID[portal.MXID] = portal
  70. }
  71. if portal.GuildID != "" {
  72. portal.Guild = portal.bridge.GetGuildByID(portal.GuildID, true)
  73. }
  74. if portal.ParentID != "" {
  75. parentKey := database.NewPortalKey(portal.ParentID, "")
  76. var ok bool
  77. portal.Parent, ok = br.portalsByID[parentKey]
  78. if !ok {
  79. portal.Parent = br.loadPortal(br.DB.Portal.GetByID(parentKey), nil, -1)
  80. }
  81. }
  82. return portal
  83. }
  84. func (br *DiscordBridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  85. br.portalsLock.Lock()
  86. defer br.portalsLock.Unlock()
  87. portal, ok := br.portalsByMXID[mxid]
  88. if !ok {
  89. return br.loadPortal(br.DB.Portal.GetByMXID(mxid), nil, -1)
  90. }
  91. return portal
  92. }
  93. func (user *User) GetPortalByMeta(meta *discordgo.Channel) *Portal {
  94. return user.GetPortalByID(meta.ID, meta.Type)
  95. }
  96. func (user *User) GetExistingPortalByID(id string) *Portal {
  97. return user.bridge.GetExistingPortalByID(database.NewPortalKey(id, user.DiscordID))
  98. }
  99. func (user *User) GetPortalByID(id string, chanType discordgo.ChannelType) *Portal {
  100. return user.bridge.GetPortalByID(database.NewPortalKey(id, user.DiscordID), chanType)
  101. }
  102. func (br *DiscordBridge) GetExistingPortalByID(key database.PortalKey) *Portal {
  103. br.portalsLock.Lock()
  104. defer br.portalsLock.Unlock()
  105. portal, ok := br.portalsByID[key]
  106. if !ok {
  107. portal, ok = br.portalsByID[database.NewPortalKey(key.ChannelID, "")]
  108. if !ok {
  109. return br.loadPortal(br.DB.Portal.GetByID(key), nil, -1)
  110. }
  111. }
  112. return portal
  113. }
  114. func (br *DiscordBridge) GetPortalByID(key database.PortalKey, chanType discordgo.ChannelType) *Portal {
  115. br.portalsLock.Lock()
  116. defer br.portalsLock.Unlock()
  117. if chanType != discordgo.ChannelTypeDM {
  118. key.Receiver = ""
  119. }
  120. portal, ok := br.portalsByID[key]
  121. if !ok {
  122. return br.loadPortal(br.DB.Portal.GetByID(key), &key, chanType)
  123. }
  124. return portal
  125. }
  126. func (br *DiscordBridge) GetAllPortals() []*Portal {
  127. return br.dbPortalsToPortals(br.DB.Portal.GetAll())
  128. }
  129. func (br *DiscordBridge) GetDMPortalsWith(otherUserID string) []*Portal {
  130. return br.dbPortalsToPortals(br.DB.Portal.FindPrivateChatsWith(otherUserID))
  131. }
  132. func (br *DiscordBridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  133. br.portalsLock.Lock()
  134. defer br.portalsLock.Unlock()
  135. output := make([]*Portal, len(dbPortals))
  136. for index, dbPortal := range dbPortals {
  137. if dbPortal == nil {
  138. continue
  139. }
  140. portal, ok := br.portalsByID[dbPortal.Key]
  141. if !ok {
  142. portal = br.loadPortal(dbPortal, nil, -1)
  143. }
  144. output[index] = portal
  145. }
  146. return output
  147. }
  148. func (br *DiscordBridge) NewPortal(dbPortal *database.Portal) *Portal {
  149. portal := &Portal{
  150. Portal: dbPortal,
  151. bridge: br,
  152. log: br.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
  153. discordMessages: make(chan portalDiscordMessage, br.Config.Bridge.PortalMessageBuffer),
  154. matrixMessages: make(chan portalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
  155. }
  156. go portal.messageLoop()
  157. return portal
  158. }
  159. func (portal *Portal) messageLoop() {
  160. for {
  161. select {
  162. case msg := <-portal.matrixMessages:
  163. portal.handleMatrixMessages(msg)
  164. case msg := <-portal.discordMessages:
  165. portal.handleDiscordMessages(msg)
  166. }
  167. }
  168. }
  169. func (portal *Portal) IsPrivateChat() bool {
  170. return portal.Type == discordgo.ChannelTypeDM
  171. }
  172. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  173. if portal.IsPrivateChat() && portal.OtherUserID != "" {
  174. return portal.bridge.GetPuppetByID(portal.OtherUserID).DefaultIntent()
  175. }
  176. return portal.bridge.Bot
  177. }
  178. func (portal *Portal) getBridgeInfo() (string, event.BridgeEventContent) {
  179. bridgeInfo := event.BridgeEventContent{
  180. BridgeBot: portal.bridge.Bot.UserID,
  181. Creator: portal.MainIntent().UserID,
  182. Protocol: event.BridgeInfoSection{
  183. ID: "discord",
  184. DisplayName: "Discord",
  185. AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
  186. ExternalURL: "https://discord.com/",
  187. },
  188. Channel: event.BridgeInfoSection{
  189. ID: portal.Key.ChannelID,
  190. DisplayName: portal.Name,
  191. },
  192. }
  193. var bridgeInfoStateKey string
  194. if portal.GuildID == "" {
  195. bridgeInfoStateKey = fmt.Sprintf("fi.mau.discord://discord/dm/%s", portal.Key.ChannelID)
  196. } else {
  197. bridgeInfo.Network = &event.BridgeInfoSection{
  198. ID: portal.GuildID,
  199. }
  200. if portal.Guild != nil {
  201. bridgeInfo.Network.DisplayName = portal.Guild.Name
  202. bridgeInfo.Network.AvatarURL = portal.Guild.AvatarURL.CUString()
  203. // TODO is it possible to find the URL?
  204. }
  205. bridgeInfoStateKey = fmt.Sprintf("fi.mau.discord://discord/%s/%s", portal.GuildID, portal.Key.ChannelID)
  206. }
  207. return bridgeInfoStateKey, bridgeInfo
  208. }
  209. func (portal *Portal) UpdateBridgeInfo() {
  210. if len(portal.MXID) == 0 {
  211. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  212. return
  213. }
  214. portal.log.Debugln("Updating bridge info...")
  215. stateKey, content := portal.getBridgeInfo()
  216. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
  217. if err != nil {
  218. portal.log.Warnln("Failed to update m.bridge:", err)
  219. }
  220. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  221. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
  222. if err != nil {
  223. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  224. }
  225. }
  226. func (portal *Portal) CreateMatrixRoom(user *User, channel *discordgo.Channel) error {
  227. portal.roomCreateLock.Lock()
  228. defer portal.roomCreateLock.Unlock()
  229. if portal.MXID != "" {
  230. return nil
  231. }
  232. portal.log.Infoln("Creating Matrix room for channel")
  233. channel = portal.UpdateInfo(user, channel)
  234. intent := portal.MainIntent()
  235. if err := intent.EnsureRegistered(); err != nil {
  236. return err
  237. }
  238. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  239. initialState := []*event.Event{{
  240. Type: event.StateBridge,
  241. Content: event.Content{Parsed: bridgeInfo},
  242. StateKey: &bridgeInfoStateKey,
  243. }, {
  244. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  245. Type: event.StateHalfShotBridge,
  246. Content: event.Content{Parsed: bridgeInfo},
  247. StateKey: &bridgeInfoStateKey,
  248. }}
  249. if !portal.AvatarURL.IsEmpty() {
  250. initialState = append(initialState, &event.Event{
  251. Type: event.StateRoomAvatar,
  252. Content: event.Content{Parsed: &event.RoomAvatarEventContent{
  253. URL: portal.AvatarURL,
  254. }},
  255. })
  256. }
  257. creationContent := make(map[string]interface{})
  258. if portal.Type == discordgo.ChannelTypeGuildCategory {
  259. creationContent["type"] = event.RoomTypeSpace
  260. }
  261. if !portal.bridge.Config.Bridge.FederateRooms {
  262. creationContent["m.federate"] = false
  263. }
  264. spaceID := portal.ExpectedSpaceID()
  265. if spaceID != "" {
  266. spaceIDStr := spaceID.String()
  267. initialState = append(initialState, &event.Event{
  268. Type: event.StateSpaceParent,
  269. StateKey: &spaceIDStr,
  270. Content: event.Content{Parsed: &event.SpaceParentEventContent{
  271. Via: []string{portal.bridge.AS.HomeserverDomain},
  272. Canonical: true,
  273. }},
  274. })
  275. }
  276. if portal.Guild != nil && portal.Guild.MXID != "" {
  277. // TODO don't do this for private channels in guilds
  278. initialState = append(initialState, &event.Event{
  279. Type: event.StateJoinRules,
  280. Content: event.Content{Parsed: &event.JoinRulesEventContent{
  281. JoinRule: event.JoinRuleRestricted,
  282. Allow: []event.JoinRuleAllow{{
  283. RoomID: spaceID,
  284. Type: event.JoinRuleAllowRoomMembership,
  285. }},
  286. }},
  287. })
  288. }
  289. // TODO set restricted join rule based on guild
  290. var invite []id.UserID
  291. if portal.bridge.Config.Bridge.Encryption.Default {
  292. initialState = append(initialState, &event.Event{
  293. Type: event.StateEncryption,
  294. Content: event.Content{
  295. Parsed: event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1},
  296. },
  297. })
  298. portal.Encrypted = true
  299. if portal.IsPrivateChat() {
  300. invite = append(invite, portal.bridge.Bot.UserID)
  301. }
  302. }
  303. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  304. Visibility: "private",
  305. Name: portal.Name,
  306. Topic: portal.Topic,
  307. Invite: invite,
  308. Preset: "private_chat",
  309. IsDirect: portal.IsPrivateChat(),
  310. InitialState: initialState,
  311. CreationContent: creationContent,
  312. })
  313. if err != nil {
  314. portal.log.Warnln("Failed to create room:", err)
  315. return err
  316. }
  317. portal.NameSet = true
  318. portal.TopicSet = true
  319. portal.AvatarSet = !portal.AvatarURL.IsEmpty()
  320. portal.MXID = resp.RoomID
  321. portal.bridge.portalsLock.Lock()
  322. portal.bridge.portalsByMXID[portal.MXID] = portal
  323. portal.bridge.portalsLock.Unlock()
  324. portal.Update()
  325. portal.log.Infoln("Matrix room created:", portal.MXID)
  326. portal.updateSpace()
  327. portal.ensureUserInvited(user)
  328. user.syncChatDoublePuppetDetails(portal, true)
  329. portal.syncParticipants(user, channel.Recipients)
  330. if portal.IsPrivateChat() {
  331. puppet := user.bridge.GetPuppetByID(portal.Key.Receiver)
  332. chats := map[id.UserID][]id.RoomID{puppet.MXID: {portal.MXID}}
  333. user.updateDirectChats(chats)
  334. }
  335. firstEventResp, err := portal.MainIntent().SendMessageEvent(portal.MXID, portalCreationDummyEvent, struct{}{})
  336. if err != nil {
  337. portal.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  338. } else {
  339. portal.FirstEventID = firstEventResp.EventID
  340. portal.Update()
  341. }
  342. return nil
  343. }
  344. func (portal *Portal) handleDiscordMessages(msg portalDiscordMessage) {
  345. if portal.MXID == "" {
  346. _, ok := msg.msg.(*discordgo.MessageCreate)
  347. if !ok {
  348. portal.log.Warnln("Can't create Matrix room from non new message event")
  349. return
  350. }
  351. portal.log.Debugln("Creating Matrix room from incoming message")
  352. if err := portal.CreateMatrixRoom(msg.user, nil); err != nil {
  353. portal.log.Errorln("Failed to create portal room:", err)
  354. return
  355. }
  356. }
  357. switch convertedMsg := msg.msg.(type) {
  358. case *discordgo.MessageCreate:
  359. portal.handleDiscordMessageCreate(msg.user, convertedMsg.Message, msg.thread)
  360. case *discordgo.MessageUpdate:
  361. portal.handleDiscordMessageUpdate(msg.user, convertedMsg.Message)
  362. case *discordgo.MessageDelete:
  363. portal.handleDiscordMessageDelete(msg.user, convertedMsg.Message)
  364. case *discordgo.MessageReactionAdd:
  365. portal.handleDiscordReaction(msg.user, convertedMsg.MessageReaction, true, msg.thread)
  366. case *discordgo.MessageReactionRemove:
  367. portal.handleDiscordReaction(msg.user, convertedMsg.MessageReaction, false, msg.thread)
  368. default:
  369. portal.log.Warnln("unknown message type")
  370. }
  371. }
  372. func (portal *Portal) ensureUserInvited(user *User) bool {
  373. return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
  374. }
  375. func (portal *Portal) markMessageHandled(discordID string, mxid id.EventID, authorID string, timestamp time.Time, threadID string) *database.Message {
  376. msg := portal.bridge.DB.Message.New()
  377. msg.Channel = portal.Key
  378. msg.DiscordID = discordID
  379. msg.MXID = mxid
  380. msg.SenderID = authorID
  381. msg.Timestamp = timestamp
  382. msg.ThreadID = threadID
  383. msg.Insert()
  384. return msg
  385. }
  386. func (portal *Portal) sendMediaFailedMessage(intent *appservice.IntentAPI, bridgeErr error) {
  387. content := &event.MessageEventContent{
  388. Body: fmt.Sprintf("Failed to bridge media: %v", bridgeErr),
  389. MsgType: event.MsgNotice,
  390. }
  391. _, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, time.Now().UTC().UnixMilli())
  392. if err != nil {
  393. portal.log.Warnfln("failed to send error message to matrix: %v", err)
  394. }
  395. }
  396. func (portal *Portal) handleDiscordAttachment(intent *appservice.IntentAPI, msgID string, attachment *discordgo.MessageAttachment, ts time.Time, threadRelation *event.RelatesTo, threadID string) {
  397. // var captionContent *event.MessageEventContent
  398. // if attachment.Description != "" {
  399. // captionContent = &event.MessageEventContent{
  400. // Body: attachment.Description,
  401. // MsgType: event.MsgNotice,
  402. // }
  403. // }
  404. // portal.Log.Debugfln("captionContent: %#v", captionContent)
  405. content := &event.MessageEventContent{
  406. Body: attachment.Filename,
  407. Info: &event.FileInfo{
  408. Height: attachment.Height,
  409. MimeType: attachment.ContentType,
  410. Width: attachment.Width,
  411. // This gets overwritten later after the file is uploaded to the homeserver
  412. Size: attachment.Size,
  413. },
  414. RelatesTo: threadRelation,
  415. }
  416. switch strings.ToLower(strings.Split(attachment.ContentType, "/")[0]) {
  417. case "audio":
  418. content.MsgType = event.MsgAudio
  419. case "image":
  420. content.MsgType = event.MsgImage
  421. case "video":
  422. content.MsgType = event.MsgVideo
  423. default:
  424. content.MsgType = event.MsgFile
  425. }
  426. data, err := portal.downloadDiscordAttachment(attachment.URL)
  427. if err != nil {
  428. portal.sendMediaFailedMessage(intent, err)
  429. return
  430. }
  431. err = portal.uploadMatrixAttachment(intent, data, content)
  432. if err != nil {
  433. portal.sendMediaFailedMessage(intent, err)
  434. return
  435. }
  436. resp, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, ts.UnixMilli())
  437. if err != nil {
  438. portal.log.Warnfln("failed to send media message to matrix: %v", err)
  439. }
  440. dbAttachment := portal.bridge.DB.Attachment.New()
  441. dbAttachment.Channel = portal.Key
  442. dbAttachment.MessageID = msgID
  443. dbAttachment.ID = attachment.ID
  444. dbAttachment.MXID = resp.EventID
  445. dbAttachment.ThreadID = threadID
  446. dbAttachment.Insert()
  447. // Update the fallback reply event for the next attachment
  448. if threadRelation != nil {
  449. threadRelation.InReplyTo.EventID = resp.EventID
  450. }
  451. }
  452. func (portal *Portal) handleDiscordMessageCreate(user *User, msg *discordgo.Message, thread *Thread) {
  453. if portal.MXID == "" {
  454. portal.log.Warnln("handle message called without a valid portal")
  455. return
  456. }
  457. // Handle room name changes
  458. if msg.Type == discordgo.MessageTypeChannelNameChange {
  459. //channel, err := user.Session.Channel(msg.ChannelID)
  460. //if err != nil {
  461. // portal.log.Errorf("Failed to find the channel for portal %s", portal.Key)
  462. // return
  463. //}
  464. //
  465. //name, err := portal.bridge.Config.Bridge.FormatChannelname(channel, user.Session)
  466. //if err != nil {
  467. // portal.log.Errorf("Failed to format name for portal %s", portal.Key)
  468. // return
  469. //}
  470. //
  471. //portal.Name = name
  472. //portal.Update()
  473. //
  474. //portal.MainIntent().SetRoomName(portal.MXID, name)
  475. return
  476. }
  477. // Handle normal message
  478. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  479. if existing != nil {
  480. portal.log.Debugln("Dropping duplicate message", msg.ID)
  481. return
  482. }
  483. portal.log.Debugfln("Starting handling of %s by %s", msg.ID, msg.Author.ID)
  484. puppet := portal.bridge.GetPuppetByID(msg.Author.ID)
  485. puppet.UpdateInfo(user, msg.Author)
  486. intent := puppet.IntentFor(portal)
  487. var threadRelation *event.RelatesTo
  488. var threadID string
  489. if thread != nil {
  490. threadID = thread.ID
  491. lastEventID := thread.RootMXID
  492. lastInThread := portal.bridge.DB.Message.GetLastInThread(portal.Key, thread.ID)
  493. if lastInThread != nil {
  494. lastEventID = lastInThread.MXID
  495. }
  496. threadRelation = (&event.RelatesTo{}).SetThread(thread.RootMXID, lastEventID)
  497. }
  498. ts, _ := discordgo.SnowflakeTimestamp(msg.ID)
  499. if msg.Content != "" {
  500. content := &event.MessageEventContent{
  501. Body: msg.Content,
  502. MsgType: event.MsgText,
  503. RelatesTo: threadRelation.Copy(),
  504. }
  505. if msg.MessageReference != nil {
  506. //key := database.PortalKey{msg.MessageReference.ChannelID, user.ID}
  507. replyTo := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.MessageReference.MessageID)
  508. if replyTo != nil {
  509. if content.RelatesTo == nil {
  510. content.RelatesTo = &event.RelatesTo{}
  511. }
  512. content.RelatesTo.SetReplyTo(replyTo.MXID)
  513. }
  514. }
  515. resp, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, ts.UnixMilli())
  516. if err != nil {
  517. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  518. return
  519. }
  520. portal.markMessageHandled(msg.ID, resp.EventID, msg.Author.ID, ts, threadID)
  521. // Update the fallback reply event for attachments
  522. if threadRelation != nil {
  523. threadRelation.InReplyTo.EventID = resp.EventID
  524. }
  525. }
  526. for _, attachment := range msg.Attachments {
  527. portal.handleDiscordAttachment(intent, msg.ID, attachment, ts, threadRelation, threadID)
  528. }
  529. }
  530. func (portal *Portal) handleDiscordMessageUpdate(user *User, msg *discordgo.Message) {
  531. if portal.MXID == "" {
  532. portal.log.Warnln("handle message called without a valid portal")
  533. return
  534. }
  535. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  536. if existing == nil {
  537. portal.log.Warnfln("Dropping update of unknown message %s", msg.ID)
  538. return
  539. }
  540. if msg.Flags == discordgo.MessageFlagsHasThread {
  541. portal.bridge.GetThreadByID(msg.ID, existing)
  542. portal.log.Debugfln("Marked %s as a thread root", msg.ID)
  543. // TODO make autojoining optional
  544. err := user.Session.ThreadJoinWithLocation(msg.ID, discordgo.ThreadJoinLocationContextMenu)
  545. if err != nil {
  546. user.log.Warnfln("Error autojoining thread %s@%s: %v", msg.ChannelID, portal.Key.ChannelID, err)
  547. }
  548. }
  549. // There's a few scenarios where the author is nil but I haven't figured
  550. // them all out yet.
  551. if msg.Author == nil {
  552. // If the server has to lookup opengraph previews it'll send the
  553. // message through without the preview and then add the preview later
  554. // via a message update. However, when it does this there is no author
  555. // as it's just the server, so for the moment we'll ignore this to
  556. // avoid a crash.
  557. if len(msg.Embeds) > 0 {
  558. portal.log.Debugln("ignoring update for opengraph attachment")
  559. return
  560. }
  561. portal.log.Errorfln("author is nil: %#v", msg)
  562. return
  563. }
  564. intent := portal.bridge.GetPuppetByID(msg.Author.ID).IntentFor(portal)
  565. if existing == nil {
  566. // Due to the differences in Discord and Matrix attachment handling,
  567. // existing will return nil if the original message was empty as we
  568. // don't store/save those messages so we can determine when we're
  569. // working against an attachment and do the attachment lookup instead.
  570. // Find all the existing attachments and drop them in a map so we can
  571. // figure out which, if any have been deleted and clean them up on the
  572. // matrix side.
  573. attachmentMap := map[string]*database.Attachment{}
  574. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  575. for _, attachment := range attachments {
  576. attachmentMap[attachment.ID] = attachment
  577. }
  578. // Now run through the list of attachments on this message and remove
  579. // them from the map.
  580. for _, attachment := range msg.Attachments {
  581. if _, found := attachmentMap[attachment.ID]; found {
  582. delete(attachmentMap, attachment.ID)
  583. }
  584. }
  585. // Finally run through any attachments still in the map and delete them
  586. // on the matrix side and our database.
  587. for _, attachment := range attachmentMap {
  588. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  589. if err != nil {
  590. portal.log.Warnfln("Failed to remove attachment %s: %v", attachment.MXID, err)
  591. }
  592. attachment.Delete()
  593. }
  594. return
  595. }
  596. content := &event.MessageEventContent{
  597. Body: msg.Content,
  598. MsgType: event.MsgText,
  599. }
  600. content.SetEdit(existing.MXID)
  601. _, err := portal.sendMatrixMessage(intent, event.EventMessage, content, nil, time.Now().UTC().UnixMilli())
  602. if err != nil {
  603. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  604. return
  605. }
  606. //ts, _ := msg.Timestamp.Parse()
  607. //portal.markMessageHandled(existing, msg.ID, resp.EventID, msg.Author.ID, ts)
  608. }
  609. func (portal *Portal) handleDiscordMessageDelete(user *User, msg *discordgo.Message) {
  610. // The discord delete message object is pretty empty and doesn't include
  611. // the author so we have to use the DMUser from the portal that was added
  612. // at creation time if we're a DM. We'll might have similar issues when we
  613. // add guild message support, but we'll cross that bridge when we get
  614. // there.
  615. // Find the message that we're working with. This could correctly return
  616. // nil if the message was just one or more attachments.
  617. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  618. intent := portal.MainIntent()
  619. if existing != nil {
  620. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  621. for _, attachment := range attachments {
  622. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  623. if err != nil {
  624. portal.log.Warnfln("Failed to redact attachment %s: %v", attachment.MXID, err)
  625. }
  626. attachment.Delete()
  627. }
  628. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  629. if err != nil {
  630. portal.log.Warnfln("Failed to redact message %s: %v", existing.MXID, err)
  631. }
  632. existing.Delete()
  633. }
  634. }
  635. func (portal *Portal) syncParticipants(source *User, participants []*discordgo.User) {
  636. for _, participant := range participants {
  637. puppet := portal.bridge.GetPuppetByID(participant.ID)
  638. puppet.UpdateInfo(source, participant)
  639. user := portal.bridge.GetUserByID(participant.ID)
  640. if user != nil {
  641. portal.ensureUserInvited(user)
  642. }
  643. if user == nil || !puppet.IntentFor(portal).IsCustomPuppet {
  644. if err := puppet.IntentFor(portal).EnsureJoined(portal.MXID); err != nil {
  645. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, portal.MXID, err)
  646. }
  647. }
  648. }
  649. }
  650. func (portal *Portal) encrypt(content *event.Content, eventType event.Type) (event.Type, error) {
  651. if portal.Encrypted && portal.bridge.Crypto != nil {
  652. // TODO maybe the locking should be inside mautrix-go?
  653. portal.encryptLock.Lock()
  654. encrypted, err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, *content)
  655. portal.encryptLock.Unlock()
  656. if err != nil {
  657. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  658. }
  659. eventType = event.EventEncrypted
  660. content.Parsed = encrypted
  661. }
  662. return eventType, nil
  663. }
  664. const doublePuppetValue = "mautrix-discord"
  665. func (portal *Portal) sendMatrixMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  666. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  667. if timestamp != 0 && intent.IsCustomPuppet {
  668. if wrappedContent.Raw == nil {
  669. wrappedContent.Raw = map[string]interface{}{}
  670. }
  671. if intent.IsCustomPuppet {
  672. wrappedContent.Raw[bridge.DoublePuppetKey] = doublePuppetValue
  673. }
  674. }
  675. var err error
  676. eventType, err = portal.encrypt(&wrappedContent, eventType)
  677. if err != nil {
  678. return nil, err
  679. }
  680. if eventType == event.EventEncrypted {
  681. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  682. if intent.IsCustomPuppet {
  683. wrappedContent.Raw = map[string]interface{}{bridge.DoublePuppetKey: doublePuppetValue}
  684. } else {
  685. wrappedContent.Raw = nil
  686. }
  687. }
  688. _, _ = intent.UserTyping(portal.MXID, false, 0)
  689. if timestamp == 0 {
  690. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  691. } else {
  692. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  693. }
  694. }
  695. func (portal *Portal) handleMatrixMessages(msg portalMatrixMessage) {
  696. switch msg.evt.Type {
  697. case event.EventMessage:
  698. portal.handleMatrixMessage(msg.user, msg.evt)
  699. case event.EventRedaction:
  700. portal.handleMatrixRedaction(msg.user, msg.evt)
  701. case event.EventReaction:
  702. portal.handleMatrixReaction(msg.user, msg.evt)
  703. default:
  704. portal.log.Debugln("unknown event type", msg.evt.Type)
  705. }
  706. }
  707. const discordEpoch = 1420070400000
  708. func generateNonce() string {
  709. snowflake := (time.Now().UnixMilli() - discordEpoch) << 22
  710. // Nonce snowflakes don't have internal IDs or increments
  711. return strconv.FormatInt(snowflake, 10)
  712. }
  713. func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
  714. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  715. return
  716. }
  717. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  718. if !ok {
  719. portal.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  720. return
  721. }
  722. channelID := portal.Key.ChannelID
  723. var threadID string
  724. if editMXID := content.GetRelatesTo().GetReplaceID(); editMXID != "" && content.NewContent != nil {
  725. edits := portal.bridge.DB.Message.GetByMXID(portal.Key, editMXID)
  726. if edits != nil {
  727. // we don't have anything to save for the update message right now
  728. // as we're not tracking edited timestamps.
  729. _, err := sender.Session.ChannelMessageEdit(edits.DiscordProtoChannelID(), edits.DiscordID, content.NewContent.Body)
  730. if err != nil {
  731. portal.log.Errorln("Failed to update message %s: %v", edits.DiscordID, err)
  732. }
  733. }
  734. return
  735. } else if threadRoot := content.GetRelatesTo().GetThreadParent(); threadRoot != "" {
  736. existingThread := portal.bridge.DB.Thread.GetByMatrixRootMsg(threadRoot)
  737. if existingThread != nil {
  738. channelID = existingThread.ID
  739. threadID = existingThread.ID
  740. } else {
  741. // TODO create new thread
  742. }
  743. }
  744. var sendReq discordgo.MessageSend
  745. switch content.MsgType {
  746. case event.MsgText, event.MsgEmote, event.MsgNotice:
  747. if replyToMXID := content.GetReplyTo(); replyToMXID != "" {
  748. replyTo := portal.bridge.DB.Message.GetByMXID(portal.Key, replyToMXID)
  749. if replyTo != nil && replyTo.ThreadID == threadID {
  750. sendReq.Reference = &discordgo.MessageReference{
  751. ChannelID: channelID,
  752. MessageID: replyTo.DiscordID,
  753. }
  754. }
  755. }
  756. sendReq.Content = content.Body
  757. case event.MsgAudio, event.MsgFile, event.MsgImage, event.MsgVideo:
  758. data, err := portal.downloadMatrixAttachment(evt.ID, content)
  759. if err != nil {
  760. portal.log.Errorfln("Failed to download matrix attachment: %v", err)
  761. return
  762. }
  763. sendReq.Files = []*discordgo.File{{
  764. Name: content.Body,
  765. ContentType: content.Info.MimeType,
  766. Reader: bytes.NewReader(data),
  767. }}
  768. default:
  769. portal.log.Warnln("Unknown message type", content.MsgType)
  770. return
  771. }
  772. sendReq.Nonce = generateNonce()
  773. msg, err := sender.Session.ChannelMessageSendComplex(channelID, &sendReq)
  774. if err != nil {
  775. portal.log.Errorfln("Failed to send message: %v", err)
  776. return
  777. }
  778. if msg != nil {
  779. dbMsg := portal.bridge.DB.Message.New()
  780. dbMsg.Channel = portal.Key
  781. dbMsg.DiscordID = msg.ID
  782. dbMsg.MXID = evt.ID
  783. dbMsg.SenderID = sender.DiscordID
  784. dbMsg.Timestamp, _ = discordgo.SnowflakeTimestamp(msg.ID)
  785. dbMsg.ThreadID = threadID
  786. dbMsg.Insert()
  787. }
  788. }
  789. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  790. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  791. portal.Delete()
  792. portal.cleanup(false)
  793. // TODO: figure out how to close a dm from the API.
  794. portal.cleanupIfEmpty()
  795. }
  796. func (portal *Portal) leave(sender *User) {
  797. if portal.MXID == "" {
  798. return
  799. }
  800. intent := portal.bridge.GetPuppetByID(sender.DiscordID).IntentFor(portal)
  801. intent.LeaveRoom(portal.MXID)
  802. }
  803. func (portal *Portal) Delete() {
  804. portal.Portal.Delete()
  805. portal.bridge.portalsLock.Lock()
  806. delete(portal.bridge.portalsByID, portal.Key)
  807. if portal.MXID != "" {
  808. delete(portal.bridge.portalsByMXID, portal.MXID)
  809. }
  810. portal.bridge.portalsLock.Unlock()
  811. }
  812. func (portal *Portal) cleanupIfEmpty() {
  813. if portal.MXID == "" {
  814. return
  815. }
  816. users, err := portal.getMatrixUsers()
  817. if err != nil {
  818. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  819. return
  820. }
  821. if len(users) == 0 {
  822. portal.log.Infoln("Room seems to be empty, cleaning up...")
  823. portal.Delete()
  824. portal.cleanup(false)
  825. }
  826. }
  827. func (portal *Portal) cleanup(puppetsOnly bool) {
  828. if portal.MXID == "" {
  829. return
  830. }
  831. if portal.IsPrivateChat() {
  832. _, err := portal.MainIntent().LeaveRoom(portal.MXID)
  833. if err != nil {
  834. portal.log.Warnln("Failed to leave private chat portal with main intent:", err)
  835. }
  836. return
  837. }
  838. intent := portal.MainIntent()
  839. members, err := intent.JoinedMembers(portal.MXID)
  840. if err != nil {
  841. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  842. return
  843. }
  844. for member := range members.Joined {
  845. if member == intent.UserID {
  846. continue
  847. }
  848. puppet := portal.bridge.GetPuppetByMXID(member)
  849. if portal != nil {
  850. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  851. if err != nil {
  852. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  853. }
  854. } else if !puppetsOnly {
  855. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  856. if err != nil {
  857. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  858. }
  859. }
  860. }
  861. _, err = intent.LeaveRoom(portal.MXID)
  862. if err != nil {
  863. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  864. }
  865. }
  866. func (portal *Portal) getMatrixUsers() ([]id.UserID, error) {
  867. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  868. if err != nil {
  869. return nil, fmt.Errorf("failed to get member list: %w", err)
  870. }
  871. var users []id.UserID
  872. for userID := range members.Joined {
  873. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  874. if !isPuppet && userID != portal.bridge.Bot.UserID {
  875. users = append(users, userID)
  876. }
  877. }
  878. return users, nil
  879. }
  880. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) {
  881. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  882. return
  883. }
  884. reaction := evt.Content.AsReaction()
  885. if reaction.RelatesTo.Type != event.RelAnnotation {
  886. portal.log.Errorfln("Ignoring reaction %s due to unknown m.relates_to data", evt.ID)
  887. return
  888. }
  889. var discordID, threadID string
  890. channelID := portal.Key.ChannelID
  891. msg := portal.bridge.DB.Message.GetByMXID(portal.Key, reaction.RelatesTo.EventID)
  892. // Due to the differences in attachments between Discord and Matrix, if a
  893. // user reacts to a media message on discord our lookup above will fail
  894. // because the relation of matrix media messages to attachments in handled
  895. // in the attachments table instead of messages so we need to check that
  896. // before continuing.
  897. //
  898. // This also leads to interesting problems when a Discord message comes in
  899. // with multiple attachments. A user can react to each one individually on
  900. // Matrix, which will cause us to send it twice. Discord tends to ignore
  901. // this, but if the user removes one of them, discord removes it and now
  902. // they're out of sync. Perhaps we should add a counter to the reactions
  903. // table to keep them in sync and to avoid sending duplicates to Discord.
  904. if msg == nil {
  905. attachment := portal.bridge.DB.Attachment.GetByMatrixID(portal.Key, reaction.RelatesTo.EventID)
  906. if attachment == nil {
  907. return
  908. }
  909. discordID = attachment.MessageID
  910. threadID = attachment.ThreadID
  911. } else {
  912. discordID = msg.DiscordID
  913. threadID = msg.ThreadID
  914. }
  915. // Figure out if this is a custom emoji or not.
  916. emojiID := reaction.RelatesTo.Key
  917. if strings.HasPrefix(emojiID, "mxc://") {
  918. uri, _ := id.ParseContentURI(emojiID)
  919. emoji := portal.bridge.DB.Emoji.GetByMatrixURL(uri)
  920. if emoji == nil {
  921. portal.log.Errorfln("Couldn't find emoji corresponding to %s", emojiID)
  922. return
  923. }
  924. emojiID = emoji.APIName()
  925. } else {
  926. emojiID = variationselector.Remove(emojiID)
  927. }
  928. if threadID != "" {
  929. channelID = threadID
  930. }
  931. err := sender.Session.MessageReactionAdd(channelID, discordID, emojiID)
  932. if err != nil {
  933. portal.log.Debugf("Failed to send reaction to %s: %v", discordID, err)
  934. return
  935. }
  936. dbReaction := portal.bridge.DB.Reaction.New()
  937. dbReaction.Channel = portal.Key
  938. dbReaction.MessageID = discordID
  939. dbReaction.Sender = sender.DiscordID
  940. dbReaction.EmojiName = emojiID
  941. dbReaction.ThreadID = threadID
  942. dbReaction.MXID = evt.ID
  943. dbReaction.Insert()
  944. }
  945. func (portal *Portal) handleDiscordReaction(user *User, reaction *discordgo.MessageReaction, add bool, thread *Thread) {
  946. intent := portal.bridge.GetPuppetByID(reaction.UserID).IntentFor(portal)
  947. var discordID string
  948. var matrixReaction string
  949. if reaction.Emoji.ID != "" {
  950. dbEmoji := portal.bridge.DB.Emoji.GetByDiscordID(reaction.Emoji.ID)
  951. if dbEmoji == nil {
  952. data, mimeType, err := portal.downloadDiscordEmoji(reaction.Emoji.ID, reaction.Emoji.Animated)
  953. if err != nil {
  954. portal.log.Warnfln("Failed to download emoji %s from discord: %v", reaction.Emoji.ID, err)
  955. return
  956. }
  957. uri, err := portal.uploadMatrixEmoji(intent, data, mimeType)
  958. if err != nil {
  959. portal.log.Warnfln("Failed to upload discord emoji %s to homeserver: %v", reaction.Emoji.ID, err)
  960. return
  961. }
  962. dbEmoji = portal.bridge.DB.Emoji.New()
  963. dbEmoji.DiscordID = reaction.Emoji.ID
  964. dbEmoji.DiscordName = reaction.Emoji.Name
  965. dbEmoji.MatrixURL = uri
  966. dbEmoji.Insert()
  967. }
  968. discordID = dbEmoji.DiscordID
  969. matrixReaction = dbEmoji.MatrixURL.String()
  970. } else {
  971. discordID = reaction.Emoji.Name
  972. matrixReaction = variationselector.Add(reaction.Emoji.Name)
  973. }
  974. // Find the message that we're working with.
  975. message := portal.bridge.DB.Message.GetByDiscordID(portal.Key, reaction.MessageID)
  976. if message == nil {
  977. portal.log.Debugfln("failed to add reaction to message %s: message not found", reaction.MessageID)
  978. return
  979. }
  980. // Lookup an existing reaction
  981. existing := portal.bridge.DB.Reaction.GetByDiscordID(portal.Key, message.DiscordID, reaction.UserID, discordID)
  982. if !add {
  983. if existing == nil {
  984. portal.log.Debugln("Failed to remove reaction for unknown message", reaction.MessageID)
  985. return
  986. }
  987. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  988. if err != nil {
  989. portal.log.Warnfln("Failed to remove reaction from %s: %v", portal.MXID, err)
  990. }
  991. existing.Delete()
  992. return
  993. } else if existing != nil {
  994. portal.log.Debugfln("Ignoring duplicate reaction %s from %s to %s", discordID, reaction.UserID, message.DiscordID)
  995. return
  996. }
  997. content := event.Content{Parsed: &event.ReactionEventContent{
  998. RelatesTo: event.RelatesTo{
  999. EventID: message.MXID,
  1000. Type: event.RelAnnotation,
  1001. Key: matrixReaction,
  1002. },
  1003. }}
  1004. resp, err := intent.Client.SendMessageEvent(portal.MXID, event.EventReaction, &content)
  1005. if err != nil {
  1006. portal.log.Errorfln("failed to send reaction from %s: %v", reaction.MessageID, err)
  1007. return
  1008. }
  1009. if existing == nil {
  1010. dbReaction := portal.bridge.DB.Reaction.New()
  1011. dbReaction.Channel = portal.Key
  1012. dbReaction.MessageID = message.DiscordID
  1013. dbReaction.Sender = reaction.UserID
  1014. dbReaction.EmojiName = discordID
  1015. dbReaction.MXID = resp.EventID
  1016. if thread != nil {
  1017. dbReaction.ThreadID = thread.ID
  1018. }
  1019. dbReaction.Insert()
  1020. }
  1021. }
  1022. func (portal *Portal) handleMatrixRedaction(user *User, evt *event.Event) {
  1023. if user.DiscordID != portal.Key.Receiver {
  1024. return
  1025. }
  1026. // First look if we're redacting a message
  1027. message := portal.bridge.DB.Message.GetByMXID(portal.Key, evt.Redacts)
  1028. if message != nil {
  1029. err := user.Session.ChannelMessageDelete(message.DiscordProtoChannelID(), message.DiscordID)
  1030. if err != nil {
  1031. portal.log.Debugfln("Failed to delete discord message %s: %v", message.DiscordID, err)
  1032. } else {
  1033. message.Delete()
  1034. }
  1035. return
  1036. }
  1037. // Now check if it's a reaction.
  1038. reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts)
  1039. if reaction != nil && reaction.Channel == portal.Key {
  1040. err := user.Session.MessageReactionRemove(reaction.DiscordProtoChannelID(), reaction.MessageID, reaction.EmojiName, reaction.Sender)
  1041. if err != nil {
  1042. portal.log.Debugfln("Failed to delete reaction %s from %s: %v", reaction.EmojiName, reaction.MessageID, err)
  1043. } else {
  1044. reaction.Delete()
  1045. }
  1046. return
  1047. }
  1048. portal.log.Warnfln("Failed to redact %s: no event found", evt.Redacts)
  1049. }
  1050. func (portal *Portal) UpdateName(name string) bool {
  1051. if portal.Name == name && portal.NameSet {
  1052. return false
  1053. } else if !portal.Encrypted && portal.IsPrivateChat() {
  1054. // TODO custom config option for always setting private chat portal meta?
  1055. return false
  1056. }
  1057. portal.Name = name
  1058. portal.NameSet = false
  1059. if portal.MXID != "" {
  1060. _, err := portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
  1061. if err != nil {
  1062. portal.log.Warnln("Failed to update room name:", err)
  1063. } else {
  1064. portal.NameSet = true
  1065. }
  1066. }
  1067. return true
  1068. }
  1069. func (portal *Portal) UpdateAvatarFromPuppet(puppet *Puppet) bool {
  1070. if portal.Avatar == puppet.Avatar && portal.AvatarSet {
  1071. return false
  1072. }
  1073. portal.Avatar = puppet.Avatar
  1074. portal.AvatarURL = puppet.AvatarURL
  1075. portal.AvatarSet = false
  1076. portal.updateRoomAvatar()
  1077. return true
  1078. }
  1079. func (portal *Portal) UpdateGroupDMAvatar(iconID string) bool {
  1080. if portal.Avatar == iconID && portal.AvatarSet {
  1081. return false
  1082. }
  1083. portal.Avatar = iconID
  1084. portal.AvatarSet = false
  1085. if portal.Avatar != "" {
  1086. uri, err := uploadAvatar(portal.MainIntent(), discordgo.EndpointGroupIcon(portal.Key.ChannelID, portal.Avatar))
  1087. if err != nil {
  1088. portal.log.Warnln("Failed to reupload avatar:", err)
  1089. return true
  1090. } else {
  1091. portal.AvatarURL = uri
  1092. }
  1093. } else {
  1094. portal.AvatarURL = id.ContentURI{}
  1095. }
  1096. portal.updateRoomAvatar()
  1097. return true
  1098. }
  1099. func (portal *Portal) updateRoomAvatar() {
  1100. if portal.MXID == "" {
  1101. return
  1102. }
  1103. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1104. if err != nil {
  1105. portal.log.Warnln("Failed to update room avatar:", err)
  1106. } else {
  1107. portal.AvatarSet = true
  1108. }
  1109. }
  1110. func (portal *Portal) UpdateTopic(topic string) bool {
  1111. if portal.Topic == topic && portal.TopicSet {
  1112. return false
  1113. }
  1114. portal.Topic = topic
  1115. portal.TopicSet = false
  1116. if portal.MXID != "" {
  1117. _, err := portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
  1118. if err != nil {
  1119. portal.log.Warnln("Failed to update room topic:", err)
  1120. }
  1121. }
  1122. return true
  1123. }
  1124. func (portal *Portal) removeFromSpace() {
  1125. if portal.InSpace == "" {
  1126. return
  1127. }
  1128. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, portal.InSpace.String(), struct{}{})
  1129. if err != nil {
  1130. portal.log.Warnfln("Failed to unset canonical space %s: %v", portal.InSpace, err)
  1131. }
  1132. _, err = portal.bridge.Bot.SendStateEvent(portal.InSpace, event.StateSpaceChild, portal.MXID.String(), struct{}{})
  1133. if err != nil {
  1134. portal.log.Warnfln("Failed to add room to space %s: %v", portal.InSpace, err)
  1135. }
  1136. portal.InSpace = ""
  1137. }
  1138. func (portal *Portal) addToSpace(mxid id.RoomID) bool {
  1139. if portal.InSpace == mxid {
  1140. return false
  1141. }
  1142. portal.removeFromSpace()
  1143. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, mxid.String(), &event.SpaceParentEventContent{
  1144. Via: []string{portal.bridge.AS.HomeserverDomain},
  1145. Canonical: true,
  1146. })
  1147. if err != nil {
  1148. portal.log.Warnfln("Failed to set canonical space %s: %v", mxid, err)
  1149. }
  1150. _, err = portal.bridge.Bot.SendStateEvent(mxid, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1151. Via: []string{portal.bridge.AS.HomeserverDomain},
  1152. // TODO order
  1153. })
  1154. if err != nil {
  1155. portal.log.Warnfln("Failed to add room to space %s: %v", mxid, err)
  1156. } else {
  1157. portal.InSpace = mxid
  1158. }
  1159. return true
  1160. }
  1161. func (portal *Portal) UpdateParent(parentID string) bool {
  1162. if portal.ParentID == parentID {
  1163. return false
  1164. }
  1165. portal.ParentID = parentID
  1166. if portal.ParentID != "" {
  1167. portal.Parent = portal.bridge.GetExistingPortalByID(database.NewPortalKey(parentID, ""))
  1168. } else {
  1169. portal.Parent = nil
  1170. }
  1171. return true
  1172. }
  1173. func (portal *Portal) ExpectedSpaceID() id.RoomID {
  1174. if portal.Parent != nil {
  1175. return portal.Parent.MXID
  1176. } else if portal.Guild != nil {
  1177. return portal.Guild.MXID
  1178. }
  1179. return ""
  1180. }
  1181. func (portal *Portal) updateSpace() bool {
  1182. if portal.MXID == "" {
  1183. return false
  1184. }
  1185. if portal.Parent != nil {
  1186. return portal.addToSpace(portal.Parent.MXID)
  1187. } else if portal.Guild != nil {
  1188. return portal.addToSpace(portal.Guild.MXID)
  1189. }
  1190. return false
  1191. }
  1192. func (portal *Portal) UpdateInfo(source *User, meta *discordgo.Channel) *discordgo.Channel {
  1193. changed := false
  1194. if portal.Type != meta.Type {
  1195. portal.log.Warnfln("Portal type changed from %d to %d", portal.Type, meta.Type)
  1196. portal.Type = meta.Type
  1197. changed = true
  1198. }
  1199. if portal.OtherUserID == "" && portal.IsPrivateChat() {
  1200. if len(meta.Recipients) == 0 {
  1201. var err error
  1202. meta, err = source.Session.Channel(meta.ID)
  1203. if err != nil {
  1204. portal.log.Errorfln("Failed to get DM channel info:", err)
  1205. }
  1206. }
  1207. portal.OtherUserID = meta.Recipients[0].ID
  1208. portal.log.Infoln("Found other user ID:", portal.OtherUserID)
  1209. changed = true
  1210. }
  1211. if meta.GuildID != "" && portal.GuildID == "" {
  1212. portal.GuildID = meta.GuildID
  1213. portal.Guild = portal.bridge.GetGuildByID(portal.GuildID, true)
  1214. changed = true
  1215. }
  1216. // FIXME
  1217. //name, err := portal.bridge.Config.Bridge.FormatChannelname(meta, source.Session)
  1218. //if err != nil {
  1219. // portal.log.Errorln("Failed to format channel name:", err)
  1220. // return
  1221. //}
  1222. switch portal.Type {
  1223. case discordgo.ChannelTypeDM:
  1224. if portal.OtherUserID != "" {
  1225. puppet := portal.bridge.GetPuppetByID(portal.OtherUserID)
  1226. changed = portal.UpdateAvatarFromPuppet(puppet) || changed
  1227. changed = portal.UpdateName(puppet.Name) || changed
  1228. }
  1229. case discordgo.ChannelTypeGroupDM:
  1230. changed = portal.UpdateGroupDMAvatar(meta.Icon) || changed
  1231. fallthrough
  1232. default:
  1233. changed = portal.UpdateName(meta.Name) || changed
  1234. }
  1235. changed = portal.UpdateTopic(meta.Topic) || changed
  1236. changed = portal.UpdateParent(meta.ParentID) || changed
  1237. if portal.MXID != "" && portal.ExpectedSpaceID() != portal.InSpace {
  1238. changed = portal.updateSpace() || changed
  1239. }
  1240. if changed {
  1241. portal.UpdateBridgeInfo()
  1242. portal.Update()
  1243. }
  1244. return meta
  1245. }