formatter.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. var matrixHTMLParser = &format.HTMLParser{
  86. TabsToSpaces: 4,
  87. Newline: "\n",
  88. HorizontalLine: "\n---\n",
  89. ItalicConverter: func(s string, context format.Context) string {
  90. return fmt.Sprintf("*%s*", s)
  91. },
  92. UnderlineConverter: func(s string, context format.Context) string {
  93. return fmt.Sprintf("__%s__", s)
  94. },
  95. TextConverter: func(s string, context format.Context) string {
  96. return discordMarkdownEscaper.Replace(s)
  97. },
  98. SpoilerConverter: func(text, reason string, ctx format.Context) string {
  99. if reason != "" {
  100. return fmt.Sprintf("(%s) ||%s||", reason, text)
  101. }
  102. return fmt.Sprintf("||%s||", text)
  103. },
  104. }
  105. func init() {
  106. matrixHTMLParser.PillConverter = pillConverter
  107. }
  108. var discordMarkdownEscaper = strings.NewReplacer(
  109. `\`, `\\`,
  110. `_`, `\_`,
  111. `*`, `\*`,
  112. `~`, `\~`,
  113. "`", "\\`",
  114. `|`, `\|`,
  115. `<`, `\<`,
  116. )
  117. func (portal *Portal) parseMatrixHTML(user *User, content *event.MessageEventContent) string {
  118. if content.Format == event.FormatHTML && len(content.FormattedBody) > 0 {
  119. return matrixHTMLParser.Parse(content.FormattedBody, format.Context{
  120. formatterContextUserKey: user,
  121. formatterContextPortalKey: portal,
  122. })
  123. } else {
  124. return discordMarkdownEscaper.Replace(content.Body)
  125. }
  126. }