historysync.go 31 KB

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