message.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 database
  17. import (
  18. "bytes"
  19. "database/sql"
  20. "encoding/json"
  21. "strings"
  22. "time"
  23. "github.com/Rhymen/go-whatsapp"
  24. waProto "github.com/Rhymen/go-whatsapp/binary/proto"
  25. log "maunium.net/go/maulogger/v2"
  26. "maunium.net/go/mautrix/id"
  27. )
  28. type MessageQuery struct {
  29. db *Database
  30. log log.Logger
  31. }
  32. func (mq *MessageQuery) New() *Message {
  33. return &Message{
  34. db: mq.db,
  35. log: mq.log,
  36. }
  37. }
  38. func (mq *MessageQuery) GetAll(chat PortalKey) (messages []*Message) {
  39. rows, err := mq.db.Query("SELECT chat_jid, chat_receiver, jid, mxid, sender, timestamp, sent, content FROM message WHERE chat_jid=$1 AND chat_receiver=$2", chat.JID, chat.Receiver)
  40. if err != nil || rows == nil {
  41. return nil
  42. }
  43. defer rows.Close()
  44. for rows.Next() {
  45. messages = append(messages, mq.New().Scan(rows))
  46. }
  47. return
  48. }
  49. func (mq *MessageQuery) GetByJID(chat PortalKey, jid whatsapp.MessageID) *Message {
  50. return mq.get("SELECT chat_jid, chat_receiver, jid, mxid, sender, timestamp, sent, content "+
  51. "FROM message WHERE chat_jid=$1 AND chat_receiver=$2 AND jid=$3", chat.JID, chat.Receiver, jid)
  52. }
  53. func (mq *MessageQuery) GetByMXID(mxid id.EventID) *Message {
  54. return mq.get("SELECT chat_jid, chat_receiver, jid, mxid, sender, timestamp, sent, content "+
  55. "FROM message WHERE mxid=$1", mxid)
  56. }
  57. func (mq *MessageQuery) GetLastInChat(chat PortalKey) *Message {
  58. return mq.GetLastInChatBefore(chat, time.Now().Unix()+60)
  59. }
  60. func (mq *MessageQuery) GetLastInChatBefore(chat PortalKey, maxTimestamp int64) *Message {
  61. msg := mq.get("SELECT chat_jid, chat_receiver, jid, mxid, sender, timestamp, sent, content "+
  62. "FROM message WHERE chat_jid=$1 AND chat_receiver=$2 AND timestamp<=$3 AND sent=true ORDER BY timestamp DESC LIMIT 1",
  63. chat.JID, chat.Receiver, maxTimestamp)
  64. if msg == nil || msg.Timestamp == 0 {
  65. // Old db, we don't know what the last message is.
  66. return nil
  67. }
  68. return msg
  69. }
  70. func (mq *MessageQuery) get(query string, args ...interface{}) *Message {
  71. row := mq.db.QueryRow(query, args...)
  72. if row == nil {
  73. return nil
  74. }
  75. return mq.New().Scan(row)
  76. }
  77. type Message struct {
  78. db *Database
  79. log log.Logger
  80. Chat PortalKey
  81. JID whatsapp.MessageID
  82. MXID id.EventID
  83. Sender whatsapp.JID
  84. Timestamp int64
  85. Sent bool
  86. Content *waProto.Message
  87. }
  88. func (msg *Message) IsFakeMXID() bool {
  89. return strings.HasPrefix(msg.MXID.String(), "net.maunium.whatsapp.fake::")
  90. }
  91. func (msg *Message) Scan(row Scannable) *Message {
  92. var content []byte
  93. err := row.Scan(&msg.Chat.JID, &msg.Chat.Receiver, &msg.JID, &msg.MXID, &msg.Sender, &msg.Timestamp, &msg.Sent, &content)
  94. if err != nil {
  95. if err != sql.ErrNoRows {
  96. msg.log.Errorln("Database scan failed:", err)
  97. }
  98. return nil
  99. }
  100. msg.decodeBinaryContent(content)
  101. return msg
  102. }
  103. func (msg *Message) decodeBinaryContent(content []byte) {
  104. msg.Content = &waProto.Message{}
  105. reader := bytes.NewReader(content)
  106. dec := json.NewDecoder(reader)
  107. err := dec.Decode(msg.Content)
  108. if err != nil {
  109. msg.log.Warnln("Failed to decode message content:", err)
  110. }
  111. }
  112. func (msg *Message) encodeBinaryContent() []byte {
  113. var buf bytes.Buffer
  114. enc := json.NewEncoder(&buf)
  115. err := enc.Encode(msg.Content)
  116. if err != nil {
  117. msg.log.Warnln("Failed to encode message content:", err)
  118. }
  119. return buf.Bytes()
  120. }
  121. func (msg *Message) Insert() {
  122. _, err := msg.db.Exec(`INSERT INTO message
  123. (chat_jid, chat_receiver, jid, mxid, sender, timestamp, sent, content)
  124. VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
  125. msg.Chat.JID, msg.Chat.Receiver, msg.JID, msg.MXID, msg.Sender, msg.Timestamp, msg.Sent, msg.encodeBinaryContent())
  126. if err != nil {
  127. msg.log.Warnfln("Failed to insert %s@%s: %v", msg.Chat, msg.JID, err)
  128. }
  129. }
  130. func (msg *Message) MarkSent() {
  131. msg.Sent = true
  132. _, err := msg.db.Exec("UPDATE message SET sent=true WHERE chat_jid=$1 AND chat_receiver=$2 AND jid=$3", msg.Chat.JID, msg.Chat.Receiver, msg.JID)
  133. if err != nil {
  134. msg.log.Warnfln("Failed to update %s@%s: %v", msg.Chat, msg.JID, err)
  135. }
  136. }
  137. func (msg *Message) Delete() {
  138. _, err := msg.db.Exec("DELETE FROM message WHERE chat_jid=$1 AND chat_receiver=$2 AND jid=$3", msg.Chat.JID, msg.Chat.Receiver, msg.JID)
  139. if err != nil {
  140. msg.log.Warnfln("Failed to delete %s@%s: %v", msg.Chat, msg.JID, err)
  141. }
  142. }