formatting.go 4.9 KB

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