historysync.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. } else if jid.Server == types.HiddenUserServer {
  385. log.Debug().Str("chat_jid", jid.String()).Msg("Skipping hidden user JID chat in history sync")
  386. continue
  387. }
  388. totalMessageCount += len(conv.GetMessages())
  389. portal := user.GetPortalByJID(jid)
  390. log := log.With().
  391. Str("chat_jid", portal.Key.JID.String()).
  392. Int("msg_count", len(conv.GetMessages())).
  393. Logger()
  394. historySyncConversation := user.bridge.DB.HistorySync.NewConversationWithValues(
  395. user.MXID,
  396. conv.GetId(),
  397. &portal.Key,
  398. getConversationTimestamp(conv),
  399. conv.GetMuteEndTime(),
  400. conv.GetArchived(),
  401. conv.GetPinned(),
  402. conv.GetDisappearingMode().GetInitiator(),
  403. conv.GetEndOfHistoryTransferType(),
  404. conv.EphemeralExpiration,
  405. conv.GetMarkedAsUnread(),
  406. conv.GetUnreadCount())
  407. historySyncConversation.Upsert()
  408. var minTime, maxTime time.Time
  409. var minTimeIndex, maxTimeIndex int
  410. successfullySaved := 0
  411. unsupportedTypes := 0
  412. for i, rawMsg := range conv.GetMessages() {
  413. // Don't store messages that will just be skipped.
  414. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, rawMsg.GetMessage())
  415. if err != nil {
  416. log.Warn().Err(err).
  417. Int("msg_index", i).
  418. Str("msg_id", rawMsg.GetMessage().GetKey().GetId()).
  419. Uint64("msg_time_seconds", rawMsg.GetMessage().GetMessageTimestamp()).
  420. Msg("Dropping historical message due to parse error")
  421. continue
  422. }
  423. if minTime.IsZero() || msgEvt.Info.Timestamp.Before(minTime) {
  424. minTime = msgEvt.Info.Timestamp
  425. minTimeIndex = i
  426. }
  427. if maxTime.IsZero() || msgEvt.Info.Timestamp.After(maxTime) {
  428. maxTime = msgEvt.Info.Timestamp
  429. maxTimeIndex = i
  430. }
  431. msgType := getMessageType(msgEvt.Message)
  432. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  433. unsupportedTypes++
  434. continue
  435. }
  436. // Don't store unsupported messages.
  437. if !containsSupportedMessage(msgEvt.Message) {
  438. unsupportedTypes++
  439. continue
  440. }
  441. message, err := user.bridge.DB.HistorySync.NewMessageWithValues(user.MXID, conv.GetId(), msgEvt.Info.ID, rawMsg)
  442. if err != nil {
  443. log.Error().Err(err).
  444. Int("msg_index", i).
  445. Str("msg_id", msgEvt.Info.ID).
  446. Time("msg_time", msgEvt.Info.Timestamp).
  447. Msg("Failed to save historical message")
  448. continue
  449. }
  450. err = message.Insert()
  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. }
  458. successfullySaved++
  459. }
  460. successfullySavedTotal += successfullySaved
  461. log.Debug().
  462. Int("saved_count", successfullySaved).
  463. Int("unsupported_msg_type_count", unsupportedTypes).
  464. Time("lowest_time", minTime).
  465. Int("lowest_time_index", minTimeIndex).
  466. Time("highest_time", maxTime).
  467. Int("highest_time_index", maxTimeIndex).
  468. Msg("Saved messages from history sync conversation")
  469. }
  470. log.Info().
  471. Int("total_saved_count", successfullySavedTotal).
  472. Int("total_message_count", totalMessageCount).
  473. Msg("Finished storing history sync")
  474. // If this was the initial bootstrap, enqueue immediate backfills for the
  475. // most recent portals. If it's the last history sync event, start
  476. // backfilling the rest of the history of the portals.
  477. if user.bridge.Config.Bridge.HistorySync.Backfill {
  478. user.enqueueBackfillsTimer.Reset(EnqueueBackfillsDelay)
  479. }
  480. }
  481. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  482. convTs := conv.GetConversationTimestamp()
  483. if convTs == 0 && len(conv.GetMessages()) > 0 {
  484. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  485. }
  486. return convTs
  487. }
  488. func (user *User) EnqueueImmediateBackfills(portals []*Portal) {
  489. for priority, portal := range portals {
  490. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  491. initialBackfill := user.bridge.DB.Backfill.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, maxMessages, maxMessages, 0)
  492. initialBackfill.Insert()
  493. }
  494. }
  495. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  496. numPortals := len(portals)
  497. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  498. for portalIdx, portal := range portals {
  499. var startDate *time.Time = nil
  500. if backfillStage.StartDaysAgo > 0 {
  501. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  502. startDate = &startDaysAgo
  503. }
  504. backfillMessages := user.bridge.DB.Backfill.NewWithValues(
  505. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  506. backfillMessages.Insert()
  507. }
  508. }
  509. }
  510. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  511. for priority, portal := range portals {
  512. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  513. if lastMsg == nil {
  514. continue
  515. }
  516. backfill := user.bridge.DB.Backfill.NewWithValues(
  517. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, -1, -1, 0)
  518. backfill.Insert()
  519. }
  520. }
  521. // endregion
  522. // region Portal backfilling
  523. func (portal *Portal) deterministicEventID(sender types.JID, messageID types.MessageID, partName string) id.EventID {
  524. data := fmt.Sprintf("%s/whatsapp/%s/%s", portal.MXID, sender.User, messageID)
  525. if partName != "" {
  526. data += "/" + partName
  527. }
  528. sum := sha256.Sum256([]byte(data))
  529. return id.EventID(fmt.Sprintf("$%s:whatsapp.com", base64.RawURLEncoding.EncodeToString(sum[:])))
  530. }
  531. var (
  532. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  533. BackfillStatusEvent = event.Type{Type: "com.beeper.backfill_status", Class: event.StateEventType}
  534. )
  535. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward, atomicMarkAsRead bool) *mautrix.RespBeeperBatchSend {
  536. var req mautrix.ReqBeeperBatchSend
  537. var infos []*wrappedInfo
  538. req.Forward = isForward
  539. if atomicMarkAsRead {
  540. req.MarkReadBy = source.MXID
  541. }
  542. portal.log.Infofln("Processing history sync with %d messages (forward: %t)", len(messages), isForward)
  543. // The messages are ordered newest to oldest, so iterate them in reverse order.
  544. for i := len(messages) - 1; i >= 0; i-- {
  545. webMsg := messages[i]
  546. msgEvt, err := source.Client.ParseWebMessage(portal.Key.JID, webMsg)
  547. if err != nil {
  548. continue
  549. }
  550. msgType := getMessageType(msgEvt.Message)
  551. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  552. if msgType != "ignore" {
  553. portal.log.Debugfln("Skipping message %s with unknown type in backfill", msgEvt.Info.ID)
  554. }
  555. continue
  556. }
  557. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  558. existingContact, _ := source.Client.Store.Contacts.GetContact(msgEvt.Info.Sender)
  559. if !existingContact.Found || existingContact.PushName == "" {
  560. changed, _, err := source.Client.Store.Contacts.PutPushName(msgEvt.Info.Sender, webMsg.GetPushName())
  561. if err != nil {
  562. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", msgEvt.Info.Sender, err)
  563. } else if changed {
  564. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), msgEvt.Info.Sender)
  565. }
  566. }
  567. }
  568. puppet := portal.getMessagePuppet(source, &msgEvt.Info)
  569. if puppet == nil {
  570. continue
  571. }
  572. converted := portal.convertMessage(puppet.IntentFor(portal), source, &msgEvt.Info, msgEvt.Message, true)
  573. if converted == nil {
  574. portal.log.Debugfln("Skipping unsupported message %s in backfill", msgEvt.Info.ID)
  575. continue
  576. }
  577. if converted.ReplyTo != nil {
  578. portal.SetReply(converted.Content, converted.ReplyTo, true)
  579. }
  580. err = portal.appendBatchEvents(source, converted, &msgEvt.Info, webMsg, &req.Events, &infos)
  581. if err != nil {
  582. portal.log.Errorfln("Error handling message %s during backfill: %v", msgEvt.Info.ID, err)
  583. }
  584. }
  585. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  586. if len(req.Events) == 0 {
  587. return nil
  588. }
  589. resp, err := portal.MainIntent().BeeperBatchSend(portal.MXID, &req)
  590. if err != nil {
  591. portal.log.Errorln("Error batch sending messages:", err)
  592. return nil
  593. } else {
  594. txn, err := portal.bridge.DB.Begin()
  595. if err != nil {
  596. portal.log.Errorln("Failed to start transaction to save batch messages:", err)
  597. return nil
  598. }
  599. portal.finishBatch(txn, resp.EventIDs, infos)
  600. err = txn.Commit()
  601. if err != nil {
  602. portal.log.Errorln("Failed to commit transaction to save batch messages:", err)
  603. return nil
  604. }
  605. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia {
  606. go portal.requestMediaRetries(source, resp.EventIDs, infos)
  607. }
  608. return resp
  609. }
  610. }
  611. func (portal *Portal) requestMediaRetries(source *User, eventIDs []id.EventID, infos []*wrappedInfo) {
  612. for i, info := range infos {
  613. if info != nil && info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  614. switch portal.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod {
  615. case config.MediaRequestMethodImmediate:
  616. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  617. if err != nil {
  618. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  619. } else {
  620. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  621. }
  622. case config.MediaRequestMethodLocalTime:
  623. req := portal.bridge.DB.MediaBackfillRequest.NewMediaBackfillRequestWithValues(source.MXID, &portal.Key, eventIDs[i], info.MediaKey)
  624. req.Upsert()
  625. }
  626. }
  627. }
  628. }
  629. func (portal *Portal) appendBatchEvents(source *User, converted *ConvertedMessage, info *types.MessageInfo, raw *waProto.WebMessageInfo, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  630. if portal.bridge.Config.Bridge.CaptionInMessage {
  631. converted.MergeCaption()
  632. }
  633. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra, "")
  634. if err != nil {
  635. return err
  636. }
  637. expirationStart := info.Timestamp
  638. if raw.GetEphemeralStartTimestamp() > 0 {
  639. expirationStart = time.Unix(int64(raw.GetEphemeralStartTimestamp()), 0)
  640. }
  641. mainInfo := &wrappedInfo{
  642. MessageInfo: info,
  643. Type: database.MsgNormal,
  644. SenderMXID: mainEvt.Sender,
  645. Error: converted.Error,
  646. MediaKey: converted.MediaKey,
  647. ExpirationStart: expirationStart,
  648. ExpiresIn: converted.ExpiresIn,
  649. }
  650. if converted.Caption != nil {
  651. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil, "caption")
  652. if err != nil {
  653. return err
  654. }
  655. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  656. *infoArray = append(*infoArray, mainInfo, nil)
  657. } else {
  658. *eventsArray = append(*eventsArray, mainEvt)
  659. *infoArray = append(*infoArray, mainInfo)
  660. }
  661. if converted.MultiEvent != nil {
  662. for i, subEvtContent := range converted.MultiEvent {
  663. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil, fmt.Sprintf("multi-%d", i))
  664. if err != nil {
  665. return err
  666. }
  667. *eventsArray = append(*eventsArray, subEvt)
  668. *infoArray = append(*infoArray, nil)
  669. }
  670. }
  671. for _, reaction := range raw.GetReactions() {
  672. reactionEvent, reactionInfo := portal.wrapBatchReaction(source, reaction, mainEvt.ID, info.Timestamp)
  673. if reactionEvent != nil {
  674. *eventsArray = append(*eventsArray, reactionEvent)
  675. *infoArray = append(*infoArray, &wrappedInfo{
  676. MessageInfo: reactionInfo,
  677. SenderMXID: reactionEvent.Sender,
  678. ReactionTarget: info.ID,
  679. Type: database.MsgReaction,
  680. })
  681. }
  682. }
  683. return nil
  684. }
  685. func (portal *Portal) wrapBatchReaction(source *User, reaction *waProto.Reaction, mainEventID id.EventID, mainEventTS time.Time) (reactionEvent *event.Event, reactionInfo *types.MessageInfo) {
  686. var senderJID types.JID
  687. if reaction.GetKey().GetFromMe() {
  688. senderJID = source.JID.ToNonAD()
  689. } else if reaction.GetKey().GetParticipant() != "" {
  690. senderJID, _ = types.ParseJID(reaction.GetKey().GetParticipant())
  691. } else if portal.IsPrivateChat() {
  692. senderJID = portal.Key.JID
  693. }
  694. if senderJID.IsEmpty() {
  695. return
  696. }
  697. reactionInfo = &types.MessageInfo{
  698. MessageSource: types.MessageSource{
  699. Chat: portal.Key.JID,
  700. Sender: senderJID,
  701. IsFromMe: reaction.GetKey().GetFromMe(),
  702. IsGroup: portal.IsGroupChat(),
  703. },
  704. ID: reaction.GetKey().GetId(),
  705. Timestamp: mainEventTS,
  706. }
  707. puppet := portal.getMessagePuppet(source, reactionInfo)
  708. if puppet == nil {
  709. return
  710. }
  711. intent := puppet.IntentFor(portal)
  712. content := event.ReactionEventContent{
  713. RelatesTo: event.RelatesTo{
  714. Type: event.RelAnnotation,
  715. EventID: mainEventID,
  716. Key: variationselector.Add(reaction.GetText()),
  717. },
  718. }
  719. if rawTS := reaction.GetSenderTimestampMs(); rawTS >= mainEventTS.UnixMilli() && rawTS <= time.Now().UnixMilli() {
  720. reactionInfo.Timestamp = time.UnixMilli(rawTS)
  721. }
  722. wrappedContent := event.Content{Parsed: &content}
  723. intent.AddDoublePuppetValue(&wrappedContent)
  724. reactionEvent = &event.Event{
  725. ID: portal.deterministicEventID(senderJID, reactionInfo.ID, ""),
  726. Type: event.EventReaction,
  727. Content: wrappedContent,
  728. Sender: intent.UserID,
  729. Timestamp: reactionInfo.Timestamp.UnixMilli(),
  730. }
  731. return
  732. }
  733. 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) {
  734. wrappedContent := event.Content{
  735. Parsed: content,
  736. Raw: extraContent,
  737. }
  738. newEventType, err := portal.encrypt(intent, &wrappedContent, eventType)
  739. if err != nil {
  740. return nil, err
  741. }
  742. intent.AddDoublePuppetValue(&wrappedContent)
  743. return &event.Event{
  744. ID: portal.deterministicEventID(info.Sender, info.ID, partName),
  745. Sender: intent.UserID,
  746. Type: newEventType,
  747. Timestamp: info.Timestamp.UnixMilli(),
  748. Content: wrappedContent,
  749. }, nil
  750. }
  751. func (portal *Portal) finishBatch(txn dbutil.Transaction, eventIDs []id.EventID, infos []*wrappedInfo) {
  752. for i, info := range infos {
  753. if info == nil {
  754. continue
  755. }
  756. eventID := eventIDs[i]
  757. portal.markHandled(txn, nil, info.MessageInfo, eventID, info.SenderMXID, true, false, info.Type, info.Error)
  758. if info.Type == database.MsgReaction {
  759. portal.upsertReaction(txn, nil, info.ReactionTarget, info.Sender, eventID, info.ID)
  760. }
  761. if info.ExpiresIn > 0 {
  762. portal.MarkDisappearing(txn, eventID, info.ExpiresIn, info.ExpirationStart)
  763. }
  764. }
  765. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  766. }
  767. func (portal *Portal) updateBackfillStatus(backfillState *database.BackfillState) {
  768. backfillStatus := "backfilling"
  769. if backfillState.BackfillComplete {
  770. backfillStatus = "complete"
  771. }
  772. _, err := portal.bridge.Bot.SendStateEvent(portal.MXID, BackfillStatusEvent, "", map[string]interface{}{
  773. "status": backfillStatus,
  774. "first_timestamp": backfillState.FirstExpectedTimestamp * 1000,
  775. })
  776. if err != nil {
  777. portal.log.Errorln("Error sending backfill status event:", err)
  778. }
  779. }
  780. // endregion