formatter.go 5.5 KB

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