historysync.go 9.1 KB

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