formatter.go 5.7 KB

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