formatter.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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/yuin/goldmark"
  22. "github.com/yuin/goldmark/parser"
  23. "maunium.net/go/mautrix/event"
  24. "maunium.net/go/mautrix/format"
  25. "maunium.net/go/mautrix/format/mdext"
  26. "maunium.net/go/mautrix/id"
  27. "maunium.net/go/mautrix/util/variationselector"
  28. )
  29. var discordExtensions = goldmark.WithExtensions(mdext.SimpleSpoiler, mdext.DiscordUnderline)
  30. var escapeFixer = regexp.MustCompile(`\\(__[^_]|\*\*[^*])`)
  31. func (portal *Portal) renderDiscordMarkdown(text string) event.MessageEventContent {
  32. return format.HTMLToContent(portal.renderDiscordMarkdownOnlyHTML(text))
  33. }
  34. func (portal *Portal) renderDiscordMarkdownOnlyHTML(text string) string {
  35. text = escapeFixer.ReplaceAllStringFunc(text, func(s string) string {
  36. return s[:2] + `\` + s[2:]
  37. })
  38. mdRenderer := goldmark.New(
  39. goldmark.WithParser(mdext.ParserWithoutFeatures(
  40. parser.NewListParser(), parser.NewListItemParser(), parser.NewHTMLBlockParser(), parser.NewRawHTMLParser(),
  41. )),
  42. format.Extensions, format.HTMLOptions, discordExtensions,
  43. goldmark.WithExtensions(&DiscordTag{portal}),
  44. )
  45. var buf strings.Builder
  46. err := mdRenderer.Convert([]byte(text), &buf)
  47. if err != nil {
  48. panic(fmt.Errorf("markdown parser errored: %w", err))
  49. }
  50. return format.UnwrapSingleParagraph(buf.String())
  51. }
  52. const formatterContextUserKey = "fi.mau.discord.user"
  53. const formatterContextPortalKey = "fi.mau.discord.portal"
  54. func pillConverter(displayname, mxid, eventID string, ctx format.Context) string {
  55. if len(mxid) == 0 {
  56. return displayname
  57. }
  58. user := ctx.ReturnData[formatterContextUserKey].(*User)
  59. if mxid[0] == '#' {
  60. alias, err := user.bridge.Bot.ResolveAlias(id.RoomAlias(mxid))
  61. if err != nil {
  62. return displayname
  63. }
  64. mxid = alias.RoomID.String()
  65. }
  66. if mxid[0] == '!' {
  67. portal := user.bridge.GetPortalByMXID(id.RoomID(mxid))
  68. if portal != nil {
  69. if eventID == "" {
  70. //currentPortal := ctx[formatterContextPortalKey].(*Portal)
  71. return fmt.Sprintf("<#%s>", portal.Key.ChannelID)
  72. //if currentPortal.GuildID == portal.GuildID {
  73. //} else if portal.GuildID != "" {
  74. // return fmt.Sprintf("<#%s:%s:%s>", portal.Key.ChannelID, portal.GuildID, portal.Name)
  75. //} else {
  76. // // TODO is mentioning private channels possible at all?
  77. //}
  78. } else if msg := user.bridge.DB.Message.GetByMXID(portal.Key, id.EventID(eventID)); msg != nil {
  79. guildID := portal.GuildID
  80. if guildID == "" {
  81. guildID = "@me"
  82. }
  83. return fmt.Sprintf("https://discord.com/channels/%s/%s/%s", guildID, msg.DiscordProtoChannelID(), msg.DiscordID)
  84. }
  85. }
  86. } else if mxid[0] == '@' {
  87. parsedID, ok := user.bridge.ParsePuppetMXID(id.UserID(mxid))
  88. if ok {
  89. return fmt.Sprintf("<@%s>", parsedID)
  90. }
  91. mentionedUser := user.bridge.GetUserByMXID(id.UserID(mxid))
  92. if mentionedUser != nil && mentionedUser.DiscordID != "" {
  93. return fmt.Sprintf("<@%s>", mentionedUser.DiscordID)
  94. }
  95. }
  96. return displayname
  97. }
  98. // Discord links start with http:// or https://, contain at least two characters afterwards,
  99. // don't contain < or whitespace anywhere, and don't end with "'),.:;]
  100. //
  101. // Zero-width whitespace is mostly in the Format category and is allowed, except \uFEFF isn't for some reason
  102. var discordLinkRegex = regexp.MustCompile(`https?://[^<\p{Zs}\x{feff}]*[^"'),.:;\]\p{Zs}\x{feff}]`)
  103. var discordMarkdownEscaper = strings.NewReplacer(
  104. `\`, `\\`,
  105. `_`, `\_`,
  106. `*`, `\*`,
  107. `~`, `\~`,
  108. "`", "\\`",
  109. `|`, `\|`,
  110. `<`, `\<`,
  111. )
  112. func escapeDiscordMarkdown(s string) string {
  113. submatches := discordLinkRegex.FindAllStringIndex(s, -1)
  114. if submatches == nil {
  115. return discordMarkdownEscaper.Replace(s)
  116. }
  117. var builder strings.Builder
  118. offset := 0
  119. for _, match := range submatches {
  120. start := match[0]
  121. end := match[1]
  122. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:start]))
  123. builder.WriteString(s[start:end])
  124. offset = end
  125. }
  126. builder.WriteString(discordMarkdownEscaper.Replace(s[offset:]))
  127. return builder.String()
  128. }
  129. var matrixHTMLParser = &format.HTMLParser{
  130. TabsToSpaces: 4,
  131. Newline: "\n",
  132. HorizontalLine: "\n---\n",
  133. ItalicConverter: func(s string, ctx format.Context) string {
  134. return fmt.Sprintf("*%s*", s)
  135. },
  136. UnderlineConverter: func(s string, ctx format.Context) string {
  137. return fmt.Sprintf("__%s__", s)
  138. },
  139. TextConverter: func(s string, ctx format.Context) string {
  140. if ctx.TagStack.Has("pre") || ctx.TagStack.Has("code") {
  141. // If we're in a code block, don't escape markdown
  142. return s
  143. }
  144. return escapeDiscordMarkdown(s)
  145. },
  146. SpoilerConverter: func(text, reason string, ctx format.Context) string {
  147. if reason != "" {
  148. return fmt.Sprintf("(%s) ||%s||", reason, text)
  149. }
  150. return fmt.Sprintf("||%s||", text)
  151. },
  152. }
  153. func init() {
  154. matrixHTMLParser.PillConverter = pillConverter
  155. }
  156. func (portal *Portal) parseMatrixHTML(user *User, content *event.MessageEventContent) string {
  157. if content.Format == event.FormatHTML && len(content.FormattedBody) > 0 {
  158. ctx := format.NewContext()
  159. ctx.ReturnData[formatterContextUserKey] = user
  160. ctx.ReturnData[formatterContextPortalKey] = portal
  161. return variationselector.Remove(matrixHTMLParser.Parse(content.FormattedBody, ctx))
  162. } else {
  163. return variationselector.Remove(escapeDiscordMarkdown(content.Body))
  164. }
  165. }