historysync.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. nPtr := &n
  165. // Negative limit on SQLite means unlimited, but Postgres prefers a NULL limit.
  166. if n < 0 && hsq.db.dialect == "postgres" {
  167. nPtr = nil
  168. }
  169. rows, err := hsq.db.Query(getNMostRecentConversations, userID, nPtr)
  170. defer rows.Close()
  171. if err != nil || rows == nil {
  172. return nil
  173. }
  174. for rows.Next() {
  175. conversations = append(conversations, hsq.NewConversation().Scan(rows))
  176. }
  177. return
  178. }
  179. func (hsq *HistorySyncQuery) GetConversation(userID id.UserID, portalKey *PortalKey) (conversation *HistorySyncConversation) {
  180. rows, err := hsq.db.Query(getConversationByPortal, userID, portalKey.JID, portalKey.Receiver)
  181. defer rows.Close()
  182. if err != nil || rows == nil {
  183. return nil
  184. }
  185. if rows.Next() {
  186. conversation = hsq.NewConversation().Scan(rows)
  187. }
  188. return
  189. }
  190. func (hsq *HistorySyncQuery) DeleteAllConversations(userID id.UserID) error {
  191. _, err := hsq.db.Exec("DELETE FROM history_sync_conversation WHERE user_mxid=$1", userID)
  192. return err
  193. }
  194. const (
  195. getMessagesBetween = `
  196. SELECT data
  197. FROM history_sync_message
  198. WHERE user_mxid=$1
  199. AND conversation_id=$2
  200. %s
  201. ORDER BY timestamp DESC
  202. %s
  203. `
  204. deleteMessages = `
  205. DELETE FROM history_sync_message
  206. WHERE %s
  207. `
  208. )
  209. type HistorySyncMessage struct {
  210. db *Database
  211. log log.Logger
  212. UserID id.UserID
  213. ConversationID string
  214. MessageID string
  215. Timestamp time.Time
  216. Data []byte
  217. }
  218. func (hsq *HistorySyncQuery) NewMessageWithValues(userID id.UserID, conversationID, messageID string, message *waProto.HistorySyncMsg) (*HistorySyncMessage, error) {
  219. msgData, err := proto.Marshal(message)
  220. if err != nil {
  221. return nil, err
  222. }
  223. return &HistorySyncMessage{
  224. db: hsq.db,
  225. log: hsq.log,
  226. UserID: userID,
  227. ConversationID: conversationID,
  228. MessageID: messageID,
  229. Timestamp: time.Unix(int64(message.Message.GetMessageTimestamp()), 0),
  230. Data: msgData,
  231. }, nil
  232. }
  233. func (hsm *HistorySyncMessage) Insert() {
  234. _, err := hsm.db.Exec(`
  235. INSERT INTO history_sync_message (user_mxid, conversation_id, message_id, timestamp, data)
  236. VALUES ($1, $2, $3, $4, $5)
  237. ON CONFLICT (user_mxid, conversation_id, message_id) DO NOTHING
  238. `, hsm.UserID, hsm.ConversationID, hsm.MessageID, hsm.Timestamp, hsm.Data)
  239. if err != nil {
  240. hsm.log.Warnfln("Failed to insert history sync message %s/%s: %v", hsm.ConversationID, hsm.Timestamp, err)
  241. }
  242. }
  243. func (hsq *HistorySyncQuery) GetMessagesBetween(userID id.UserID, conversationID string, startTime, endTime *time.Time, limit int) (messages []*waProto.WebMessageInfo) {
  244. whereClauses := ""
  245. args := []interface{}{userID, conversationID}
  246. argNum := 3
  247. if startTime != nil {
  248. whereClauses += fmt.Sprintf(" AND timestamp >= $%d", argNum)
  249. args = append(args, startTime)
  250. argNum++
  251. }
  252. if endTime != nil {
  253. whereClauses += fmt.Sprintf(" AND timestamp <= $%d", argNum)
  254. args = append(args, endTime)
  255. }
  256. limitClause := ""
  257. if limit > 0 {
  258. limitClause = fmt.Sprintf("LIMIT %d", limit)
  259. }
  260. rows, err := hsq.db.Query(fmt.Sprintf(getMessagesBetween, whereClauses, limitClause), args...)
  261. defer rows.Close()
  262. if err != nil || rows == nil {
  263. return nil
  264. }
  265. var msgData []byte
  266. for rows.Next() {
  267. err = rows.Scan(&msgData)
  268. if err != nil {
  269. hsq.log.Errorfln("Database scan failed: %v", err)
  270. continue
  271. }
  272. var historySyncMsg waProto.HistorySyncMsg
  273. err = proto.Unmarshal(msgData, &historySyncMsg)
  274. if err != nil {
  275. hsq.log.Errorfln("Failed to unmarshal history sync message: %v", err)
  276. continue
  277. }
  278. messages = append(messages, historySyncMsg.Message)
  279. }
  280. return
  281. }
  282. func (hsq *HistorySyncQuery) DeleteMessages(userID id.UserID, conversationID string, messages []*waProto.WebMessageInfo) error {
  283. whereClauses := []string{}
  284. preparedStatementArgs := []interface{}{userID, conversationID}
  285. for i, msg := range messages {
  286. whereClauses = append(whereClauses, fmt.Sprintf("(user_mxid=$1 AND conversation_id=$2 AND message_id=$%d)", i+3))
  287. preparedStatementArgs = append(preparedStatementArgs, msg.GetKey().GetId())
  288. }
  289. _, err := hsq.db.Exec(fmt.Sprintf(deleteMessages, strings.Join(whereClauses, " OR ")), preparedStatementArgs...)
  290. return err
  291. }
  292. func (hsq *HistorySyncQuery) DeleteAllMessages(userID id.UserID) error {
  293. _, err := hsq.db.Exec("DELETE FROM history_sync_message WHERE user_mxid=$1", userID)
  294. return err
  295. }