historysync.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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).UTC(),
  75. MuteEndTime: time.Unix(int64(muteEndTime), 0).UTC(),
  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. last_message_timestamp=CASE
  108. WHEN EXCLUDED.last_message_timestamp > history_sync_conversation.last_message_timestamp THEN EXCLUDED.last_message_timestamp
  109. ELSE history_sync_conversation.last_message_timestamp
  110. END,
  111. end_of_history_transfer_type=EXCLUDED.end_of_history_transfer_type
  112. `,
  113. hsc.UserID,
  114. hsc.ConversationID,
  115. hsc.PortalKey.JID.String(),
  116. hsc.PortalKey.Receiver.String(),
  117. hsc.LastMessageTimestamp,
  118. hsc.Archived,
  119. hsc.Pinned,
  120. hsc.MuteEndTime,
  121. hsc.DisappearingMode,
  122. hsc.EndOfHistoryTransferType,
  123. hsc.EphemeralExpiration,
  124. hsc.MarkedAsUnread,
  125. hsc.UnreadCount)
  126. if err != nil {
  127. hsc.log.Warnfln("Failed to insert history sync conversation %s/%s: %v", hsc.UserID, hsc.ConversationID, err)
  128. }
  129. }
  130. func (hsc *HistorySyncConversation) Scan(row Scannable) *HistorySyncConversation {
  131. err := row.Scan(
  132. &hsc.UserID,
  133. &hsc.ConversationID,
  134. &hsc.PortalKey.JID,
  135. &hsc.PortalKey.Receiver,
  136. &hsc.LastMessageTimestamp,
  137. &hsc.Archived,
  138. &hsc.Pinned,
  139. &hsc.MuteEndTime,
  140. &hsc.DisappearingMode,
  141. &hsc.EndOfHistoryTransferType,
  142. &hsc.EphemeralExpiration,
  143. &hsc.MarkedAsUnread,
  144. &hsc.UnreadCount)
  145. if err != nil {
  146. if !errors.Is(err, sql.ErrNoRows) {
  147. hsc.log.Errorln("Database scan failed:", err)
  148. }
  149. return nil
  150. }
  151. return hsc
  152. }
  153. func (hsq *HistorySyncQuery) GetNMostRecentConversations(userID id.UserID, n int) (conversations []*HistorySyncConversation) {
  154. nPtr := &n
  155. // Negative limit on SQLite means unlimited, but Postgres prefers a NULL limit.
  156. if n < 0 && hsq.db.dialect == "postgres" {
  157. nPtr = nil
  158. }
  159. rows, err := hsq.db.Query(getNMostRecentConversations, userID, nPtr)
  160. defer rows.Close()
  161. if err != nil || rows == nil {
  162. return nil
  163. }
  164. for rows.Next() {
  165. conversations = append(conversations, hsq.NewConversation().Scan(rows))
  166. }
  167. return
  168. }
  169. func (hsq *HistorySyncQuery) GetConversation(userID id.UserID, portalKey *PortalKey) (conversation *HistorySyncConversation) {
  170. rows, err := hsq.db.Query(getConversationByPortal, userID, portalKey.JID, portalKey.Receiver)
  171. defer rows.Close()
  172. if err != nil || rows == nil {
  173. return nil
  174. }
  175. if rows.Next() {
  176. conversation = hsq.NewConversation().Scan(rows)
  177. }
  178. return
  179. }
  180. func (hsq *HistorySyncQuery) DeleteAllConversations(userID id.UserID) {
  181. _, err := hsq.db.Exec("DELETE FROM history_sync_conversation WHERE user_mxid=$1", userID)
  182. if err != nil {
  183. hsq.log.Warnfln("Failed to delete historical chat info for %s/%s: %v", userID, err)
  184. }
  185. }
  186. const (
  187. getMessagesBetween = `
  188. SELECT data FROM history_sync_message
  189. WHERE user_mxid=$1 AND conversation_id=$2
  190. %s
  191. ORDER BY timestamp DESC
  192. %s
  193. `
  194. deleteMessagesBetweenExclusive = `
  195. DELETE FROM history_sync_message
  196. WHERE user_mxid=$1 AND conversation_id=$2 AND timestamp<$3 AND timestamp>$4
  197. `
  198. )
  199. type HistorySyncMessage struct {
  200. db *Database
  201. log log.Logger
  202. UserID id.UserID
  203. ConversationID string
  204. MessageID string
  205. Timestamp time.Time
  206. Data []byte
  207. }
  208. func (hsq *HistorySyncQuery) NewMessageWithValues(userID id.UserID, conversationID, messageID string, message *waProto.HistorySyncMsg) (*HistorySyncMessage, error) {
  209. msgData, err := proto.Marshal(message)
  210. if err != nil {
  211. return nil, err
  212. }
  213. return &HistorySyncMessage{
  214. db: hsq.db,
  215. log: hsq.log,
  216. UserID: userID,
  217. ConversationID: conversationID,
  218. MessageID: messageID,
  219. Timestamp: time.Unix(int64(message.Message.GetMessageTimestamp()), 0),
  220. Data: msgData,
  221. }, nil
  222. }
  223. func (hsm *HistorySyncMessage) Insert() {
  224. _, err := hsm.db.Exec(`
  225. INSERT INTO history_sync_message (user_mxid, conversation_id, message_id, timestamp, data, inserted_time)
  226. VALUES ($1, $2, $3, $4, $5, $6)
  227. ON CONFLICT (user_mxid, conversation_id, message_id) DO NOTHING
  228. `, hsm.UserID, hsm.ConversationID, hsm.MessageID, hsm.Timestamp, hsm.Data, time.Now())
  229. if err != nil {
  230. hsm.log.Warnfln("Failed to insert history sync message %s/%s: %v", hsm.ConversationID, hsm.Timestamp, err)
  231. }
  232. }
  233. func (hsq *HistorySyncQuery) GetMessagesBetween(userID id.UserID, conversationID string, startTime, endTime *time.Time, limit int) (messages []*waProto.WebMessageInfo) {
  234. whereClauses := ""
  235. args := []interface{}{userID, conversationID}
  236. argNum := 3
  237. if startTime != nil {
  238. whereClauses += fmt.Sprintf(" AND timestamp >= $%d", argNum)
  239. args = append(args, startTime)
  240. argNum++
  241. }
  242. if endTime != nil {
  243. whereClauses += fmt.Sprintf(" AND timestamp <= $%d", argNum)
  244. args = append(args, endTime)
  245. }
  246. limitClause := ""
  247. if limit > 0 {
  248. limitClause = fmt.Sprintf("LIMIT %d", limit)
  249. }
  250. rows, err := hsq.db.Query(fmt.Sprintf(getMessagesBetween, whereClauses, limitClause), args...)
  251. defer rows.Close()
  252. if err != nil || rows == nil {
  253. return nil
  254. }
  255. var msgData []byte
  256. for rows.Next() {
  257. err = rows.Scan(&msgData)
  258. if err != nil {
  259. hsq.log.Errorfln("Database scan failed: %v", err)
  260. continue
  261. }
  262. var historySyncMsg waProto.HistorySyncMsg
  263. err = proto.Unmarshal(msgData, &historySyncMsg)
  264. if err != nil {
  265. hsq.log.Errorfln("Failed to unmarshal history sync message: %v", err)
  266. continue
  267. }
  268. messages = append(messages, historySyncMsg.Message)
  269. }
  270. return
  271. }
  272. func (hsq *HistorySyncQuery) DeleteMessages(userID id.UserID, conversationID string, messages []*waProto.WebMessageInfo) error {
  273. newest := messages[0]
  274. beforeTS := time.Unix(int64(newest.GetMessageTimestamp())+1, 0)
  275. oldest := messages[len(messages)-1]
  276. afterTS := time.Unix(int64(oldest.GetMessageTimestamp())-1, 0)
  277. _, err := hsq.db.Exec(deleteMessagesBetweenExclusive, userID, conversationID, beforeTS, afterTS)
  278. return err
  279. }
  280. func (hsq *HistorySyncQuery) DeleteAllMessages(userID id.UserID) {
  281. _, err := hsq.db.Exec("DELETE FROM history_sync_message WHERE user_mxid=$1", userID)
  282. if err != nil {
  283. hsq.log.Warnfln("Failed to delete historical messages for %s: %v", userID, err)
  284. }
  285. }
  286. func (hsq *HistorySyncQuery) DeleteAllMessagesForPortal(userID id.UserID, portalKey PortalKey) {
  287. _, err := hsq.db.Exec(`
  288. DELETE FROM history_sync_message
  289. WHERE user_mxid=$1 AND conversation_id=$2
  290. `, userID, portalKey.JID)
  291. if err != nil {
  292. hsq.log.Warnfln("Failed to delete historical messages for %s/%s: %v", userID, portalKey.JID, err)
  293. }
  294. }