historysync.go 9.9 KB

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