portal.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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, 0)
  392. if err != nil {
  393. portal.log.Warnfln("Failed to send media 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 := renderDiscordMarkdown(msg.Content)
  501. content.RelatesTo = threadRelation.Copy()
  502. if msg.MessageReference != nil {
  503. //key := database.PortalKey{msg.MessageReference.ChannelID, user.ID}
  504. replyTo := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.MessageReference.MessageID)
  505. if replyTo != nil {
  506. if content.RelatesTo == nil {
  507. content.RelatesTo = &event.RelatesTo{}
  508. }
  509. content.RelatesTo.SetReplyTo(replyTo.MXID)
  510. }
  511. }
  512. resp, err := portal.sendMatrixMessage(intent, event.EventMessage, &content, nil, ts.UnixMilli())
  513. if err != nil {
  514. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  515. return
  516. }
  517. portal.markMessageHandled(msg.ID, resp.EventID, msg.Author.ID, ts, threadID)
  518. // Update the fallback reply event for attachments
  519. if threadRelation != nil {
  520. threadRelation.InReplyTo.EventID = resp.EventID
  521. }
  522. }
  523. for _, attachment := range msg.Attachments {
  524. portal.handleDiscordAttachment(intent, msg.ID, attachment, ts, threadRelation, threadID)
  525. }
  526. }
  527. func (portal *Portal) handleDiscordMessageUpdate(user *User, msg *discordgo.Message) {
  528. if portal.MXID == "" {
  529. portal.log.Warnln("handle message called without a valid portal")
  530. return
  531. }
  532. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  533. if existing == nil {
  534. portal.log.Warnfln("Dropping update of unknown message %s", msg.ID)
  535. return
  536. }
  537. if msg.Flags == discordgo.MessageFlagsHasThread {
  538. portal.bridge.GetThreadByID(msg.ID, existing)
  539. portal.log.Debugfln("Marked %s as a thread root", msg.ID)
  540. // TODO make autojoining configurable
  541. //err := user.Session.ThreadJoinWithLocation(msg.ID, discordgo.ThreadJoinLocationContextMenu)
  542. //if err != nil {
  543. // user.log.Warnfln("Error autojoining thread %s@%s: %v", msg.ChannelID, portal.Key.ChannelID, err)
  544. //}
  545. }
  546. // There's a few scenarios where the author is nil but I haven't figured
  547. // them all out yet.
  548. if msg.Author == nil {
  549. // If the server has to lookup opengraph previews it'll send the
  550. // message through without the preview and then add the preview later
  551. // via a message update. However, when it does this there is no author
  552. // as it's just the server, so for the moment we'll ignore this to
  553. // avoid a crash.
  554. if len(msg.Embeds) > 0 {
  555. portal.log.Debugln("ignoring update for opengraph attachment")
  556. return
  557. }
  558. //portal.log.Errorfln("author is nil: %#v", msg)
  559. return
  560. }
  561. intent := portal.bridge.GetPuppetByID(msg.Author.ID).IntentFor(portal)
  562. if existing == nil {
  563. // Due to the differences in Discord and Matrix attachment handling,
  564. // existing will return nil if the original message was empty as we
  565. // don't store/save those messages so we can determine when we're
  566. // working against an attachment and do the attachment lookup instead.
  567. // Find all the existing attachments and drop them in a map so we can
  568. // figure out which, if any have been deleted and clean them up on the
  569. // matrix side.
  570. attachmentMap := map[string]*database.Attachment{}
  571. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  572. for _, attachment := range attachments {
  573. attachmentMap[attachment.ID] = attachment
  574. }
  575. // Now run through the list of attachments on this message and remove
  576. // them from the map.
  577. for _, attachment := range msg.Attachments {
  578. if _, found := attachmentMap[attachment.ID]; found {
  579. delete(attachmentMap, attachment.ID)
  580. }
  581. }
  582. // Finally run through any attachments still in the map and delete them
  583. // on the matrix side and our database.
  584. for _, attachment := range attachmentMap {
  585. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  586. if err != nil {
  587. portal.log.Warnfln("Failed to remove attachment %s: %v", attachment.MXID, err)
  588. }
  589. attachment.Delete()
  590. }
  591. return
  592. }
  593. content := renderDiscordMarkdown(msg.Content)
  594. content.SetEdit(existing.MXID)
  595. var editTS int64
  596. if msg.EditedTimestamp != nil {
  597. editTS = msg.EditedTimestamp.UnixMilli()
  598. }
  599. // TODO figure out some way to deduplicate outgoing edits
  600. _, err := portal.sendMatrixMessage(intent, event.EventMessage, &content, nil, editTS)
  601. if err != nil {
  602. portal.log.Warnfln("failed to send message %q to matrix: %v", msg.ID, err)
  603. return
  604. }
  605. //ts, _ := msg.Timestamp.Parse()
  606. //portal.markMessageHandled(existing, msg.ID, resp.EventID, msg.Author.ID, ts)
  607. }
  608. func (portal *Portal) handleDiscordMessageDelete(user *User, msg *discordgo.Message) {
  609. // The discord delete message object is pretty empty and doesn't include
  610. // the author so we have to use the DMUser from the portal that was added
  611. // at creation time if we're a DM. We'll might have similar issues when we
  612. // add guild message support, but we'll cross that bridge when we get
  613. // there.
  614. // Find the message that we're working with. This could correctly return
  615. // nil if the message was just one or more attachments.
  616. existing := portal.bridge.DB.Message.GetByDiscordID(portal.Key, msg.ID)
  617. intent := portal.MainIntent()
  618. if existing != nil {
  619. attachments := portal.bridge.DB.Attachment.GetAllByDiscordMessageID(portal.Key, msg.ID)
  620. for _, attachment := range attachments {
  621. _, err := intent.RedactEvent(portal.MXID, attachment.MXID)
  622. if err != nil {
  623. portal.log.Warnfln("Failed to redact attachment %s: %v", attachment.MXID, err)
  624. }
  625. attachment.Delete()
  626. }
  627. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  628. if err != nil {
  629. portal.log.Warnfln("Failed to redact message %s: %v", existing.MXID, err)
  630. }
  631. existing.Delete()
  632. }
  633. }
  634. func (portal *Portal) syncParticipants(source *User, participants []*discordgo.User) {
  635. for _, participant := range participants {
  636. puppet := portal.bridge.GetPuppetByID(participant.ID)
  637. puppet.UpdateInfo(source, participant)
  638. user := portal.bridge.GetUserByID(participant.ID)
  639. if user != nil {
  640. portal.ensureUserInvited(user)
  641. }
  642. if user == nil || !puppet.IntentFor(portal).IsCustomPuppet {
  643. if err := puppet.IntentFor(portal).EnsureJoined(portal.MXID); err != nil {
  644. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, portal.MXID, err)
  645. }
  646. }
  647. }
  648. }
  649. func (portal *Portal) encrypt(content *event.Content, eventType event.Type) (event.Type, error) {
  650. if portal.Encrypted && portal.bridge.Crypto != nil {
  651. // TODO maybe the locking should be inside mautrix-go?
  652. portal.encryptLock.Lock()
  653. encrypted, err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, *content)
  654. portal.encryptLock.Unlock()
  655. if err != nil {
  656. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  657. }
  658. eventType = event.EventEncrypted
  659. content.Parsed = encrypted
  660. }
  661. return eventType, nil
  662. }
  663. const doublePuppetValue = "mautrix-discord"
  664. func (portal *Portal) sendMatrixMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  665. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  666. if timestamp != 0 && intent.IsCustomPuppet {
  667. if wrappedContent.Raw == nil {
  668. wrappedContent.Raw = map[string]interface{}{}
  669. }
  670. if intent.IsCustomPuppet {
  671. wrappedContent.Raw[bridge.DoublePuppetKey] = doublePuppetValue
  672. }
  673. }
  674. var err error
  675. eventType, err = portal.encrypt(&wrappedContent, eventType)
  676. if err != nil {
  677. return nil, err
  678. }
  679. if eventType == event.EventEncrypted {
  680. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  681. if intent.IsCustomPuppet {
  682. wrappedContent.Raw = map[string]interface{}{bridge.DoublePuppetKey: doublePuppetValue}
  683. } else {
  684. wrappedContent.Raw = nil
  685. }
  686. }
  687. _, _ = intent.UserTyping(portal.MXID, false, 0)
  688. if timestamp == 0 {
  689. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  690. } else {
  691. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  692. }
  693. }
  694. func (portal *Portal) handleMatrixMessages(msg portalMatrixMessage) {
  695. switch msg.evt.Type {
  696. case event.EventMessage:
  697. portal.handleMatrixMessage(msg.user, msg.evt)
  698. case event.EventRedaction:
  699. portal.handleMatrixRedaction(msg.user, msg.evt)
  700. case event.EventReaction:
  701. portal.handleMatrixReaction(msg.user, msg.evt)
  702. default:
  703. portal.log.Debugln("unknown event type", msg.evt.Type)
  704. }
  705. }
  706. const discordEpoch = 1420070400000
  707. func generateNonce() string {
  708. snowflake := (time.Now().UnixMilli() - discordEpoch) << 22
  709. // Nonce snowflakes don't have internal IDs or increments
  710. return strconv.FormatInt(snowflake, 10)
  711. }
  712. func (portal *Portal) getEvent(mxid id.EventID) (*event.Event, error) {
  713. evt, err := portal.MainIntent().GetEvent(portal.MXID, mxid)
  714. if err != nil {
  715. return nil, err
  716. }
  717. _ = evt.Content.ParseRaw(evt.Type)
  718. if evt.Type == event.EventEncrypted {
  719. decryptedEvt, err := portal.bridge.Crypto.Decrypt(evt)
  720. if err != nil {
  721. return nil, err
  722. } else {
  723. evt = decryptedEvt
  724. }
  725. }
  726. return evt, nil
  727. }
  728. func genThreadName(evt *event.Event) string {
  729. body := evt.Content.AsMessage().Body
  730. if len(body) == 0 {
  731. return "thread"
  732. }
  733. fields := strings.Fields(body)
  734. var title string
  735. for _, field := range fields {
  736. if len(title)+len(field) < 40 {
  737. title += field
  738. title += " "
  739. continue
  740. }
  741. if len(title) == 0 {
  742. title = field[:40]
  743. }
  744. break
  745. }
  746. return title
  747. }
  748. func (portal *Portal) startThreadFromMatrix(sender *User, threadRoot id.EventID) (string, error) {
  749. rootEvt, err := portal.getEvent(threadRoot)
  750. if err != nil {
  751. return "", fmt.Errorf("failed to get root event: %w", err)
  752. }
  753. threadName := genThreadName(rootEvt)
  754. existingMsg := portal.bridge.DB.Message.GetByMXID(portal.Key, threadRoot)
  755. if existingMsg == nil {
  756. return "", fmt.Errorf("unknown root event")
  757. } else if existingMsg.ThreadID != "" {
  758. return "", fmt.Errorf("root event is already in a thread")
  759. } else {
  760. var ch *discordgo.Channel
  761. ch, err = sender.Session.MessageThreadStartComplex(portal.Key.ChannelID, existingMsg.DiscordID, &discordgo.ThreadStart{
  762. Name: threadName,
  763. AutoArchiveDuration: 24 * 60,
  764. Type: discordgo.ChannelTypeGuildPublicThread,
  765. Location: "Message",
  766. })
  767. if err != nil {
  768. return "", fmt.Errorf("error starting thread: %v", err)
  769. }
  770. portal.log.Debugfln("Created Discord thread from %s/%s", threadRoot, ch.ID)
  771. fmt.Printf("Created thread %+v\n", ch)
  772. portal.bridge.GetThreadByID(existingMsg.DiscordID, existingMsg)
  773. return ch.ID, nil
  774. }
  775. }
  776. func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
  777. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  778. return
  779. }
  780. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  781. if !ok {
  782. portal.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
  783. return
  784. }
  785. channelID := portal.Key.ChannelID
  786. var threadID string
  787. if editMXID := content.GetRelatesTo().GetReplaceID(); editMXID != "" && content.NewContent != nil {
  788. edits := portal.bridge.DB.Message.GetByMXID(portal.Key, editMXID)
  789. if edits != nil {
  790. discordContent := portal.parseMatrixHTML(sender, content.NewContent)
  791. // we don't have anything to save for the update message right now
  792. // as we're not tracking edited timestamps.
  793. _, err := sender.Session.ChannelMessageEdit(edits.DiscordProtoChannelID(), edits.DiscordID, discordContent)
  794. if err != nil {
  795. portal.log.Errorln("Failed to update message %s: %v", edits.DiscordID, err)
  796. }
  797. }
  798. return
  799. } else if threadRoot := content.GetRelatesTo().GetThreadParent(); threadRoot != "" {
  800. existingThread := portal.bridge.DB.Thread.GetByMatrixRootMsg(threadRoot)
  801. if existingThread != nil {
  802. threadID = existingThread.ID
  803. } else {
  804. var err error
  805. threadID, err = portal.startThreadFromMatrix(sender, threadRoot)
  806. if err != nil {
  807. portal.log.Warnfln("Failed to start thread from %s: %v", threadRoot, err)
  808. }
  809. }
  810. }
  811. if threadID != "" {
  812. channelID = threadID
  813. }
  814. var sendReq discordgo.MessageSend
  815. switch content.MsgType {
  816. case event.MsgText, event.MsgEmote, event.MsgNotice:
  817. if replyToMXID := content.GetReplyTo(); replyToMXID != "" {
  818. replyTo := portal.bridge.DB.Message.GetByMXID(portal.Key, replyToMXID)
  819. if replyTo != nil && replyTo.ThreadID == threadID {
  820. sendReq.Reference = &discordgo.MessageReference{
  821. ChannelID: channelID,
  822. MessageID: replyTo.DiscordID,
  823. }
  824. }
  825. }
  826. sendReq.Content = portal.parseMatrixHTML(sender, content)
  827. case event.MsgAudio, event.MsgFile, event.MsgImage, event.MsgVideo:
  828. data, err := portal.downloadMatrixAttachment(evt.ID, content)
  829. if err != nil {
  830. portal.log.Errorfln("Failed to download matrix attachment: %v", err)
  831. return
  832. }
  833. sendReq.Files = []*discordgo.File{{
  834. Name: content.Body,
  835. ContentType: content.Info.MimeType,
  836. Reader: bytes.NewReader(data),
  837. }}
  838. default:
  839. portal.log.Warnln("Unknown message type", content.MsgType)
  840. return
  841. }
  842. sendReq.Nonce = generateNonce()
  843. msg, err := sender.Session.ChannelMessageSendComplex(channelID, &sendReq)
  844. if err != nil {
  845. portal.log.Errorfln("Failed to send message: %v", err)
  846. return
  847. }
  848. if msg != nil {
  849. dbMsg := portal.bridge.DB.Message.New()
  850. dbMsg.Channel = portal.Key
  851. dbMsg.DiscordID = msg.ID
  852. dbMsg.MXID = evt.ID
  853. dbMsg.SenderID = sender.DiscordID
  854. dbMsg.Timestamp, _ = discordgo.SnowflakeTimestamp(msg.ID)
  855. dbMsg.ThreadID = threadID
  856. dbMsg.Insert()
  857. }
  858. }
  859. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  860. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  861. portal.Delete()
  862. portal.cleanup(false)
  863. // TODO: figure out how to close a dm from the API.
  864. portal.cleanupIfEmpty()
  865. }
  866. func (portal *Portal) leave(sender *User) {
  867. if portal.MXID == "" {
  868. return
  869. }
  870. intent := portal.bridge.GetPuppetByID(sender.DiscordID).IntentFor(portal)
  871. intent.LeaveRoom(portal.MXID)
  872. }
  873. func (portal *Portal) Delete() {
  874. portal.Portal.Delete()
  875. portal.bridge.portalsLock.Lock()
  876. delete(portal.bridge.portalsByID, portal.Key)
  877. if portal.MXID != "" {
  878. delete(portal.bridge.portalsByMXID, portal.MXID)
  879. }
  880. portal.bridge.portalsLock.Unlock()
  881. }
  882. func (portal *Portal) cleanupIfEmpty() {
  883. if portal.MXID == "" {
  884. return
  885. }
  886. users, err := portal.getMatrixUsers()
  887. if err != nil {
  888. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  889. return
  890. }
  891. if len(users) == 0 {
  892. portal.log.Infoln("Room seems to be empty, cleaning up...")
  893. portal.Delete()
  894. portal.cleanup(false)
  895. }
  896. }
  897. func (portal *Portal) cleanup(puppetsOnly bool) {
  898. if portal.MXID == "" {
  899. return
  900. }
  901. if portal.IsPrivateChat() {
  902. _, err := portal.MainIntent().LeaveRoom(portal.MXID)
  903. if err != nil {
  904. portal.log.Warnln("Failed to leave private chat portal with main intent:", err)
  905. }
  906. return
  907. }
  908. intent := portal.MainIntent()
  909. members, err := intent.JoinedMembers(portal.MXID)
  910. if err != nil {
  911. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  912. return
  913. }
  914. for member := range members.Joined {
  915. if member == intent.UserID {
  916. continue
  917. }
  918. puppet := portal.bridge.GetPuppetByMXID(member)
  919. if portal != nil {
  920. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  921. if err != nil {
  922. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  923. }
  924. } else if !puppetsOnly {
  925. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  926. if err != nil {
  927. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  928. }
  929. }
  930. }
  931. _, err = intent.LeaveRoom(portal.MXID)
  932. if err != nil {
  933. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  934. }
  935. }
  936. func (portal *Portal) getMatrixUsers() ([]id.UserID, error) {
  937. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  938. if err != nil {
  939. return nil, fmt.Errorf("failed to get member list: %w", err)
  940. }
  941. var users []id.UserID
  942. for userID := range members.Joined {
  943. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  944. if !isPuppet && userID != portal.bridge.Bot.UserID {
  945. users = append(users, userID)
  946. }
  947. }
  948. return users, nil
  949. }
  950. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) {
  951. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  952. return
  953. }
  954. reaction := evt.Content.AsReaction()
  955. if reaction.RelatesTo.Type != event.RelAnnotation {
  956. portal.log.Errorfln("Ignoring reaction %s due to unknown m.relates_to data", evt.ID)
  957. return
  958. }
  959. var discordID, threadID string
  960. channelID := portal.Key.ChannelID
  961. msg := portal.bridge.DB.Message.GetByMXID(portal.Key, reaction.RelatesTo.EventID)
  962. // Due to the differences in attachments between Discord and Matrix, if a
  963. // user reacts to a media message on discord our lookup above will fail
  964. // because the relation of matrix media messages to attachments in handled
  965. // in the attachments table instead of messages so we need to check that
  966. // before continuing.
  967. //
  968. // This also leads to interesting problems when a Discord message comes in
  969. // with multiple attachments. A user can react to each one individually on
  970. // Matrix, which will cause us to send it twice. Discord tends to ignore
  971. // this, but if the user removes one of them, discord removes it and now
  972. // they're out of sync. Perhaps we should add a counter to the reactions
  973. // table to keep them in sync and to avoid sending duplicates to Discord.
  974. if msg == nil {
  975. attachment := portal.bridge.DB.Attachment.GetByMatrixID(portal.Key, reaction.RelatesTo.EventID)
  976. if attachment == nil {
  977. return
  978. }
  979. discordID = attachment.MessageID
  980. threadID = attachment.ThreadID
  981. } else {
  982. discordID = msg.DiscordID
  983. threadID = msg.ThreadID
  984. }
  985. // Figure out if this is a custom emoji or not.
  986. emojiID := reaction.RelatesTo.Key
  987. if strings.HasPrefix(emojiID, "mxc://") {
  988. uri, _ := id.ParseContentURI(emojiID)
  989. emoji := portal.bridge.DB.Emoji.GetByMatrixURL(uri)
  990. if emoji == nil {
  991. portal.log.Errorfln("Couldn't find emoji corresponding to %s", emojiID)
  992. return
  993. }
  994. emojiID = emoji.APIName()
  995. } else {
  996. emojiID = variationselector.Remove(emojiID)
  997. }
  998. if threadID != "" {
  999. channelID = threadID
  1000. }
  1001. err := sender.Session.MessageReactionAdd(channelID, discordID, emojiID)
  1002. if err != nil {
  1003. portal.log.Debugf("Failed to send reaction to %s: %v", discordID, err)
  1004. return
  1005. }
  1006. dbReaction := portal.bridge.DB.Reaction.New()
  1007. dbReaction.Channel = portal.Key
  1008. dbReaction.MessageID = discordID
  1009. dbReaction.Sender = sender.DiscordID
  1010. dbReaction.EmojiName = emojiID
  1011. dbReaction.ThreadID = threadID
  1012. dbReaction.MXID = evt.ID
  1013. dbReaction.Insert()
  1014. }
  1015. func (portal *Portal) handleDiscordReaction(user *User, reaction *discordgo.MessageReaction, add bool, thread *Thread) {
  1016. intent := portal.bridge.GetPuppetByID(reaction.UserID).IntentFor(portal)
  1017. var discordID string
  1018. var matrixReaction string
  1019. if reaction.Emoji.ID != "" {
  1020. dbEmoji := portal.bridge.DB.Emoji.GetByDiscordID(reaction.Emoji.ID)
  1021. if dbEmoji == nil {
  1022. data, mimeType, err := portal.downloadDiscordEmoji(reaction.Emoji.ID, reaction.Emoji.Animated)
  1023. if err != nil {
  1024. portal.log.Warnfln("Failed to download emoji %s from discord: %v", reaction.Emoji.ID, err)
  1025. return
  1026. }
  1027. uri, err := portal.uploadMatrixEmoji(intent, data, mimeType)
  1028. if err != nil {
  1029. portal.log.Warnfln("Failed to upload discord emoji %s to homeserver: %v", reaction.Emoji.ID, err)
  1030. return
  1031. }
  1032. dbEmoji = portal.bridge.DB.Emoji.New()
  1033. dbEmoji.DiscordID = reaction.Emoji.ID
  1034. dbEmoji.DiscordName = reaction.Emoji.Name
  1035. dbEmoji.MatrixURL = uri
  1036. dbEmoji.Insert()
  1037. }
  1038. discordID = dbEmoji.DiscordID
  1039. matrixReaction = dbEmoji.MatrixURL.String()
  1040. } else {
  1041. discordID = reaction.Emoji.Name
  1042. matrixReaction = variationselector.Add(reaction.Emoji.Name)
  1043. }
  1044. // Find the message that we're working with.
  1045. message := portal.bridge.DB.Message.GetByDiscordID(portal.Key, reaction.MessageID)
  1046. if message == nil {
  1047. portal.log.Debugfln("failed to add reaction to message %s: message not found", reaction.MessageID)
  1048. return
  1049. }
  1050. // Lookup an existing reaction
  1051. existing := portal.bridge.DB.Reaction.GetByDiscordID(portal.Key, message.DiscordID, reaction.UserID, discordID)
  1052. if !add {
  1053. if existing == nil {
  1054. portal.log.Debugln("Failed to remove reaction for unknown message", reaction.MessageID)
  1055. return
  1056. }
  1057. _, err := intent.RedactEvent(portal.MXID, existing.MXID)
  1058. if err != nil {
  1059. portal.log.Warnfln("Failed to remove reaction from %s: %v", portal.MXID, err)
  1060. }
  1061. existing.Delete()
  1062. return
  1063. } else if existing != nil {
  1064. portal.log.Debugfln("Ignoring duplicate reaction %s from %s to %s", discordID, reaction.UserID, message.DiscordID)
  1065. return
  1066. }
  1067. content := event.Content{Parsed: &event.ReactionEventContent{
  1068. RelatesTo: event.RelatesTo{
  1069. EventID: message.MXID,
  1070. Type: event.RelAnnotation,
  1071. Key: matrixReaction,
  1072. },
  1073. }}
  1074. if intent.IsCustomPuppet {
  1075. content.Raw = map[string]interface{}{
  1076. bridge.DoublePuppetKey: doublePuppetValue,
  1077. }
  1078. }
  1079. resp, err := intent.SendMessageEvent(portal.MXID, event.EventReaction, &content)
  1080. if err != nil {
  1081. portal.log.Errorfln("failed to send reaction from %s: %v", reaction.MessageID, err)
  1082. return
  1083. }
  1084. if existing == nil {
  1085. dbReaction := portal.bridge.DB.Reaction.New()
  1086. dbReaction.Channel = portal.Key
  1087. dbReaction.MessageID = message.DiscordID
  1088. dbReaction.Sender = reaction.UserID
  1089. dbReaction.EmojiName = discordID
  1090. dbReaction.MXID = resp.EventID
  1091. if thread != nil {
  1092. dbReaction.ThreadID = thread.ID
  1093. }
  1094. dbReaction.Insert()
  1095. }
  1096. }
  1097. func (portal *Portal) handleMatrixRedaction(sender *User, evt *event.Event) {
  1098. if portal.IsPrivateChat() && sender.DiscordID != portal.Key.Receiver {
  1099. return
  1100. }
  1101. // First look if we're redacting a message
  1102. message := portal.bridge.DB.Message.GetByMXID(portal.Key, evt.Redacts)
  1103. if message != nil {
  1104. err := sender.Session.ChannelMessageDelete(message.DiscordProtoChannelID(), message.DiscordID)
  1105. if err != nil {
  1106. portal.log.Debugfln("Failed to delete discord message %s: %v", message.DiscordID, err)
  1107. } else {
  1108. message.Delete()
  1109. }
  1110. return
  1111. }
  1112. // Now check if it's a reaction.
  1113. reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts)
  1114. if reaction != nil && reaction.Channel == portal.Key {
  1115. err := sender.Session.MessageReactionRemove(reaction.DiscordProtoChannelID(), reaction.MessageID, reaction.EmojiName, reaction.Sender)
  1116. if err != nil {
  1117. portal.log.Debugfln("Failed to delete reaction %s from %s: %v", reaction.EmojiName, reaction.MessageID, err)
  1118. } else {
  1119. reaction.Delete()
  1120. }
  1121. return
  1122. }
  1123. portal.log.Warnfln("Failed to redact %s: no event found", evt.Redacts)
  1124. }
  1125. func (portal *Portal) UpdateName(name string) bool {
  1126. if portal.Name == name && portal.NameSet {
  1127. return false
  1128. } else if !portal.Encrypted && portal.IsPrivateChat() {
  1129. // TODO custom config option for always setting private chat portal meta?
  1130. return false
  1131. }
  1132. portal.Name = name
  1133. portal.NameSet = false
  1134. if portal.MXID != "" {
  1135. _, err := portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
  1136. if err != nil {
  1137. portal.log.Warnln("Failed to update room name:", err)
  1138. } else {
  1139. portal.NameSet = true
  1140. }
  1141. }
  1142. return true
  1143. }
  1144. func (portal *Portal) UpdateAvatarFromPuppet(puppet *Puppet) bool {
  1145. if portal.Avatar == puppet.Avatar && portal.AvatarSet {
  1146. return false
  1147. }
  1148. portal.Avatar = puppet.Avatar
  1149. portal.AvatarURL = puppet.AvatarURL
  1150. portal.AvatarSet = false
  1151. portal.updateRoomAvatar()
  1152. return true
  1153. }
  1154. func (portal *Portal) UpdateGroupDMAvatar(iconID string) bool {
  1155. if portal.Avatar == iconID && portal.AvatarSet {
  1156. return false
  1157. }
  1158. portal.Avatar = iconID
  1159. portal.AvatarSet = false
  1160. if portal.Avatar != "" {
  1161. uri, err := uploadAvatar(portal.MainIntent(), discordgo.EndpointGroupIcon(portal.Key.ChannelID, portal.Avatar))
  1162. if err != nil {
  1163. portal.log.Warnln("Failed to reupload avatar:", err)
  1164. return true
  1165. } else {
  1166. portal.AvatarURL = uri
  1167. }
  1168. } else {
  1169. portal.AvatarURL = id.ContentURI{}
  1170. }
  1171. portal.updateRoomAvatar()
  1172. return true
  1173. }
  1174. func (portal *Portal) updateRoomAvatar() {
  1175. if portal.MXID == "" {
  1176. return
  1177. }
  1178. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1179. if err != nil {
  1180. portal.log.Warnln("Failed to update room avatar:", err)
  1181. } else {
  1182. portal.AvatarSet = true
  1183. }
  1184. }
  1185. func (portal *Portal) UpdateTopic(topic string) bool {
  1186. if portal.Topic == topic && portal.TopicSet {
  1187. return false
  1188. }
  1189. portal.Topic = topic
  1190. portal.TopicSet = false
  1191. if portal.MXID != "" {
  1192. _, err := portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
  1193. if err != nil {
  1194. portal.log.Warnln("Failed to update room topic:", err)
  1195. }
  1196. }
  1197. return true
  1198. }
  1199. func (portal *Portal) removeFromSpace() {
  1200. if portal.InSpace == "" {
  1201. return
  1202. }
  1203. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, portal.InSpace.String(), struct{}{})
  1204. if err != nil {
  1205. portal.log.Warnfln("Failed to unset canonical space %s: %v", portal.InSpace, err)
  1206. }
  1207. _, err = portal.bridge.Bot.SendStateEvent(portal.InSpace, event.StateSpaceChild, portal.MXID.String(), struct{}{})
  1208. if err != nil {
  1209. portal.log.Warnfln("Failed to add room to space %s: %v", portal.InSpace, err)
  1210. }
  1211. portal.InSpace = ""
  1212. }
  1213. func (portal *Portal) addToSpace(mxid id.RoomID) bool {
  1214. if portal.InSpace == mxid {
  1215. return false
  1216. }
  1217. portal.removeFromSpace()
  1218. if mxid == "" {
  1219. return true
  1220. }
  1221. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, mxid.String(), &event.SpaceParentEventContent{
  1222. Via: []string{portal.bridge.AS.HomeserverDomain},
  1223. Canonical: true,
  1224. })
  1225. if err != nil {
  1226. portal.log.Warnfln("Failed to set canonical space %s: %v", mxid, err)
  1227. }
  1228. _, err = portal.bridge.Bot.SendStateEvent(mxid, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1229. Via: []string{portal.bridge.AS.HomeserverDomain},
  1230. // TODO order
  1231. })
  1232. if err != nil {
  1233. portal.log.Warnfln("Failed to add room to space %s: %v", mxid, err)
  1234. } else {
  1235. portal.InSpace = mxid
  1236. }
  1237. return true
  1238. }
  1239. func (portal *Portal) UpdateParent(parentID string) bool {
  1240. if portal.ParentID == parentID {
  1241. return false
  1242. }
  1243. portal.ParentID = parentID
  1244. if portal.ParentID != "" {
  1245. portal.Parent = portal.bridge.GetPortalByID(database.NewPortalKey(parentID, ""), discordgo.ChannelTypeGuildCategory)
  1246. } else {
  1247. portal.Parent = nil
  1248. }
  1249. return true
  1250. }
  1251. func (portal *Portal) ExpectedSpaceID() id.RoomID {
  1252. if portal.Parent != nil {
  1253. return portal.Parent.MXID
  1254. } else if portal.Guild != nil {
  1255. return portal.Guild.MXID
  1256. }
  1257. return ""
  1258. }
  1259. func (portal *Portal) updateSpace() bool {
  1260. if portal.MXID == "" {
  1261. return false
  1262. }
  1263. if portal.Parent != nil {
  1264. return portal.addToSpace(portal.Parent.MXID)
  1265. } else if portal.Guild != nil {
  1266. return portal.addToSpace(portal.Guild.MXID)
  1267. }
  1268. return false
  1269. }
  1270. func (portal *Portal) UpdateInfo(source *User, meta *discordgo.Channel) *discordgo.Channel {
  1271. changed := false
  1272. if portal.Type != meta.Type {
  1273. portal.log.Warnfln("Portal type changed from %d to %d", portal.Type, meta.Type)
  1274. portal.Type = meta.Type
  1275. changed = true
  1276. }
  1277. if portal.OtherUserID == "" && portal.IsPrivateChat() {
  1278. if len(meta.Recipients) == 0 {
  1279. var err error
  1280. meta, err = source.Session.Channel(meta.ID)
  1281. if err != nil {
  1282. portal.log.Errorfln("Failed to get DM channel info:", err)
  1283. }
  1284. }
  1285. portal.OtherUserID = meta.Recipients[0].ID
  1286. portal.log.Infoln("Found other user ID:", portal.OtherUserID)
  1287. changed = true
  1288. }
  1289. if meta.GuildID != "" && portal.GuildID == "" {
  1290. portal.GuildID = meta.GuildID
  1291. portal.Guild = portal.bridge.GetGuildByID(portal.GuildID, true)
  1292. changed = true
  1293. }
  1294. // FIXME
  1295. //name, err := portal.bridge.Config.Bridge.FormatChannelname(meta, source.Session)
  1296. //if err != nil {
  1297. // portal.log.Errorln("Failed to format channel name:", err)
  1298. // return
  1299. //}
  1300. switch portal.Type {
  1301. case discordgo.ChannelTypeDM:
  1302. if portal.OtherUserID != "" {
  1303. puppet := portal.bridge.GetPuppetByID(portal.OtherUserID)
  1304. changed = portal.UpdateAvatarFromPuppet(puppet) || changed
  1305. changed = portal.UpdateName(puppet.Name) || changed
  1306. }
  1307. case discordgo.ChannelTypeGroupDM:
  1308. changed = portal.UpdateGroupDMAvatar(meta.Icon) || changed
  1309. fallthrough
  1310. default:
  1311. changed = portal.UpdateName(meta.Name) || changed
  1312. }
  1313. changed = portal.UpdateTopic(meta.Topic) || changed
  1314. changed = portal.UpdateParent(meta.ParentID) || changed
  1315. if portal.MXID != "" && portal.ExpectedSpaceID() != portal.InSpace {
  1316. changed = portal.updateSpace() || changed
  1317. }
  1318. if changed {
  1319. portal.UpdateBridgeInfo()
  1320. portal.Update()
  1321. }
  1322. return meta
  1323. }