formatter.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 formatterContextPortalKey = "fi.mau.discord.portal"
  80. func (br *DiscordBridge) pillConverter(displayname, mxid, eventID string, ctx format.Context) string {
  81. if len(mxid) == 0 {
  82. return displayname
  83. }
  84. if mxid[0] == '#' {
  85. alias, err := br.Bot.ResolveAlias(id.RoomAlias(mxid))
  86. if err != nil {
  87. return displayname
  88. }
  89. mxid = alias.RoomID.String()
  90. }
  91. if mxid[0] == '!' {
  92. portal := br.GetPortalByMXID(id.RoomID(mxid))
  93. if portal != nil {
  94. if eventID == "" {
  95. //currentPortal := ctx[formatterContextPortalKey].(*Portal)
  96. return fmt.Sprintf("<#%s>", portal.Key.ChannelID)
  97. //if currentPortal.GuildID == portal.GuildID {
  98. //} else if portal.GuildID != "" {
  99. // return fmt.Sprintf("<#%s:%s:%s>", portal.Key.ChannelID, portal.GuildID, portal.Name)
  100. //} else {
  101. // // TODO is mentioning private channels possible at all?
  102. //}
  103. } else if msg := br.DB.Message.GetByMXID(portal.Key, id.EventID(eventID)); msg != nil {
  104. guildID := portal.GuildID
  105. if guildID == "" {
  106. guildID = "@me"
  107. }
  108. return fmt.Sprintf("https://discord.com/channels/%s/%s/%s", guildID, msg.DiscordProtoChannelID(), msg.DiscordID)
  109. }
  110. }
  111. } else if mxid[0] == '@' {
  112. parsedID, ok := br.ParsePuppetMXID(id.UserID(mxid))
  113. if ok {
  114. return fmt.Sprintf("<@%s>", parsedID)
  115. }
  116. mentionedUser := br.GetUserByMXID(id.UserID(mxid))
  117. if mentionedUser != nil && mentionedUser.DiscordID != "" {
  118. return fmt.Sprintf("<@%s>", mentionedUser.DiscordID)
  119. }
  120. }
  121. return displayname
  122. }
  123. // Discord links start with http:// or https://, contain at least two characters afterwards,
  124. // don't contain < or whitespace anywhere, and don't end with "'),.:;]
  125. //
  126. // Zero-width whitespace is mostly in the Format category and is allowed, except \uFEFF isn't for some reason
  127. var discordLinkRegex = regexp.MustCompile(`https?://[^<\p{Zs}\x{feff}]*[^"'),.:;\]\p{Zs}\x{feff}]`)
  128. var discordMarkdownEscaper = strings.NewReplacer(
  129. `\`, `\\`,
  130. `_`, `\_`,
  131. `*`, `\*`,
  132. `~`, `\~`,
  133. "`", "\\`",
  134. `|`, `\|`,
  135. `<`, `\<`,
  136. )
  137. func escapeDiscordMarkdown(s string) string {
  138. submatches := discordLinkRegex.FindAllStringIndex(s, -1)
  139. if submatches == nil {
  140. return discordMarkdownEscaper.Replace(s)
  141. }
  142. var builder strings.Builder
  143. offset := 0
  144. for _, match := range submatches {
  145. start := match[0]
  146. end := match[1]
  147. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:start]))
  148. builder.WriteString(s[start:end])
  149. offset = end
  150. }
  151. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:]))
  152. return builder.String()
  153. }
  154. var matrixHTMLParser = &format.HTMLParser{
  155. TabsToSpaces: 4,
  156. Newline: "\n",
  157. HorizontalLine: "\n---\n",
  158. ItalicConverter: func(s string, ctx format.Context) string {
  159. return fmt.Sprintf("*%s*", s)
  160. },
  161. UnderlineConverter: func(s string, ctx format.Context) string {
  162. return fmt.Sprintf("__%s__", s)
  163. },
  164. TextConverter: func(s string, ctx format.Context) string {
  165. if ctx.TagStack.Has("pre") || ctx.TagStack.Has("code") {
  166. // If we're in a code block, don't escape markdown
  167. return s
  168. }
  169. return escapeDiscordMarkdown(s)
  170. },
  171. SpoilerConverter: func(text, reason string, ctx format.Context) string {
  172. if reason != "" {
  173. return fmt.Sprintf("(%s) ||%s||", reason, text)
  174. }
  175. return fmt.Sprintf("||%s||", text)
  176. },
  177. }
  178. func (portal *Portal) parseMatrixHTML(content *event.MessageEventContent) string {
  179. if content.Format == event.FormatHTML && len(content.FormattedBody) > 0 {
  180. ctx := format.NewContext()
  181. ctx.ReturnData[formatterContextPortalKey] = portal
  182. return variationselector.FullyQualify(matrixHTMLParser.Parse(content.FormattedBody, ctx))
  183. } else {
  184. return variationselector.FullyQualify(escapeDiscordMarkdown(content.Body))
  185. }
  186. }