historysync.go 33 KB

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