portal.go 44 KB

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