formatter.go 7.3 KB

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