formatting.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "html"
  20. "regexp"
  21. "strings"
  22. "go.mau.fi/whatsmeow/types"
  23. "maunium.net/go/mautrix/event"
  24. "maunium.net/go/mautrix/format"
  25. "maunium.net/go/mautrix/id"
  26. )
  27. var italicRegex = regexp.MustCompile("([\\s>~*]|^)_(.+?)_([^a-zA-Z\\d]|$)")
  28. var boldRegex = regexp.MustCompile("([\\s>_~]|^)\\*(.+?)\\*([^a-zA-Z\\d]|$)")
  29. var strikethroughRegex = regexp.MustCompile("([\\s>_*]|^)~(.+?)~([^a-zA-Z\\d]|$)")
  30. var codeBlockRegex = regexp.MustCompile("```(?:.|\n)+?```")
  31. var inlineURLRegex = regexp.MustCompile(`\[(.+?)]\((.+?)\)`)
  32. const mentionedJIDsContextKey = "fi.mau.whatsapp.mentioned_jids"
  33. const disableMentionsContextKey = "fi.mau.whatsapp.no_mentions"
  34. type Formatter struct {
  35. bridge *WABridge
  36. matrixHTMLParser *format.HTMLParser
  37. waReplString map[*regexp.Regexp]string
  38. waReplFunc map[*regexp.Regexp]func(string) string
  39. waReplFuncText map[*regexp.Regexp]func(string) string
  40. }
  41. func NewFormatter(bridge *WABridge) *Formatter {
  42. formatter := &Formatter{
  43. bridge: bridge,
  44. matrixHTMLParser: &format.HTMLParser{
  45. TabsToSpaces: 4,
  46. Newline: "\n",
  47. PillConverter: func(displayname, mxid, eventID string, ctx format.Context) string {
  48. _, disableMentions := ctx.ReturnData[disableMentionsContextKey]
  49. if mxid[0] == '@' && !disableMentions {
  50. puppet := bridge.GetPuppetByMXID(id.UserID(mxid))
  51. if puppet != nil {
  52. jids, ok := ctx.ReturnData[mentionedJIDsContextKey].([]string)
  53. if !ok {
  54. ctx.ReturnData[mentionedJIDsContextKey] = []string{puppet.JID.String()}
  55. } else {
  56. ctx.ReturnData[mentionedJIDsContextKey] = append(jids, puppet.JID.String())
  57. }
  58. return "@" + puppet.JID.User
  59. }
  60. }
  61. return displayname
  62. },
  63. BoldConverter: func(text string, _ format.Context) string { return fmt.Sprintf("*%s*", text) },
  64. ItalicConverter: func(text string, _ format.Context) string { return fmt.Sprintf("_%s_", text) },
  65. StrikethroughConverter: func(text string, _ format.Context) string { return fmt.Sprintf("~%s~", text) },
  66. MonospaceConverter: func(text string, _ format.Context) string { return fmt.Sprintf("```%s```", text) },
  67. MonospaceBlockConverter: func(text, language string, _ format.Context) string { return fmt.Sprintf("```%s```", text) },
  68. },
  69. waReplString: map[*regexp.Regexp]string{
  70. italicRegex: "$1<em>$2</em>$3",
  71. boldRegex: "$1<strong>$2</strong>$3",
  72. strikethroughRegex: "$1<del>$2</del>$3",
  73. },
  74. }
  75. formatter.waReplFunc = map[*regexp.Regexp]func(string) string{
  76. codeBlockRegex: func(str string) string {
  77. str = str[3 : len(str)-3]
  78. if strings.ContainsRune(str, '\n') {
  79. return fmt.Sprintf("<pre><code>%s</code></pre>", str)
  80. }
  81. return fmt.Sprintf("<code>%s</code>", str)
  82. },
  83. }
  84. formatter.waReplFuncText = map[*regexp.Regexp]func(string) string{}
  85. return formatter
  86. }
  87. func (formatter *Formatter) getMatrixInfoByJID(roomID id.RoomID, jid types.JID) (mxid id.UserID, displayname string) {
  88. if puppet := formatter.bridge.GetPuppetByJID(jid); puppet != nil {
  89. mxid = puppet.MXID
  90. displayname = puppet.Displayname
  91. }
  92. if user := formatter.bridge.GetUserByJID(jid); user != nil {
  93. mxid = user.MXID
  94. member := formatter.bridge.StateStore.GetMember(roomID, user.MXID)
  95. if len(member.Displayname) > 0 {
  96. displayname = member.Displayname
  97. }
  98. }
  99. return
  100. }
  101. func (formatter *Formatter) ParseWhatsApp(roomID id.RoomID, content *event.MessageEventContent, mentionedJIDs []string, allowInlineURL, forceHTML bool) {
  102. output := html.EscapeString(content.Body)
  103. for regex, replacement := range formatter.waReplString {
  104. output = regex.ReplaceAllString(output, replacement)
  105. }
  106. for regex, replacer := range formatter.waReplFunc {
  107. output = regex.ReplaceAllStringFunc(output, replacer)
  108. }
  109. if allowInlineURL {
  110. output = inlineURLRegex.ReplaceAllStringFunc(output, func(s string) string {
  111. groups := inlineURLRegex.FindStringSubmatch(s)
  112. return fmt.Sprintf(`<a href="%s">%s</a>`, groups[2], groups[1])
  113. })
  114. }
  115. for _, rawJID := range mentionedJIDs {
  116. jid, err := types.ParseJID(rawJID)
  117. if err != nil {
  118. continue
  119. } else if jid.Server == types.LegacyUserServer {
  120. jid.Server = types.DefaultUserServer
  121. }
  122. mxid, displayname := formatter.getMatrixInfoByJID(roomID, jid)
  123. number := "@" + jid.User
  124. output = strings.ReplaceAll(output, number, fmt.Sprintf(`<a href="https://matrix.to/#/%s">%s</a>`, mxid, displayname))
  125. content.Body = strings.ReplaceAll(content.Body, number, displayname)
  126. }
  127. if output != content.Body || forceHTML {
  128. output = strings.ReplaceAll(output, "\n", "<br/>")
  129. content.FormattedBody = output
  130. content.Format = event.FormatHTML
  131. for regex, replacer := range formatter.waReplFuncText {
  132. content.Body = regex.ReplaceAllStringFunc(content.Body, replacer)
  133. }
  134. }
  135. }
  136. func (formatter *Formatter) ParseMatrix(html string) (string, []string) {
  137. ctx := format.NewContext()
  138. result := formatter.matrixHTMLParser.Parse(html, ctx)
  139. mentionedJIDs, _ := ctx.ReturnData[mentionedJIDsContextKey].([]string)
  140. return result, mentionedJIDs
  141. }
  142. func (formatter *Formatter) ParseMatrixWithoutMentions(html string) string {
  143. ctx := format.NewContext()
  144. ctx.ReturnData[disableMentionsContextKey] = true
  145. return formatter.matrixHTMLParser.Parse(html, ctx)
  146. }