historysync.go 31 KB

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