formatting.go 5.0 KB

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