formatter.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "fmt"
  19. "regexp"
  20. "strings"
  21. "github.com/bwmarrin/discordgo"
  22. "github.com/yuin/goldmark"
  23. "github.com/yuin/goldmark/parser"
  24. "maunium.net/go/mautrix/event"
  25. "maunium.net/go/mautrix/format"
  26. "maunium.net/go/mautrix/format/mdext"
  27. "maunium.net/go/mautrix/id"
  28. )
  29. var discordExtensions = goldmark.WithExtensions(mdext.SimpleSpoiler, mdext.DiscordUnderline)
  30. var escapeFixer = regexp.MustCompile(`\\(__[^_]|\*\*[^*])`)
  31. const msgInteractionTemplate = `> <@%s> used /%s
  32. `
  33. func (portal *Portal) renderDiscordMarkdown(text string, interaction *discordgo.MessageInteraction) event.MessageEventContent {
  34. if interaction != nil {
  35. text = fmt.Sprintf(msgInteractionTemplate, interaction.User.ID, interaction.Name) + text
  36. }
  37. return format.HTMLToContent(portal.renderDiscordMarkdownOnlyHTML(text))
  38. }
  39. func (portal *Portal) renderDiscordMarkdownOnlyHTML(text string) string {
  40. text = escapeFixer.ReplaceAllStringFunc(text, func(s string) string {
  41. return s[:2] + `\` + s[2:]
  42. })
  43. mdRenderer := goldmark.New(
  44. goldmark.WithParser(mdext.ParserWithoutFeatures(
  45. parser.NewListParser(), parser.NewListItemParser(), parser.NewHTMLBlockParser(), parser.NewRawHTMLParser(),
  46. )),
  47. format.Extensions, format.HTMLOptions, discordExtensions,
  48. goldmark.WithExtensions(&DiscordTag{portal}),
  49. )
  50. var buf strings.Builder
  51. err := mdRenderer.Convert([]byte(text), &buf)
  52. if err != nil {
  53. panic(fmt.Errorf("markdown parser errored: %w", err))
  54. }
  55. return format.UnwrapSingleParagraph(buf.String())
  56. }
  57. const formatterContextUserKey = "fi.mau.discord.user"
  58. const formatterContextPortalKey = "fi.mau.discord.portal"
  59. func pillConverter(displayname, mxid, eventID string, ctx format.Context) string {
  60. if len(mxid) == 0 {
  61. return displayname
  62. }
  63. user := ctx.ReturnData[formatterContextUserKey].(*User)
  64. if mxid[0] == '#' {
  65. alias, err := user.bridge.Bot.ResolveAlias(id.RoomAlias(mxid))
  66. if err != nil {
  67. return displayname
  68. }
  69. mxid = alias.RoomID.String()
  70. }
  71. if mxid[0] == '!' {
  72. portal := user.bridge.GetPortalByMXID(id.RoomID(mxid))
  73. if portal != nil {
  74. if eventID == "" {
  75. //currentPortal := ctx[formatterContextPortalKey].(*Portal)
  76. return fmt.Sprintf("<#%s>", portal.Key.ChannelID)
  77. //if currentPortal.GuildID == portal.GuildID {
  78. //} else if portal.GuildID != "" {
  79. // return fmt.Sprintf("<#%s:%s:%s>", portal.Key.ChannelID, portal.GuildID, portal.Name)
  80. //} else {
  81. // // TODO is mentioning private channels possible at all?
  82. //}
  83. } else if msg := user.bridge.DB.Message.GetByMXID(portal.Key, id.EventID(eventID)); msg != nil {
  84. guildID := portal.GuildID
  85. if guildID == "" {
  86. guildID = "@me"
  87. }
  88. return fmt.Sprintf("https://discord.com/channels/%s/%s/%s", guildID, msg.DiscordProtoChannelID(), msg.DiscordID)
  89. }
  90. }
  91. } else if mxid[0] == '@' {
  92. parsedID, ok := user.bridge.ParsePuppetMXID(id.UserID(mxid))
  93. if ok {
  94. return fmt.Sprintf("<@%s>", parsedID)
  95. }
  96. mentionedUser := user.bridge.GetUserByMXID(id.UserID(mxid))
  97. if mentionedUser != nil && mentionedUser.DiscordID != "" {
  98. return fmt.Sprintf("<@%s>", mentionedUser.DiscordID)
  99. }
  100. }
  101. return displayname
  102. }
  103. // Discord links start with http:// or https://, contain at least two characters afterwards,
  104. // don't contain < or whitespace anywhere, and don't end with "'),.:;]
  105. //
  106. // Zero-width whitespace is mostly in the Format category and is allowed, except \uFEFF isn't for some reason
  107. var discordLinkRegex = regexp.MustCompile(`https?://[^<\p{Zs}\x{feff}]*[^"'),.:;\]\p{Zs}\x{feff}]`)
  108. var discordMarkdownEscaper = strings.NewReplacer(
  109. `\`, `\\`,
  110. `_`, `\_`,
  111. `*`, `\*`,
  112. `~`, `\~`,
  113. "`", "\\`",
  114. `|`, `\|`,
  115. `<`, `\<`,
  116. )
  117. func escapeDiscordMarkdown(s string) string {
  118. submatches := discordLinkRegex.FindAllStringIndex(s, -1)
  119. if submatches == nil {
  120. return discordMarkdownEscaper.Replace(s)
  121. }
  122. var builder strings.Builder
  123. offset := 0
  124. for _, match := range submatches {
  125. start := match[0]
  126. end := match[1]
  127. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:start]))
  128. builder.WriteString(s[start:end])
  129. offset = end
  130. }
  131. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:]))
  132. return builder.String()
  133. }
  134. var matrixHTMLParser = &format.HTMLParser{
  135. TabsToSpaces: 4,
  136. Newline: "\n",
  137. HorizontalLine: "\n---\n",
  138. ItalicConverter: func(s string, ctx format.Context) string {
  139. return fmt.Sprintf("*%s*", s)
  140. },
  141. UnderlineConverter: func(s string, ctx format.Context) string {
  142. return fmt.Sprintf("__%s__", s)
  143. },
  144. TextConverter: func(s string, ctx format.Context) string {
  145. if ctx.TagStack.Has("pre") || ctx.TagStack.Has("code") {
  146. // If we're in a code block, don't escape markdown
  147. return s
  148. }
  149. return escapeDiscordMarkdown(s)
  150. },
  151. SpoilerConverter: func(text, reason string, ctx format.Context) string {
  152. if reason != "" {
  153. return fmt.Sprintf("(%s) ||%s||", reason, text)
  154. }
  155. return fmt.Sprintf("||%s||", text)
  156. },
  157. }
  158. func init() {
  159. matrixHTMLParser.PillConverter = pillConverter
  160. }
  161. func (portal *Portal) parseMatrixHTML(user *User, content *event.MessageEventContent) string {
  162. if content.Format == event.FormatHTML && len(content.FormattedBody) > 0 {
  163. ctx := format.NewContext()
  164. ctx.ReturnData[formatterContextUserKey] = user
  165. ctx.ReturnData[formatterContextPortalKey] = portal
  166. return matrixHTMLParser.Parse(content.FormattedBody, ctx)
  167. } else {
  168. return escapeDiscordMarkdown(content.Body)
  169. }
  170. }