historysync.go 31 KB

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