historysync.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan, Sumner Evans
  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. "database/sql"
  19. "errors"
  20. "fmt"
  21. "strings"
  22. "time"
  23. waProto "go.mau.fi/whatsmeow/binary/proto"
  24. "google.golang.org/protobuf/proto"
  25. _ "github.com/mattn/go-sqlite3"
  26. log "maunium.net/go/maulogger/v2"
  27. "maunium.net/go/mautrix/id"
  28. )
  29. type HistorySyncQuery struct {
  30. db *Database
  31. log log.Logger
  32. }
  33. type HistorySyncConversation struct {
  34. db *Database
  35. log log.Logger
  36. UserID id.UserID
  37. ConversationID string
  38. PortalKey *PortalKey
  39. LastMessageTimestamp time.Time
  40. MuteEndTime time.Time
  41. Archived bool
  42. Pinned uint32
  43. DisappearingMode waProto.DisappearingMode_DisappearingModeInitiator
  44. EndOfHistoryTransferType waProto.Conversation_ConversationEndOfHistoryTransferType
  45. EphemeralExpiration *uint32
  46. MarkedAsUnread bool
  47. UnreadCount uint32
  48. }
  49. func (hsq *HistorySyncQuery) NewConversation() *HistorySyncConversation {
  50. return &HistorySyncConversation{
  51. db: hsq.db,
  52. log: hsq.log,
  53. PortalKey: &PortalKey{},
  54. }
  55. }
  56. func (hsq *HistorySyncQuery) NewConversationWithValues(
  57. userID id.UserID,
  58. conversationID string,
  59. portalKey *PortalKey,
  60. lastMessageTimestamp,
  61. muteEndTime uint64,
  62. archived bool,
  63. pinned uint32,
  64. disappearingMode waProto.DisappearingMode_DisappearingModeInitiator,
  65. endOfHistoryTransferType waProto.Conversation_ConversationEndOfHistoryTransferType,
  66. ephemeralExpiration *uint32,
  67. markedAsUnread bool,
  68. unreadCount uint32) *HistorySyncConversation {
  69. return &HistorySyncConversation{
  70. db: hsq.db,
  71. log: hsq.log,
  72. UserID: userID,
  73. ConversationID: conversationID,
  74. PortalKey: portalKey,
  75. LastMessageTimestamp: time.Unix(int64(lastMessageTimestamp), 0),
  76. MuteEndTime: time.Unix(int64(muteEndTime), 0),
  77. Archived: archived,
  78. Pinned: pinned,
  79. DisappearingMode: disappearingMode,
  80. EndOfHistoryTransferType: endOfHistoryTransferType,
  81. EphemeralExpiration: ephemeralExpiration,
  82. MarkedAsUnread: markedAsUnread,
  83. UnreadCount: unreadCount,
  84. }
  85. }
  86. const (
  87. getNMostRecentConversations = `
  88. SELECT user_mxid, conversation_id, portal_jid, portal_receiver, last_message_timestamp, archived, pinned, mute_end_time, disappearing_mode, end_of_history_transfer_type, ephemeral_expiration, marked_as_unread, unread_count
  89. FROM history_sync_conversation
  90. WHERE user_mxid=$1
  91. ORDER BY last_message_timestamp DESC
  92. LIMIT $2
  93. `
  94. getConversationByPortal = `
  95. SELECT user_mxid, conversation_id, portal_jid, portal_receiver, last_message_timestamp, archived, pinned, mute_end_time, disappearing_mode, end_of_history_transfer_type, ephemeral_expiration, marked_as_unread, unread_count
  96. FROM history_sync_conversation
  97. WHERE user_mxid=$1
  98. AND portal_jid=$2
  99. AND portal_receiver=$3
  100. `
  101. )
  102. func (hsc *HistorySyncConversation) Upsert() {
  103. _, err := hsc.db.Exec(`
  104. INSERT INTO history_sync_conversation (user_mxid, conversation_id, portal_jid, portal_receiver, last_message_timestamp, archived, pinned, mute_end_time, disappearing_mode, end_of_history_transfer_type, ephemeral_expiration, marked_as_unread, unread_count)
  105. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
  106. ON CONFLICT (user_mxid, conversation_id)
  107. DO UPDATE SET
  108. portal_jid=EXCLUDED.portal_jid,
  109. portal_receiver=EXCLUDED.portal_receiver,
  110. last_message_timestamp=CASE
  111. WHEN EXCLUDED.last_message_timestamp > history_sync_conversation.last_message_timestamp THEN EXCLUDED.last_message_timestamp
  112. ELSE history_sync_conversation.last_message_timestamp
  113. END,
  114. archived=EXCLUDED.archived,
  115. pinned=EXCLUDED.pinned,
  116. mute_end_time=EXCLUDED.mute_end_time,
  117. disappearing_mode=EXCLUDED.disappearing_mode,
  118. end_of_history_transfer_type=EXCLUDED.end_of_history_transfer_type,
  119. ephemeral_expiration=EXCLUDED.ephemeral_expiration,
  120. marked_as_unread=EXCLUDED.marked_as_unread,
  121. unread_count=EXCLUDED.unread_count
  122. `,
  123. hsc.UserID,
  124. hsc.ConversationID,
  125. hsc.PortalKey.JID.String(),
  126. hsc.PortalKey.Receiver.String(),
  127. hsc.LastMessageTimestamp,
  128. hsc.Archived,
  129. hsc.Pinned,
  130. hsc.MuteEndTime,
  131. hsc.DisappearingMode,
  132. hsc.EndOfHistoryTransferType,
  133. hsc.EphemeralExpiration,
  134. hsc.MarkedAsUnread,
  135. hsc.UnreadCount)
  136. if err != nil {
  137. hsc.log.Warnfln("Failed to insert history sync conversation %s/%s: %v", hsc.UserID, hsc.ConversationID, err)
  138. }
  139. }
  140. func (hsc *HistorySyncConversation) Scan(row Scannable) *HistorySyncConversation {
  141. err := row.Scan(
  142. &hsc.UserID,
  143. &hsc.ConversationID,
  144. &hsc.PortalKey.JID,
  145. &hsc.PortalKey.Receiver,
  146. &hsc.LastMessageTimestamp,
  147. &hsc.Archived,
  148. &hsc.Pinned,
  149. &hsc.MuteEndTime,
  150. &hsc.DisappearingMode,
  151. &hsc.EndOfHistoryTransferType,
  152. &hsc.EphemeralExpiration,
  153. &hsc.MarkedAsUnread,
  154. &hsc.UnreadCount)
  155. if err != nil {
  156. if !errors.Is(err, sql.ErrNoRows) {
  157. hsc.log.Errorln("Database scan failed:", err)
  158. }
  159. return nil
  160. }
  161. return hsc
  162. }
  163. func (hsq *HistorySyncQuery) GetNMostRecentConversations(userID id.UserID, n int) (conversations []*HistorySyncConversation) {
  164. rows, err := hsq.db.Query(getNMostRecentConversations, userID, n)
  165. defer rows.Close()
  166. if err != nil || rows == nil {
  167. return nil
  168. }
  169. for rows.Next() {
  170. conversations = append(conversations, hsq.NewConversation().Scan(rows))
  171. }
  172. return
  173. }
  174. func (hsq *HistorySyncQuery) GetConversation(userID id.UserID, portalKey *PortalKey) (conversation *HistorySyncConversation) {
  175. rows, err := hsq.db.Query(getConversationByPortal, userID, portalKey.JID, portalKey.Receiver)
  176. defer rows.Close()
  177. if err != nil || rows == nil {
  178. return nil
  179. }
  180. if rows.Next() {
  181. conversation = hsq.NewConversation().Scan(rows)
  182. }
  183. return
  184. }
  185. func (hsq *HistorySyncQuery) DeleteAllConversations(userID id.UserID) error {
  186. _, err := hsq.db.Exec("DELETE FROM history_sync_conversation WHERE user_mxid=$1", userID)
  187. return err
  188. }
  189. const (
  190. getMessagesBetween = `
  191. SELECT data
  192. FROM history_sync_message
  193. WHERE user_mxid=$1
  194. AND conversation_id=$2
  195. %s
  196. ORDER BY timestamp DESC
  197. %s
  198. `
  199. deleteMessages = `
  200. DELETE FROM history_sync_message
  201. WHERE %s
  202. `
  203. )
  204. type HistorySyncMessage struct {
  205. db *Database
  206. log log.Logger
  207. UserID id.UserID
  208. ConversationID string
  209. MessageID string
  210. Timestamp time.Time
  211. Data []byte
  212. }
  213. func (hsq *HistorySyncQuery) NewMessageWithValues(userID id.UserID, conversationID, messageID string, message *waProto.HistorySyncMsg) (*HistorySyncMessage, error) {
  214. msgData, err := proto.Marshal(message)
  215. if err != nil {
  216. return nil, err
  217. }
  218. return &HistorySyncMessage{
  219. db: hsq.db,
  220. log: hsq.log,
  221. UserID: userID,
  222. ConversationID: conversationID,
  223. MessageID: messageID,
  224. Timestamp: time.Unix(int64(message.Message.GetMessageTimestamp()), 0),
  225. Data: msgData,
  226. }, nil
  227. }
  228. func (hsm *HistorySyncMessage) Insert() {
  229. _, err := hsm.db.Exec(`
  230. INSERT INTO history_sync_message (user_mxid, conversation_id, message_id, timestamp, data)
  231. VALUES ($1, $2, $3, $4, $5)
  232. ON CONFLICT (user_mxid, conversation_id, message_id) DO NOTHING
  233. `, hsm.UserID, hsm.ConversationID, hsm.MessageID, hsm.Timestamp, hsm.Data)
  234. if err != nil {
  235. hsm.log.Warnfln("Failed to insert history sync message %s/%s: %v", hsm.ConversationID, hsm.Timestamp, err)
  236. }
  237. }
  238. func (hsq *HistorySyncQuery) GetMessagesBetween(userID id.UserID, conversationID string, startTime, endTime *time.Time, limit int) (messages []*waProto.WebMessageInfo) {
  239. whereClauses := ""
  240. args := []interface{}{userID, conversationID}
  241. argNum := 3
  242. if startTime != nil {
  243. whereClauses += fmt.Sprintf(" AND timestamp >= $%d", argNum)
  244. args = append(args, startTime)
  245. argNum++
  246. }
  247. if endTime != nil {
  248. whereClauses += fmt.Sprintf(" AND timestamp <= $%d", argNum)
  249. args = append(args, endTime)
  250. }
  251. limitClause := ""
  252. if limit > 0 {
  253. limitClause = fmt.Sprintf("LIMIT %d", limit)
  254. }
  255. rows, err := hsq.db.Query(fmt.Sprintf(getMessagesBetween, whereClauses, limitClause), args...)
  256. defer rows.Close()
  257. if err != nil || rows == nil {
  258. return nil
  259. }
  260. var msgData []byte
  261. for rows.Next() {
  262. err := rows.Scan(&msgData)
  263. if err != nil {
  264. hsq.log.Error("Database scan failed: %v", err)
  265. continue
  266. }
  267. var historySyncMsg waProto.HistorySyncMsg
  268. err = proto.Unmarshal(msgData, &historySyncMsg)
  269. if err != nil {
  270. hsq.log.Errorf("Failed to unmarshal history sync message: %v", err)
  271. continue
  272. }
  273. messages = append(messages, historySyncMsg.Message)
  274. }
  275. return
  276. }
  277. func (hsq *HistorySyncQuery) DeleteMessages(userID id.UserID, conversationID string, messages []*waProto.WebMessageInfo) error {
  278. whereClauses := []string{}
  279. preparedStatementArgs := []interface{}{userID, conversationID}
  280. for i, msg := range messages {
  281. whereClauses = append(whereClauses, fmt.Sprintf("(user_mxid=$1 AND conversation_id=$2 AND message_id=$%d)", i+3))
  282. preparedStatementArgs = append(preparedStatementArgs, msg.GetKey().GetId())
  283. }
  284. _, err := hsq.db.Exec(fmt.Sprintf(deleteMessages, strings.Join(whereClauses, " OR ")), preparedStatementArgs...)
  285. return err
  286. }
  287. func (hsq *HistorySyncQuery) DeleteAllMessages(userID id.UserID) error {
  288. _, err := hsq.db.Exec("DELETE FROM history_sync_message WHERE user_mxid=$1", userID)
  289. return err
  290. }