formatter.go 5.1 KB

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