formatting.go 5.2 KB

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