formatter.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2023 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/extension"
  24. "github.com/yuin/goldmark/parser"
  25. "github.com/yuin/goldmark/util"
  26. "maunium.net/go/mautrix/event"
  27. "maunium.net/go/mautrix/format"
  28. "maunium.net/go/mautrix/format/mdext"
  29. "maunium.net/go/mautrix/id"
  30. "maunium.net/go/mautrix/util/variationselector"
  31. )
  32. // escapeFixer is a hacky partial fix for the difference in escaping markdown, used with escapeReplacement
  33. //
  34. // Discord allows escaping with just one backslash, e.g. \__a__,
  35. // but standard markdown requires both to be escaped (\_\_a__)
  36. var escapeFixer = regexp.MustCompile(`\\(__[^_]|\*\*[^*])`)
  37. func escapeReplacement(s string) string {
  38. return s[:2] + `\` + s[2:]
  39. }
  40. // indentableParagraphParser is the default paragraph parser with CanAcceptIndentedLine.
  41. // Used when disabling CodeBlockParser (as disabling it without a replacement will make indented blocks disappear).
  42. type indentableParagraphParser struct {
  43. parser.BlockParser
  44. }
  45. var defaultIndentableParagraphParser = &indentableParagraphParser{BlockParser: parser.NewParagraphParser()}
  46. func (b *indentableParagraphParser) CanAcceptIndentedLine() bool {
  47. return true
  48. }
  49. var removeFeaturesExceptLinks = []any{
  50. parser.NewListParser(), parser.NewListItemParser(), parser.NewHTMLBlockParser(), parser.NewRawHTMLParser(),
  51. parser.NewSetextHeadingParser(), parser.NewATXHeadingParser(), parser.NewThematicBreakParser(),
  52. parser.NewCodeBlockParser(),
  53. }
  54. var removeFeaturesAndLinks = append(removeFeaturesExceptLinks, parser.NewLinkParser())
  55. var fixIndentedParagraphs = goldmark.WithParserOptions(parser.WithBlockParsers(util.Prioritized(defaultIndentableParagraphParser, 500)))
  56. var discordExtensions = goldmark.WithExtensions(extension.Strikethrough, mdext.SimpleSpoiler, mdext.DiscordUnderline, ExtDiscordEveryone, ExtDiscordTag)
  57. var discordRenderer = goldmark.New(
  58. goldmark.WithParser(mdext.ParserWithoutFeatures(removeFeaturesAndLinks...)),
  59. fixIndentedParagraphs, format.HTMLOptions, discordExtensions,
  60. )
  61. var discordRendererWithInlineLinks = goldmark.New(
  62. goldmark.WithParser(mdext.ParserWithoutFeatures(removeFeaturesExceptLinks...)),
  63. fixIndentedParagraphs, format.HTMLOptions, discordExtensions,
  64. )
  65. func (portal *Portal) renderDiscordMarkdownOnlyHTML(text string, allowInlineLinks bool) string {
  66. text = escapeFixer.ReplaceAllStringFunc(text, escapeReplacement)
  67. var buf strings.Builder
  68. ctx := parser.NewContext()
  69. ctx.Set(parserContextPortal, portal)
  70. renderer := discordRenderer
  71. if allowInlineLinks {
  72. renderer = discordRendererWithInlineLinks
  73. }
  74. err := renderer.Convert([]byte(text), &buf, parser.WithContext(ctx))
  75. if err != nil {
  76. panic(fmt.Errorf("markdown parser errored: %w", err))
  77. }
  78. return format.UnwrapSingleParagraph(buf.String())
  79. }
  80. const formatterContextPortalKey = "fi.mau.discord.portal"
  81. const formatterContextAllowedMentionsKey = "fi.mau.discord.allowed_mentions"
  82. func appendIfNotContains(arr []string, newItem string) []string {
  83. for _, item := range arr {
  84. if item == newItem {
  85. return arr
  86. }
  87. }
  88. return append(arr, newItem)
  89. }
  90. func (br *DiscordBridge) pillConverter(displayname, mxid, eventID string, ctx format.Context) string {
  91. if len(mxid) == 0 {
  92. return displayname
  93. }
  94. if mxid[0] == '#' {
  95. alias, err := br.Bot.ResolveAlias(id.RoomAlias(mxid))
  96. if err != nil {
  97. return displayname
  98. }
  99. mxid = alias.RoomID.String()
  100. }
  101. if mxid[0] == '!' {
  102. portal := br.GetPortalByMXID(id.RoomID(mxid))
  103. if portal != nil {
  104. if eventID == "" {
  105. //currentPortal := ctx[formatterContextPortalKey].(*Portal)
  106. return fmt.Sprintf("<#%s>", portal.Key.ChannelID)
  107. //if currentPortal.GuildID == portal.GuildID {
  108. //} else if portal.GuildID != "" {
  109. // return fmt.Sprintf("<#%s:%s:%s>", portal.Key.ChannelID, portal.GuildID, portal.Name)
  110. //} else {
  111. // // TODO is mentioning private channels possible at all?
  112. //}
  113. } else if msg := br.DB.Message.GetByMXID(portal.Key, id.EventID(eventID)); msg != nil {
  114. guildID := portal.GuildID
  115. if guildID == "" {
  116. guildID = "@me"
  117. }
  118. return fmt.Sprintf("https://discord.com/channels/%s/%s/%s", guildID, msg.DiscordProtoChannelID(), msg.DiscordID)
  119. }
  120. }
  121. } else if mxid[0] == '@' {
  122. mentions := ctx.ReturnData[formatterContextAllowedMentionsKey].(*discordgo.MessageAllowedMentions)
  123. parsedID, ok := br.ParsePuppetMXID(id.UserID(mxid))
  124. if ok {
  125. mentions.Users = appendIfNotContains(mentions.Users, parsedID)
  126. return fmt.Sprintf("<@%s>", parsedID)
  127. }
  128. mentionedUser := br.GetUserByMXID(id.UserID(mxid))
  129. if mentionedUser != nil && mentionedUser.DiscordID != "" {
  130. mentions.Users = appendIfNotContains(mentions.Users, mentionedUser.DiscordID)
  131. return fmt.Sprintf("<@%s>", mentionedUser.DiscordID)
  132. }
  133. }
  134. return displayname
  135. }
  136. // Discord links start with http:// or https://, contain at least two characters afterwards,
  137. // don't contain < or whitespace anywhere, and don't end with "'),.:;]
  138. //
  139. // Zero-width whitespace is mostly in the Format category and is allowed, except \uFEFF isn't for some reason
  140. var discordLinkRegex = regexp.MustCompile(`https?://[^<\p{Zs}\x{feff}]*[^"'),.:;\]\p{Zs}\x{feff}]`)
  141. var discordMarkdownEscaper = strings.NewReplacer(
  142. `\`, `\\`,
  143. `_`, `\_`,
  144. `*`, `\*`,
  145. `~`, `\~`,
  146. "`", "\\`",
  147. `|`, `\|`,
  148. `<`, `\<`,
  149. )
  150. func escapeDiscordMarkdown(s string) string {
  151. submatches := discordLinkRegex.FindAllStringIndex(s, -1)
  152. if submatches == nil {
  153. return discordMarkdownEscaper.Replace(s)
  154. }
  155. var builder strings.Builder
  156. offset := 0
  157. for _, match := range submatches {
  158. start := match[0]
  159. end := match[1]
  160. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:start]))
  161. builder.WriteString(s[start:end])
  162. offset = end
  163. }
  164. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:]))
  165. return builder.String()
  166. }
  167. var matrixHTMLParser = &format.HTMLParser{
  168. TabsToSpaces: 4,
  169. Newline: "\n",
  170. HorizontalLine: "\n---\n",
  171. ItalicConverter: func(s string, ctx format.Context) string {
  172. return fmt.Sprintf("*%s*", s)
  173. },
  174. UnderlineConverter: func(s string, ctx format.Context) string {
  175. return fmt.Sprintf("__%s__", s)
  176. },
  177. TextConverter: func(s string, ctx format.Context) string {
  178. if ctx.TagStack.Has("pre") || ctx.TagStack.Has("code") {
  179. // If we're in a code block, don't escape markdown
  180. return s
  181. }
  182. return escapeDiscordMarkdown(s)
  183. },
  184. SpoilerConverter: func(text, reason string, ctx format.Context) string {
  185. if reason != "" {
  186. return fmt.Sprintf("(%s) ||%s||", reason, text)
  187. }
  188. return fmt.Sprintf("||%s||", text)
  189. },
  190. }
  191. func (portal *Portal) parseMatrixHTML(content *event.MessageEventContent) (string, *discordgo.MessageAllowedMentions) {
  192. allowedMentions := &discordgo.MessageAllowedMentions{
  193. Parse: []discordgo.AllowedMentionType{},
  194. Users: []string{},
  195. RepliedUser: true,
  196. }
  197. if content.Format == event.FormatHTML && len(content.FormattedBody) > 0 {
  198. ctx := format.NewContext()
  199. ctx.ReturnData[formatterContextPortalKey] = portal
  200. ctx.ReturnData[formatterContextAllowedMentionsKey] = allowedMentions
  201. return variationselector.FullyQualify(matrixHTMLParser.Parse(content.FormattedBody, ctx)), allowedMentions
  202. } else {
  203. return variationselector.FullyQualify(escapeDiscordMarkdown(content.Body)), allowedMentions
  204. }
  205. }