historysync.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  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 main
  17. import (
  18. "crypto/sha256"
  19. "encoding/base64"
  20. "fmt"
  21. "time"
  22. "github.com/rs/zerolog"
  23. "maunium.net/go/mautrix/util/variationselector"
  24. waProto "go.mau.fi/whatsmeow/binary/proto"
  25. "go.mau.fi/whatsmeow/types"
  26. "maunium.net/go/mautrix"
  27. "maunium.net/go/mautrix/appservice"
  28. "maunium.net/go/mautrix/event"
  29. "maunium.net/go/mautrix/id"
  30. "maunium.net/go/mautrix/util/dbutil"
  31. "maunium.net/go/mautrix-whatsapp/config"
  32. "maunium.net/go/mautrix-whatsapp/database"
  33. )
  34. // region User history sync handling
  35. type wrappedInfo struct {
  36. *types.MessageInfo
  37. Type database.MessageType
  38. Error database.MessageErrorType
  39. SenderMXID id.UserID
  40. ReactionTarget types.MessageID
  41. MediaKey []byte
  42. ExpirationStart time.Time
  43. ExpiresIn time.Duration
  44. }
  45. func (user *User) handleHistorySyncsLoop() {
  46. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  47. return
  48. }
  49. batchSend := user.bridge.SpecVersions.Supports(mautrix.BeeperFeatureBatchSending)
  50. if batchSend {
  51. // Start the backfill queue.
  52. user.BackfillQueue = &BackfillQueue{
  53. BackfillQuery: user.bridge.DB.Backfill,
  54. reCheckChannels: []chan bool{},
  55. log: user.log.Sub("BackfillQueue"),
  56. }
  57. forwardAndImmediate := []database.BackfillType{database.BackfillImmediate, database.BackfillForward}
  58. // Immediate backfills can be done in parallel
  59. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  60. go user.HandleBackfillRequestsLoop(forwardAndImmediate, []database.BackfillType{})
  61. }
  62. // Deferred backfills should be handled synchronously so as not to
  63. // overload the homeserver. Users can configure their backfill stages
  64. // to be more or less aggressive with backfilling at this stage.
  65. go user.HandleBackfillRequestsLoop([]database.BackfillType{database.BackfillDeferred}, forwardAndImmediate)
  66. }
  67. if user.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia &&
  68. user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod == config.MediaRequestMethodLocalTime {
  69. go user.dailyMediaRequestLoop()
  70. }
  71. // Always save the history syncs for the user. If they want to enable
  72. // backfilling in the future, we will have it in the database.
  73. for {
  74. select {
  75. case evt := <-user.historySyncs:
  76. if evt == nil {
  77. return
  78. }
  79. user.storeHistorySync(evt.Data)
  80. case <-user.enqueueBackfillsTimer.C:
  81. if batchSend {
  82. user.enqueueAllBackfills()
  83. } else {
  84. user.backfillAll()
  85. }
  86. }
  87. }
  88. }
  89. const EnqueueBackfillsDelay = 30 * time.Second
  90. func (user *User) enqueueAllBackfills() {
  91. nMostRecent := user.bridge.DB.HistorySync.GetRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  92. if len(nMostRecent) > 0 {
  93. user.log.Infofln("%v has passed since the last history sync blob, enqueueing backfills for %d chats", EnqueueBackfillsDelay, len(nMostRecent))
  94. // Find the portals for all the conversations.
  95. portals := []*Portal{}
  96. for _, conv := range nMostRecent {
  97. jid, err := types.ParseJID(conv.ConversationID)
  98. if err != nil {
  99. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  100. continue
  101. }
  102. portals = append(portals, user.GetPortalByJID(jid))
  103. }
  104. user.EnqueueImmediateBackfills(portals)
  105. user.EnqueueForwardBackfills(portals)
  106. user.EnqueueDeferredBackfills(portals)
  107. // Tell the queue to check for new backfill requests.
  108. user.BackfillQueue.ReCheck()
  109. }
  110. }
  111. func (user *User) backfillAll() {
  112. conversations := user.bridge.DB.HistorySync.GetRecentConversations(user.MXID, -1)
  113. if len(conversations) > 0 {
  114. user.zlog.Info().
  115. Int("conversation_count", len(conversations)).
  116. Msg("Probably received all history sync blobs, now backfilling conversations")
  117. limit := user.bridge.Config.Bridge.HistorySync.MaxInitialConversations
  118. // Find the portals for all the conversations.
  119. for i, conv := range conversations {
  120. jid, err := types.ParseJID(conv.ConversationID)
  121. if err != nil {
  122. user.zlog.Warn().Err(err).
  123. Str("conversation_id", conv.ConversationID).
  124. Msg("Failed to parse chat JID in history sync")
  125. continue
  126. }
  127. portal := user.GetPortalByJID(jid)
  128. if portal.MXID != "" {
  129. user.zlog.Debug().
  130. Str("portal_jid", portal.Key.JID.String()).
  131. Msg("Chat already has a room, deleting messages from database")
  132. user.bridge.DB.HistorySync.DeleteConversation(user.MXID, portal.Key.JID.String())
  133. } else if limit < 0 || i < limit {
  134. err = portal.CreateMatrixRoom(user, nil, true, true)
  135. if err != nil {
  136. user.zlog.Err(err).Msg("Failed to create Matrix room for backfill")
  137. }
  138. }
  139. }
  140. }
  141. }
  142. func (portal *Portal) legacyBackfill(user *User) {
  143. defer portal.latestEventBackfillLock.Unlock()
  144. // This should only be called from CreateMatrixRoom which locks latestEventBackfillLock before creating the room.
  145. if portal.latestEventBackfillLock.TryLock() {
  146. panic("legacyBackfill() called without locking latestEventBackfillLock")
  147. }
  148. // TODO use portal.zlog instead of user.zlog
  149. log := user.zlog.With().
  150. Str("portal_jid", portal.Key.JID.String()).
  151. Str("action", "legacy backfill").
  152. Logger()
  153. conv := user.bridge.DB.HistorySync.GetConversation(user.MXID, portal.Key)
  154. messages := user.bridge.DB.HistorySync.GetMessagesBetween(user.MXID, portal.Key.JID.String(), nil, nil, portal.bridge.Config.Bridge.HistorySync.MessageCount)
  155. log.Debug().Int("message_count", len(messages)).Msg("Got messages to backfill from database")
  156. for i := len(messages) - 1; i >= 0; i-- {
  157. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, messages[i])
  158. if err != nil {
  159. log.Warn().Err(err).
  160. Int("msg_index", i).
  161. Str("msg_id", messages[i].GetKey().GetId()).
  162. Uint64("msg_time_seconds", messages[i].GetMessageTimestamp()).
  163. Msg("Dropping historical message due to parse error")
  164. continue
  165. }
  166. portal.handleMessage(user, msgEvt, true)
  167. }
  168. if conv != nil {
  169. isUnread := conv.MarkedAsUnread || conv.UnreadCount > 0
  170. isTooOld := user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold > 0 && conv.LastMessageTimestamp.Before(time.Now().Add(time.Duration(-user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold)*time.Hour))
  171. shouldMarkAsRead := !isUnread || isTooOld
  172. if shouldMarkAsRead {
  173. user.markSelfReadFull(portal)
  174. }
  175. }
  176. log.Debug().Msg("Backfill complete, deleting leftover messages from database")
  177. user.bridge.DB.HistorySync.DeleteConversation(user.MXID, portal.Key.JID.String())
  178. }
  179. func (user *User) dailyMediaRequestLoop() {
  180. // Calculate when to do the first set of media retry requests
  181. now := time.Now()
  182. userTz, err := time.LoadLocation(user.Timezone)
  183. if err != nil {
  184. userTz = now.Local().Location()
  185. }
  186. tonightMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, userTz)
  187. midnightOffset := time.Duration(user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestLocalTime) * time.Minute
  188. requestStartTime := tonightMidnight.Add(midnightOffset)
  189. // If the request time for today has already happened, we need to start the
  190. // request loop tomorrow instead.
  191. if requestStartTime.Before(now) {
  192. requestStartTime = requestStartTime.AddDate(0, 0, 1)
  193. }
  194. // Wait to start the loop
  195. user.log.Infof("Waiting until %s to do media retry requests", requestStartTime)
  196. time.Sleep(time.Until(requestStartTime))
  197. for {
  198. mediaBackfillRequests := user.bridge.DB.MediaBackfillRequest.GetMediaBackfillRequestsForUser(user.MXID)
  199. user.log.Infof("Sending %d media retry requests", len(mediaBackfillRequests))
  200. // Send all of the media backfill requests for the user at once
  201. for _, req := range mediaBackfillRequests {
  202. portal := user.GetPortalByJID(req.PortalKey.JID)
  203. _, err := portal.requestMediaRetry(user, req.EventID, req.MediaKey)
  204. if err != nil {
  205. user.log.Warnf("Failed to send media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  206. req.Status = database.MediaBackfillRequestStatusRequestFailed
  207. req.Error = err.Error()
  208. } else {
  209. user.log.Debugfln("Sent media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  210. req.Status = database.MediaBackfillRequestStatusRequested
  211. }
  212. req.MediaKey = nil
  213. req.Upsert()
  214. }
  215. // Wait for 24 hours before making requests again
  216. time.Sleep(24 * time.Hour)
  217. }
  218. }
  219. func (user *User) backfillInChunks(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
  220. portal.backfillLock.Lock()
  221. defer portal.backfillLock.Unlock()
  222. if len(portal.MXID) > 0 && !user.bridge.AS.StateStore.IsInRoom(portal.MXID, user.MXID) {
  223. portal.ensureUserInvited(user)
  224. }
  225. backfillState := user.bridge.DB.Backfill.GetBackfillState(user.MXID, &portal.Key)
  226. if backfillState == nil {
  227. backfillState = user.bridge.DB.Backfill.NewBackfillState(user.MXID, &portal.Key)
  228. }
  229. backfillState.SetProcessingBatch(true)
  230. defer backfillState.SetProcessingBatch(false)
  231. var timeEnd *time.Time
  232. var forward, shouldMarkAsRead bool
  233. portal.latestEventBackfillLock.Lock()
  234. if req.BackfillType == database.BackfillForward {
  235. // TODO this overrides the TimeStart set when enqueuing the backfill
  236. // maybe the enqueue should instead include the prev event ID
  237. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  238. start := lastMessage.Timestamp.Add(1 * time.Second)
  239. req.TimeStart = &start
  240. // Sending events at the end of the room (= latest events)
  241. forward = true
  242. } else {
  243. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  244. if firstMessage != nil {
  245. end := firstMessage.Timestamp.Add(-1 * time.Second)
  246. timeEnd = &end
  247. user.log.Debugfln("Limiting backfill to end at %v", end)
  248. } else {
  249. // Portal is empty -> events are latest
  250. forward = true
  251. }
  252. }
  253. if !forward {
  254. // We'll use normal batch sending, so no need to keep blocking new message processing
  255. portal.latestEventBackfillLock.Unlock()
  256. } else {
  257. // This might involve sending events at the end of the room as non-historical events,
  258. // make sure we don't process messages until this is done.
  259. defer portal.latestEventBackfillLock.Unlock()
  260. isUnread := conv.MarkedAsUnread || conv.UnreadCount > 0
  261. isTooOld := user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold > 0 && conv.LastMessageTimestamp.Before(time.Now().Add(time.Duration(-user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold)*time.Hour))
  262. shouldMarkAsRead = !isUnread || isTooOld
  263. }
  264. allMsgs := user.bridge.DB.HistorySync.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, timeEnd, req.MaxTotalEvents)
  265. sendDisappearedNotice := false
  266. // If expired messages are on, and a notice has not been sent to this chat
  267. // about it having disappeared messages at the conversation timestamp, send
  268. // a notice indicating so.
  269. if len(allMsgs) == 0 && conv.EphemeralExpiration != nil && *conv.EphemeralExpiration > 0 {
  270. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  271. if lastMessage == nil || conv.LastMessageTimestamp.After(lastMessage.Timestamp) {
  272. sendDisappearedNotice = true
  273. }
  274. }
  275. if !sendDisappearedNotice && len(allMsgs) == 0 {
  276. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  277. return
  278. }
  279. if len(portal.MXID) == 0 {
  280. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  281. err := portal.CreateMatrixRoom(user, nil, true, false)
  282. if err != nil {
  283. user.log.Errorfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  284. return
  285. }
  286. }
  287. // Update the backfill status here after the room has been created.
  288. portal.updateBackfillStatus(backfillState)
  289. if sendDisappearedNotice {
  290. user.log.Debugfln("Sending notice to %s that there are disappeared messages ending at %v", portal.Key.JID, conv.LastMessageTimestamp)
  291. resp, err := portal.sendMessage(portal.MainIntent(), event.EventMessage, &event.MessageEventContent{
  292. MsgType: event.MsgNotice,
  293. Body: portal.formatDisappearingMessageNotice(),
  294. }, nil, conv.LastMessageTimestamp.UnixMilli())
  295. if err != nil {
  296. portal.log.Errorln("Error sending disappearing messages notice event")
  297. return
  298. }
  299. msg := portal.bridge.DB.Message.New()
  300. msg.Chat = portal.Key
  301. msg.MXID = resp.EventID
  302. msg.JID = types.MessageID(resp.EventID)
  303. msg.Timestamp = conv.LastMessageTimestamp
  304. msg.SenderMXID = portal.MainIntent().UserID
  305. msg.Sent = true
  306. msg.Type = database.MsgFake
  307. msg.Insert(nil)
  308. user.markSelfReadFull(portal)
  309. return
  310. }
  311. user.log.Infofln("Backfilling %d messages in %s, %d messages at a time (queue ID: %d)", len(allMsgs), portal.Key.JID, req.MaxBatchEvents, req.QueueID)
  312. toBackfill := allMsgs[0:]
  313. for len(toBackfill) > 0 {
  314. var msgs []*waProto.WebMessageInfo
  315. if len(toBackfill) <= req.MaxBatchEvents || req.MaxBatchEvents < 0 {
  316. msgs = toBackfill
  317. toBackfill = nil
  318. } else {
  319. msgs = toBackfill[:req.MaxBatchEvents]
  320. toBackfill = toBackfill[req.MaxBatchEvents:]
  321. }
  322. if len(msgs) > 0 {
  323. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  324. user.log.Debugfln("Backfilling %d messages in %s (queue ID: %d)", len(msgs), portal.Key.JID, req.QueueID)
  325. portal.backfill(user, msgs, forward, shouldMarkAsRead)
  326. }
  327. }
  328. user.log.Debugfln("Finished backfilling %d messages in %s (queue ID: %d)", len(allMsgs), portal.Key.JID, req.QueueID)
  329. err := user.bridge.DB.HistorySync.DeleteMessages(user.MXID, conv.ConversationID, allMsgs)
  330. if err != nil {
  331. user.log.Warnfln("Failed to delete %d history sync messages after backfilling (queue ID: %d): %v", len(allMsgs), req.QueueID, err)
  332. }
  333. if req.TimeStart == nil {
  334. // If the time start is nil, then there's no more history to backfill.
  335. backfillState.BackfillComplete = true
  336. if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY {
  337. // Since there are more messages on the phone, but we can't
  338. // backfill any more of them, indicate that the last timestamp
  339. // that we expect to be backfilled is the oldest one that was just
  340. // backfilled.
  341. backfillState.FirstExpectedTimestamp = allMsgs[len(allMsgs)-1].GetMessageTimestamp()
  342. } else if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY {
  343. // Since there are no more messages left on the phone, we've
  344. // backfilled everything. Indicate so by setting the expected
  345. // timestamp to 0 which means that the backfill goes to the
  346. // beginning of time.
  347. backfillState.FirstExpectedTimestamp = 0
  348. }
  349. backfillState.Upsert()
  350. portal.updateBackfillStatus(backfillState)
  351. }
  352. }
  353. func (user *User) storeHistorySync(evt *waProto.HistorySync) {
  354. if evt == nil || evt.SyncType == nil {
  355. return
  356. }
  357. log := user.bridge.ZLog.With().
  358. Str("method", "User.storeHistorySync").
  359. Str("user_id", user.MXID.String()).
  360. Str("sync_type", evt.GetSyncType().String()).
  361. Uint32("chunk_order", evt.GetChunkOrder()).
  362. Uint32("progress", evt.GetProgress()).
  363. Logger()
  364. if evt.GetGlobalSettings() != nil {
  365. log.Debug().Interface("global_settings", evt.GetGlobalSettings()).Msg("Got global settings in history sync")
  366. }
  367. if evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME || evt.GetSyncType() == waProto.HistorySync_NON_BLOCKING_DATA {
  368. log.Debug().
  369. Int("conversation_count", len(evt.GetConversations())).
  370. Int("pushname_count", len(evt.GetPushnames())).
  371. Int("status_count", len(evt.GetStatusV3Messages())).
  372. Int("recent_sticker_count", len(evt.GetRecentStickers())).
  373. Int("past_participant_count", len(evt.GetPastParticipants())).
  374. Msg("Ignoring history sync")
  375. return
  376. }
  377. log.Info().
  378. Int("conversation_count", len(evt.GetConversations())).
  379. Int("past_participant_count", len(evt.GetPastParticipants())).
  380. Msg("Storing history sync")
  381. successfullySavedTotal := 0
  382. totalMessageCount := 0
  383. for _, conv := range evt.GetConversations() {
  384. jid, err := types.ParseJID(conv.GetId())
  385. if err != nil {
  386. totalMessageCount += len(conv.GetMessages())
  387. log.Warn().Err(err).
  388. Str("chat_jid", conv.GetId()).
  389. Int("msg_count", len(conv.GetMessages())).
  390. Msg("Failed to parse chat JID in history sync")
  391. continue
  392. } else if jid.Server == types.BroadcastServer {
  393. log.Debug().Str("chat_jid", jid.String()).Msg("Skipping broadcast list in history sync")
  394. continue
  395. } else if jid.Server == types.HiddenUserServer {
  396. log.Debug().Str("chat_jid", jid.String()).Msg("Skipping hidden user JID chat in history sync")
  397. continue
  398. }
  399. totalMessageCount += len(conv.GetMessages())
  400. portal := user.GetPortalByJID(jid)
  401. log := log.With().
  402. Str("chat_jid", portal.Key.JID.String()).
  403. Int("msg_count", len(conv.GetMessages())).
  404. Logger()
  405. historySyncConversation := user.bridge.DB.HistorySync.NewConversationWithValues(
  406. user.MXID,
  407. conv.GetId(),
  408. &portal.Key,
  409. getConversationTimestamp(conv),
  410. conv.GetMuteEndTime(),
  411. conv.GetArchived(),
  412. conv.GetPinned(),
  413. conv.GetDisappearingMode().GetInitiator(),
  414. conv.GetEndOfHistoryTransferType(),
  415. conv.EphemeralExpiration,
  416. conv.GetMarkedAsUnread(),
  417. conv.GetUnreadCount())
  418. historySyncConversation.Upsert()
  419. var minTime, maxTime time.Time
  420. var minTimeIndex, maxTimeIndex int
  421. successfullySaved := 0
  422. unsupportedTypes := 0
  423. for i, rawMsg := range conv.GetMessages() {
  424. // Don't store messages that will just be skipped.
  425. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, rawMsg.GetMessage())
  426. if err != nil {
  427. log.Warn().Err(err).
  428. Int("msg_index", i).
  429. Str("msg_id", rawMsg.GetMessage().GetKey().GetId()).
  430. Uint64("msg_time_seconds", rawMsg.GetMessage().GetMessageTimestamp()).
  431. Msg("Dropping historical message due to parse error")
  432. continue
  433. }
  434. if minTime.IsZero() || msgEvt.Info.Timestamp.Before(minTime) {
  435. minTime = msgEvt.Info.Timestamp
  436. minTimeIndex = i
  437. }
  438. if maxTime.IsZero() || msgEvt.Info.Timestamp.After(maxTime) {
  439. maxTime = msgEvt.Info.Timestamp
  440. maxTimeIndex = i
  441. }
  442. msgType := getMessageType(msgEvt.Message)
  443. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  444. unsupportedTypes++
  445. continue
  446. }
  447. // Don't store unsupported messages.
  448. if !containsSupportedMessage(msgEvt.Message) {
  449. unsupportedTypes++
  450. continue
  451. }
  452. message, err := user.bridge.DB.HistorySync.NewMessageWithValues(user.MXID, conv.GetId(), msgEvt.Info.ID, rawMsg)
  453. if err != nil {
  454. log.Error().Err(err).
  455. Int("msg_index", i).
  456. Str("msg_id", msgEvt.Info.ID).
  457. Time("msg_time", msgEvt.Info.Timestamp).
  458. Msg("Failed to save historical message")
  459. continue
  460. }
  461. err = message.Insert()
  462. if err != nil {
  463. log.Error().Err(err).
  464. Int("msg_index", i).
  465. Str("msg_id", msgEvt.Info.ID).
  466. Time("msg_time", msgEvt.Info.Timestamp).
  467. Msg("Failed to save historical message")
  468. }
  469. successfullySaved++
  470. }
  471. successfullySavedTotal += successfullySaved
  472. log.Debug().
  473. Int("saved_count", successfullySaved).
  474. Int("unsupported_msg_type_count", unsupportedTypes).
  475. Time("lowest_time", minTime).
  476. Int("lowest_time_index", minTimeIndex).
  477. Time("highest_time", maxTime).
  478. Int("highest_time_index", maxTimeIndex).
  479. Dict("metadata", zerolog.Dict().
  480. Uint32("ephemeral_expiration", conv.GetEphemeralExpiration()).
  481. Bool("marked_unread", conv.GetMarkedAsUnread()).
  482. Bool("archived", conv.GetArchived()).
  483. Uint32("pinned", conv.GetPinned()).
  484. Uint64("mute_end", conv.GetMuteEndTime()).
  485. Uint32("unread_count", conv.GetUnreadCount()),
  486. ).
  487. Msg("Saved messages from history sync conversation")
  488. }
  489. log.Info().
  490. Int("total_saved_count", successfullySavedTotal).
  491. Int("total_message_count", totalMessageCount).
  492. Msg("Finished storing history sync")
  493. // If this was the initial bootstrap, enqueue immediate backfills for the
  494. // most recent portals. If it's the last history sync event, start
  495. // backfilling the rest of the history of the portals.
  496. if user.bridge.Config.Bridge.HistorySync.Backfill {
  497. user.enqueueBackfillsTimer.Reset(EnqueueBackfillsDelay)
  498. }
  499. }
  500. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  501. convTs := conv.GetConversationTimestamp()
  502. if convTs == 0 && len(conv.GetMessages()) > 0 {
  503. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  504. }
  505. return convTs
  506. }
  507. func (user *User) EnqueueImmediateBackfills(portals []*Portal) {
  508. for priority, portal := range portals {
  509. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  510. initialBackfill := user.bridge.DB.Backfill.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, maxMessages, maxMessages, 0)
  511. initialBackfill.Insert()
  512. }
  513. }
  514. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  515. numPortals := len(portals)
  516. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  517. for portalIdx, portal := range portals {
  518. var startDate *time.Time = nil
  519. if backfillStage.StartDaysAgo > 0 {
  520. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  521. startDate = &startDaysAgo
  522. }
  523. backfillMessages := user.bridge.DB.Backfill.NewWithValues(
  524. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  525. backfillMessages.Insert()
  526. }
  527. }
  528. }
  529. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  530. for priority, portal := range portals {
  531. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  532. if lastMsg == nil {
  533. continue
  534. }
  535. backfill := user.bridge.DB.Backfill.NewWithValues(
  536. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, -1, -1, 0)
  537. backfill.Insert()
  538. }
  539. }
  540. // endregion
  541. // region Portal backfilling
  542. func (portal *Portal) deterministicEventID(sender types.JID, messageID types.MessageID, partName string) id.EventID {
  543. data := fmt.Sprintf("%s/whatsapp/%s/%s", portal.MXID, sender.User, messageID)
  544. if partName != "" {
  545. data += "/" + partName
  546. }
  547. sum := sha256.Sum256([]byte(data))
  548. return id.EventID(fmt.Sprintf("$%s:whatsapp.com", base64.RawURLEncoding.EncodeToString(sum[:])))
  549. }
  550. var (
  551. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  552. BackfillStatusEvent = event.Type{Type: "com.beeper.backfill_status", Class: event.StateEventType}
  553. )
  554. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward, atomicMarkAsRead bool) *mautrix.RespBeeperBatchSend {
  555. var req mautrix.ReqBeeperBatchSend
  556. var infos []*wrappedInfo
  557. req.Forward = isForward
  558. if atomicMarkAsRead {
  559. req.MarkReadBy = source.MXID
  560. }
  561. portal.log.Infofln("Processing history sync with %d messages (forward: %t)", len(messages), isForward)
  562. // The messages are ordered newest to oldest, so iterate them in reverse order.
  563. for i := len(messages) - 1; i >= 0; i-- {
  564. webMsg := messages[i]
  565. msgEvt, err := source.Client.ParseWebMessage(portal.Key.JID, webMsg)
  566. if err != nil {
  567. continue
  568. }
  569. msgType := getMessageType(msgEvt.Message)
  570. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  571. if msgType != "ignore" {
  572. portal.log.Debugfln("Skipping message %s with unknown type in backfill", msgEvt.Info.ID)
  573. }
  574. continue
  575. }
  576. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  577. existingContact, _ := source.Client.Store.Contacts.GetContact(msgEvt.Info.Sender)
  578. if !existingContact.Found || existingContact.PushName == "" {
  579. changed, _, err := source.Client.Store.Contacts.PutPushName(msgEvt.Info.Sender, webMsg.GetPushName())
  580. if err != nil {
  581. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", msgEvt.Info.Sender, err)
  582. } else if changed {
  583. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), msgEvt.Info.Sender)
  584. }
  585. }
  586. }
  587. puppet := portal.getMessagePuppet(source, &msgEvt.Info)
  588. if puppet == nil {
  589. continue
  590. }
  591. converted := portal.convertMessage(puppet.IntentFor(portal), source, &msgEvt.Info, msgEvt.Message, true)
  592. if converted == nil {
  593. portal.log.Debugfln("Skipping unsupported message %s in backfill", msgEvt.Info.ID)
  594. continue
  595. }
  596. if converted.ReplyTo != nil {
  597. portal.SetReply(msgEvt.Info.ID, converted.Content, converted.ReplyTo, true)
  598. }
  599. err = portal.appendBatchEvents(source, converted, &msgEvt.Info, webMsg, &req.Events, &infos)
  600. if err != nil {
  601. portal.log.Errorfln("Error handling message %s during backfill: %v", msgEvt.Info.ID, err)
  602. }
  603. }
  604. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  605. if len(req.Events) == 0 {
  606. return nil
  607. }
  608. resp, err := portal.MainIntent().BeeperBatchSend(portal.MXID, &req)
  609. if err != nil {
  610. portal.log.Errorln("Error batch sending messages:", err)
  611. return nil
  612. } else {
  613. txn, err := portal.bridge.DB.Begin()
  614. if err != nil {
  615. portal.log.Errorln("Failed to start transaction to save batch messages:", err)
  616. return nil
  617. }
  618. portal.finishBatch(txn, resp.EventIDs, infos)
  619. err = txn.Commit()
  620. if err != nil {
  621. portal.log.Errorln("Failed to commit transaction to save batch messages:", err)
  622. return nil
  623. }
  624. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia {
  625. go portal.requestMediaRetries(source, resp.EventIDs, infos)
  626. }
  627. return resp
  628. }
  629. }
  630. func (portal *Portal) requestMediaRetries(source *User, eventIDs []id.EventID, infos []*wrappedInfo) {
  631. for i, info := range infos {
  632. if info != nil && info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  633. switch portal.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod {
  634. case config.MediaRequestMethodImmediate:
  635. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  636. if err != nil {
  637. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  638. } else {
  639. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  640. }
  641. case config.MediaRequestMethodLocalTime:
  642. req := portal.bridge.DB.MediaBackfillRequest.NewMediaBackfillRequestWithValues(source.MXID, &portal.Key, eventIDs[i], info.MediaKey)
  643. req.Upsert()
  644. }
  645. }
  646. }
  647. }
  648. func (portal *Portal) appendBatchEvents(source *User, converted *ConvertedMessage, info *types.MessageInfo, raw *waProto.WebMessageInfo, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  649. if portal.bridge.Config.Bridge.CaptionInMessage {
  650. converted.MergeCaption()
  651. }
  652. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra, "")
  653. if err != nil {
  654. return err
  655. }
  656. expirationStart := info.Timestamp
  657. if raw.GetEphemeralStartTimestamp() > 0 {
  658. expirationStart = time.Unix(int64(raw.GetEphemeralStartTimestamp()), 0)
  659. }
  660. mainInfo := &wrappedInfo{
  661. MessageInfo: info,
  662. Type: database.MsgNormal,
  663. SenderMXID: mainEvt.Sender,
  664. Error: converted.Error,
  665. MediaKey: converted.MediaKey,
  666. ExpirationStart: expirationStart,
  667. ExpiresIn: converted.ExpiresIn,
  668. }
  669. if converted.Caption != nil {
  670. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil, "caption")
  671. if err != nil {
  672. return err
  673. }
  674. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  675. *infoArray = append(*infoArray, mainInfo, nil)
  676. } else {
  677. *eventsArray = append(*eventsArray, mainEvt)
  678. *infoArray = append(*infoArray, mainInfo)
  679. }
  680. if converted.MultiEvent != nil {
  681. for i, subEvtContent := range converted.MultiEvent {
  682. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil, fmt.Sprintf("multi-%d", i))
  683. if err != nil {
  684. return err
  685. }
  686. *eventsArray = append(*eventsArray, subEvt)
  687. *infoArray = append(*infoArray, nil)
  688. }
  689. }
  690. for _, reaction := range raw.GetReactions() {
  691. reactionEvent, reactionInfo := portal.wrapBatchReaction(source, reaction, mainEvt.ID, info.Timestamp)
  692. if reactionEvent != nil {
  693. *eventsArray = append(*eventsArray, reactionEvent)
  694. *infoArray = append(*infoArray, &wrappedInfo{
  695. MessageInfo: reactionInfo,
  696. SenderMXID: reactionEvent.Sender,
  697. ReactionTarget: info.ID,
  698. Type: database.MsgReaction,
  699. })
  700. }
  701. }
  702. return nil
  703. }
  704. func (portal *Portal) wrapBatchReaction(source *User, reaction *waProto.Reaction, mainEventID id.EventID, mainEventTS time.Time) (reactionEvent *event.Event, reactionInfo *types.MessageInfo) {
  705. var senderJID types.JID
  706. if reaction.GetKey().GetFromMe() {
  707. senderJID = source.JID.ToNonAD()
  708. } else if reaction.GetKey().GetParticipant() != "" {
  709. senderJID, _ = types.ParseJID(reaction.GetKey().GetParticipant())
  710. } else if portal.IsPrivateChat() {
  711. senderJID = portal.Key.JID
  712. }
  713. if senderJID.IsEmpty() {
  714. return
  715. }
  716. reactionInfo = &types.MessageInfo{
  717. MessageSource: types.MessageSource{
  718. Chat: portal.Key.JID,
  719. Sender: senderJID,
  720. IsFromMe: reaction.GetKey().GetFromMe(),
  721. IsGroup: portal.IsGroupChat(),
  722. },
  723. ID: reaction.GetKey().GetId(),
  724. Timestamp: mainEventTS,
  725. }
  726. puppet := portal.getMessagePuppet(source, reactionInfo)
  727. if puppet == nil {
  728. return
  729. }
  730. intent := puppet.IntentFor(portal)
  731. content := event.ReactionEventContent{
  732. RelatesTo: event.RelatesTo{
  733. Type: event.RelAnnotation,
  734. EventID: mainEventID,
  735. Key: variationselector.Add(reaction.GetText()),
  736. },
  737. }
  738. if rawTS := reaction.GetSenderTimestampMs(); rawTS >= mainEventTS.UnixMilli() && rawTS <= time.Now().UnixMilli() {
  739. reactionInfo.Timestamp = time.UnixMilli(rawTS)
  740. }
  741. wrappedContent := event.Content{Parsed: &content}
  742. intent.AddDoublePuppetValue(&wrappedContent)
  743. reactionEvent = &event.Event{
  744. ID: portal.deterministicEventID(senderJID, reactionInfo.ID, ""),
  745. Type: event.EventReaction,
  746. Content: wrappedContent,
  747. Sender: intent.UserID,
  748. Timestamp: reactionInfo.Timestamp.UnixMilli(),
  749. }
  750. return
  751. }
  752. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, partName string) (*event.Event, error) {
  753. wrappedContent := event.Content{
  754. Parsed: content,
  755. Raw: extraContent,
  756. }
  757. newEventType, err := portal.encrypt(intent, &wrappedContent, eventType)
  758. if err != nil {
  759. return nil, err
  760. }
  761. intent.AddDoublePuppetValue(&wrappedContent)
  762. return &event.Event{
  763. ID: portal.deterministicEventID(info.Sender, info.ID, partName),
  764. Sender: intent.UserID,
  765. Type: newEventType,
  766. Timestamp: info.Timestamp.UnixMilli(),
  767. Content: wrappedContent,
  768. }, nil
  769. }
  770. func (portal *Portal) finishBatch(txn dbutil.Transaction, eventIDs []id.EventID, infos []*wrappedInfo) {
  771. for i, info := range infos {
  772. if info == nil {
  773. continue
  774. }
  775. eventID := eventIDs[i]
  776. portal.markHandled(txn, nil, info.MessageInfo, eventID, info.SenderMXID, true, false, info.Type, info.Error)
  777. if info.Type == database.MsgReaction {
  778. portal.upsertReaction(txn, nil, info.ReactionTarget, info.Sender, eventID, info.ID)
  779. }
  780. if info.ExpiresIn > 0 {
  781. portal.MarkDisappearing(txn, eventID, info.ExpiresIn, info.ExpirationStart)
  782. }
  783. }
  784. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  785. }
  786. func (portal *Portal) updateBackfillStatus(backfillState *database.BackfillState) {
  787. backfillStatus := "backfilling"
  788. if backfillState.BackfillComplete {
  789. backfillStatus = "complete"
  790. }
  791. _, err := portal.bridge.Bot.SendStateEvent(portal.MXID, BackfillStatusEvent, "", map[string]interface{}{
  792. "status": backfillStatus,
  793. "first_timestamp": backfillState.FirstExpectedTimestamp * 1000,
  794. })
  795. if err != nil {
  796. portal.log.Errorln("Error sending backfill status event:", err)
  797. }
  798. }
  799. // endregion