historysync.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. "fmt"
  19. "time"
  20. waProto "go.mau.fi/whatsmeow/binary/proto"
  21. "go.mau.fi/whatsmeow/types"
  22. "maunium.net/go/mautrix"
  23. "maunium.net/go/mautrix/appservice"
  24. "maunium.net/go/mautrix/event"
  25. "maunium.net/go/mautrix/id"
  26. "maunium.net/go/mautrix-whatsapp/config"
  27. "maunium.net/go/mautrix-whatsapp/database"
  28. )
  29. // region User history sync handling
  30. type wrappedInfo struct {
  31. *types.MessageInfo
  32. Type database.MessageType
  33. Error database.MessageErrorType
  34. MediaKey []byte
  35. ExpirationStart uint64
  36. ExpiresIn uint32
  37. }
  38. func (user *User) handleHistorySyncsLoop() {
  39. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  40. return
  41. }
  42. reCheckQueue := make(chan bool, 1)
  43. // Start the backfill queue.
  44. user.BackfillQueue = &BackfillQueue{
  45. BackfillQuery: user.bridge.DB.Backfill,
  46. ImmediateBackfillRequests: make(chan *database.Backfill, 1),
  47. DeferredBackfillRequests: make(chan *database.Backfill, 1),
  48. ReCheckQueue: make(chan bool, 1),
  49. log: user.log.Sub("BackfillQueue"),
  50. }
  51. reCheckQueue = user.BackfillQueue.ReCheckQueue
  52. // Immediate backfills can be done in parallel
  53. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  54. go user.handleBackfillRequestsLoop(user.BackfillQueue.ImmediateBackfillRequests)
  55. }
  56. // Deferred backfills should be handled synchronously so as not to
  57. // overload the homeserver. Users can configure their backfill stages
  58. // to be more or less aggressive with backfilling at this stage.
  59. go user.handleBackfillRequestsLoop(user.BackfillQueue.DeferredBackfillRequests)
  60. go user.BackfillQueue.RunLoop(user)
  61. if user.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia &&
  62. user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod == config.MediaRequestMethodLocalTime {
  63. go user.dailyMediaRequestLoop()
  64. }
  65. // Always save the history syncs for the user. If they want to enable
  66. // backfilling in the future, we will have it in the database.
  67. for evt := range user.historySyncs {
  68. user.handleHistorySync(reCheckQueue, evt.Data)
  69. }
  70. }
  71. func (user *User) dailyMediaRequestLoop() {
  72. // Calculate when to do the first set of media retry requests
  73. now := time.Now()
  74. userTz, err := time.LoadLocation(user.Timezone)
  75. if err != nil {
  76. userTz = now.Local().Location()
  77. }
  78. tonightMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, userTz)
  79. midnightOffset := time.Duration(user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestLocalTime) * time.Minute
  80. requestStartTime := tonightMidnight.Add(midnightOffset)
  81. // If the request time for today has already happened, we need to start the
  82. // request loop tomorrow instead.
  83. if requestStartTime.Before(now) {
  84. requestStartTime = requestStartTime.AddDate(0, 0, 1)
  85. }
  86. // Wait to start the loop
  87. user.log.Infof("Waiting until %s to do media retry requests", requestStartTime)
  88. time.Sleep(time.Until(requestStartTime))
  89. for {
  90. mediaBackfillRequests := user.bridge.DB.MediaBackfillRequest.GetMediaBackfillRequestsForUser(user.MXID)
  91. user.log.Infof("Sending %d media retry requests", len(mediaBackfillRequests))
  92. // Send all of the media backfill requests for the user at once
  93. for _, req := range mediaBackfillRequests {
  94. portal := user.GetPortalByJID(req.PortalKey.JID)
  95. _, err := portal.requestMediaRetry(user, req.EventID, req.MediaKey)
  96. if err != nil {
  97. user.log.Warnf("Failed to send media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  98. req.Status = database.MediaBackfillRequestStatusRequestFailed
  99. req.Error = err.Error()
  100. } else {
  101. user.log.Debugfln("Sent media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  102. req.Status = database.MediaBackfillRequestStatusRequested
  103. }
  104. req.MediaKey = nil
  105. req.Upsert()
  106. }
  107. // Wait for 24 hours before making requests again
  108. time.Sleep(24 * time.Hour)
  109. }
  110. }
  111. func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Backfill) {
  112. for req := range backfillRequests {
  113. user.log.Infofln("Handling backfill request %s", req)
  114. conv := user.bridge.DB.HistorySync.GetConversation(user.MXID, req.Portal)
  115. if conv == nil {
  116. user.log.Debugfln("Could not find history sync conversation data for %s", req.Portal.String())
  117. continue
  118. }
  119. portal := user.GetPortalByJID(conv.PortalKey.JID)
  120. // Update the client store with basic chat settings.
  121. if conv.MuteEndTime.After(time.Now()) {
  122. user.Client.Store.ChatSettings.PutMutedUntil(conv.PortalKey.JID, conv.MuteEndTime)
  123. }
  124. if conv.Archived {
  125. user.Client.Store.ChatSettings.PutArchived(conv.PortalKey.JID, true)
  126. }
  127. if conv.Pinned > 0 {
  128. user.Client.Store.ChatSettings.PutPinned(conv.PortalKey.JID, true)
  129. }
  130. if conv.EphemeralExpiration != nil && portal.ExpirationTime != *conv.EphemeralExpiration {
  131. portal.ExpirationTime = *conv.EphemeralExpiration
  132. portal.Update()
  133. }
  134. user.backfillInChunks(req, conv, portal)
  135. }
  136. }
  137. func (user *User) backfillInChunks(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
  138. portal.backfillLock.Lock()
  139. defer portal.backfillLock.Unlock()
  140. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  141. return
  142. }
  143. var forwardPrevID id.EventID
  144. var timeEnd *time.Time
  145. if req.BackfillType == database.BackfillForward {
  146. // TODO this overrides the TimeStart set when enqueuing the backfill
  147. // maybe the enqueue should instead include the prev event ID
  148. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  149. forwardPrevID = lastMessage.MXID
  150. start := lastMessage.Timestamp.Add(1 * time.Second)
  151. req.TimeStart = &start
  152. } else {
  153. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  154. if firstMessage != nil {
  155. end := firstMessage.Timestamp.Add(-1 * time.Second)
  156. timeEnd = &end
  157. user.log.Debugfln("Limiting backfill to end at %v", end)
  158. }
  159. }
  160. allMsgs := user.bridge.DB.HistorySync.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, timeEnd, req.MaxTotalEvents)
  161. sendDisappearedNotice := false
  162. // If expired messages are on, and a notice has not been sent to this chat
  163. // about it having disappeared messages at the conversation timestamp, send
  164. // a notice indicating so.
  165. if len(allMsgs) == 0 && conv.EphemeralExpiration != nil && *conv.EphemeralExpiration > 0 {
  166. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  167. if lastMessage == nil || conv.LastMessageTimestamp.After(lastMessage.Timestamp) {
  168. sendDisappearedNotice = true
  169. }
  170. }
  171. if !sendDisappearedNotice && len(allMsgs) == 0 {
  172. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  173. return
  174. }
  175. if len(portal.MXID) == 0 {
  176. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  177. err := portal.CreateMatrixRoom(user, nil, true, false)
  178. if err != nil {
  179. user.log.Errorfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  180. return
  181. }
  182. }
  183. if sendDisappearedNotice {
  184. user.log.Debugfln("Sending notice to %s that there are disappeared messages ending at %v", portal.Key.JID, conv.LastMessageTimestamp)
  185. resp, err := portal.sendMessage(portal.MainIntent(), event.EventMessage, &event.MessageEventContent{
  186. MsgType: event.MsgNotice,
  187. Body: portal.formatDisappearingMessageNotice(),
  188. }, nil, conv.LastMessageTimestamp.UnixMilli())
  189. if err != nil {
  190. portal.log.Errorln("Error sending disappearing messages notice event")
  191. return
  192. }
  193. msg := portal.bridge.DB.Message.New()
  194. msg.Chat = portal.Key
  195. msg.MXID = resp.EventID
  196. msg.JID = types.MessageID(resp.EventID)
  197. msg.Timestamp = conv.LastMessageTimestamp
  198. msg.Sent = true
  199. msg.Type = database.MsgFake
  200. msg.Insert()
  201. return
  202. }
  203. 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)
  204. toBackfill := allMsgs[0:]
  205. var insertionEventIds []id.EventID
  206. for len(toBackfill) > 0 {
  207. var msgs []*waProto.WebMessageInfo
  208. if len(toBackfill) <= req.MaxBatchEvents || req.MaxBatchEvents < 0 {
  209. msgs = toBackfill
  210. toBackfill = nil
  211. } else {
  212. msgs = toBackfill[:req.MaxBatchEvents]
  213. toBackfill = toBackfill[req.MaxBatchEvents:]
  214. }
  215. if len(msgs) > 0 {
  216. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  217. user.log.Debugfln("Backfilling %d messages in %s (queue ID: %d)", len(msgs), portal.Key.JID, req.QueueID)
  218. resp := portal.backfill(user, msgs, req.BackfillType == database.BackfillForward, forwardPrevID)
  219. if resp != nil {
  220. insertionEventIds = append(insertionEventIds, resp.BaseInsertionEventID)
  221. }
  222. }
  223. }
  224. user.log.Debugfln("Finished backfilling %d messages in %s (queue ID: %d)", len(allMsgs), portal.Key.JID, req.QueueID)
  225. if len(insertionEventIds) > 0 {
  226. portal.sendPostBackfillDummy(
  227. time.Unix(int64(allMsgs[0].GetMessageTimestamp()), 0),
  228. insertionEventIds[0])
  229. }
  230. user.log.Debugfln("Deleting %d history sync messages after backfilling (queue ID: %d)", len(allMsgs), req.QueueID)
  231. err := user.bridge.DB.HistorySync.DeleteMessages(user.MXID, conv.ConversationID, allMsgs)
  232. if err != nil {
  233. user.log.Warnfln("Failed to delete %d history sync messages after backfilling (queue ID: %d): %v", len(allMsgs), req.QueueID, err)
  234. }
  235. if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
  236. user.markSelfReadFull(portal)
  237. }
  238. }
  239. func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
  240. if len(portal.MXID) > 0 {
  241. if !user.bridge.AS.StateStore.IsInRoom(portal.MXID, user.MXID) {
  242. portal.ensureUserInvited(user)
  243. }
  244. // Portal exists, let backfill continue
  245. return true
  246. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  247. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  248. } else {
  249. // Portal doesn't exist, but should be created
  250. return true
  251. }
  252. // Portal shouldn't be created, reason logged above
  253. return false
  254. }
  255. func (user *User) handleHistorySync(reCheckQueue chan bool, evt *waProto.HistorySync) {
  256. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  257. return
  258. }
  259. description := fmt.Sprintf("type %s, %d conversations, chunk order %d, progress: %d", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder(), evt.GetProgress())
  260. user.log.Infoln("Storing history sync with", description)
  261. for _, conv := range evt.GetConversations() {
  262. jid, err := types.ParseJID(conv.GetId())
  263. if err != nil {
  264. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  265. continue
  266. } else if jid.Server == types.BroadcastServer {
  267. user.log.Debugfln("Skipping broadcast list %s in history sync", jid)
  268. continue
  269. }
  270. portal := user.GetPortalByJID(jid)
  271. historySyncConversation := user.bridge.DB.HistorySync.NewConversationWithValues(
  272. user.MXID,
  273. conv.GetId(),
  274. &portal.Key,
  275. getConversationTimestamp(conv),
  276. conv.GetMuteEndTime(),
  277. conv.GetArchived(),
  278. conv.GetPinned(),
  279. conv.GetDisappearingMode().GetInitiator(),
  280. conv.GetEndOfHistoryTransferType(),
  281. conv.EphemeralExpiration,
  282. conv.GetMarkedAsUnread(),
  283. conv.GetUnreadCount())
  284. historySyncConversation.Upsert()
  285. for _, rawMsg := range conv.GetMessages() {
  286. // Don't store messages that will just be skipped.
  287. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, rawMsg.GetMessage())
  288. if err != nil {
  289. continue
  290. }
  291. msgType := getMessageType(msgEvt.Message)
  292. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  293. continue
  294. }
  295. // Don't store unsupported messages.
  296. if !containsSupportedMessage(msgEvt.Message) {
  297. continue
  298. }
  299. message, err := user.bridge.DB.HistorySync.NewMessageWithValues(user.MXID, conv.GetId(), msgEvt.Info.ID, rawMsg)
  300. if err != nil {
  301. user.log.Warnfln("Failed to save message %s in %s. Error: %+v", msgEvt.Info.ID, conv.GetId(), err)
  302. continue
  303. }
  304. message.Insert()
  305. }
  306. }
  307. // If this was the initial bootstrap, enqueue immediate backfills for the
  308. // most recent portals. If it's the last history sync event, start
  309. // backfilling the rest of the history of the portals.
  310. if user.bridge.Config.Bridge.HistorySync.Backfill {
  311. if evt.GetSyncType() != waProto.HistorySync_INITIAL_BOOTSTRAP && evt.GetProgress() < 98 {
  312. return
  313. }
  314. nMostRecent := user.bridge.DB.HistorySync.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  315. if len(nMostRecent) > 0 {
  316. // Find the portals for all of the conversations.
  317. portals := []*Portal{}
  318. for _, conv := range nMostRecent {
  319. jid, err := types.ParseJID(conv.ConversationID)
  320. if err != nil {
  321. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  322. continue
  323. }
  324. portals = append(portals, user.GetPortalByJID(jid))
  325. }
  326. switch evt.GetSyncType() {
  327. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  328. // Enqueue immediate backfills for the most recent messages first.
  329. user.EnqueueImmedateBackfills(portals)
  330. case waProto.HistorySync_FULL, waProto.HistorySync_RECENT:
  331. user.EnqueueForwardBackfills(portals)
  332. // Enqueue deferred backfills as configured.
  333. user.EnqueueDeferredBackfills(portals)
  334. }
  335. // Tell the queue to check for new backfill requests.
  336. reCheckQueue <- true
  337. }
  338. }
  339. }
  340. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  341. convTs := conv.GetConversationTimestamp()
  342. if convTs == 0 && len(conv.GetMessages()) > 0 {
  343. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  344. }
  345. return convTs
  346. }
  347. func (user *User) EnqueueImmedateBackfills(portals []*Portal) {
  348. for priority, portal := range portals {
  349. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  350. initialBackfill := user.bridge.DB.Backfill.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, maxMessages, maxMessages, 0)
  351. initialBackfill.Insert()
  352. }
  353. }
  354. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  355. numPortals := len(portals)
  356. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  357. for portalIdx, portal := range portals {
  358. var startDate *time.Time = nil
  359. if backfillStage.StartDaysAgo > 0 {
  360. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  361. startDate = &startDaysAgo
  362. }
  363. backfillMessages := user.bridge.DB.Backfill.NewWithValues(
  364. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  365. backfillMessages.Insert()
  366. }
  367. }
  368. }
  369. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  370. for priority, portal := range portals {
  371. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  372. if lastMsg == nil {
  373. continue
  374. }
  375. backfill := user.bridge.DB.Backfill.NewWithValues(
  376. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, -1, -1, 0)
  377. backfill.Insert()
  378. }
  379. }
  380. // endregion
  381. // region Portal backfilling
  382. var (
  383. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  384. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  385. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  386. HistorySyncMarker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  387. )
  388. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward bool, prevEventID id.EventID) *mautrix.RespBatchSend {
  389. var req mautrix.ReqBatchSend
  390. var infos []*wrappedInfo
  391. if !isForward {
  392. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  393. req.PrevEventID = portal.FirstEventID
  394. req.BatchID = portal.NextBatchID
  395. } else {
  396. portal.log.Warnfln("Can't backfill %d messages through %s to chat: first event ID not known", len(messages), source.MXID)
  397. return nil
  398. }
  399. } else {
  400. req.PrevEventID = prevEventID
  401. }
  402. beforeFirstMessageTimestampMillis := (int64(messages[len(messages)-1].GetMessageTimestamp()) * 1000) - 1
  403. req.StateEventsAtStart = make([]*event.Event, 0)
  404. addedMembers := make(map[id.UserID]struct{})
  405. addMember := func(puppet *Puppet) {
  406. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  407. return
  408. }
  409. mxid := puppet.MXID.String()
  410. content := event.MemberEventContent{
  411. Membership: event.MembershipJoin,
  412. Displayname: puppet.Displayname,
  413. AvatarURL: puppet.AvatarURL.CUString(),
  414. }
  415. inviteContent := content
  416. inviteContent.Membership = event.MembershipInvite
  417. req.StateEventsAtStart = append(req.StateEventsAtStart, &event.Event{
  418. Type: event.StateMember,
  419. Sender: portal.MainIntent().UserID,
  420. StateKey: &mxid,
  421. Timestamp: beforeFirstMessageTimestampMillis,
  422. Content: event.Content{Parsed: &inviteContent},
  423. }, &event.Event{
  424. Type: event.StateMember,
  425. Sender: puppet.MXID,
  426. StateKey: &mxid,
  427. Timestamp: beforeFirstMessageTimestampMillis,
  428. Content: event.Content{Parsed: &content},
  429. })
  430. addedMembers[puppet.MXID] = struct{}{}
  431. }
  432. portal.log.Infofln("Processing history sync with %d messages (forward: %t, prev: %s, batch: %s)", len(messages), isForward, req.PrevEventID, req.BatchID)
  433. // The messages are ordered newest to oldest, so iterate them in reverse order.
  434. for i := len(messages) - 1; i >= 0; i-- {
  435. webMsg := messages[i]
  436. msgEvt, err := source.Client.ParseWebMessage(portal.Key.JID, webMsg)
  437. if err != nil {
  438. continue
  439. }
  440. msgType := getMessageType(msgEvt.Message)
  441. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  442. if msgType != "ignore" {
  443. portal.log.Debugfln("Skipping message %s with unknown type in backfill", msgEvt.Info.ID)
  444. }
  445. continue
  446. }
  447. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  448. existingContact, _ := source.Client.Store.Contacts.GetContact(msgEvt.Info.Sender)
  449. if !existingContact.Found || existingContact.PushName == "" {
  450. changed, _, err := source.Client.Store.Contacts.PutPushName(msgEvt.Info.Sender, webMsg.GetPushName())
  451. if err != nil {
  452. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", msgEvt.Info.Sender, err)
  453. } else if changed {
  454. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), msgEvt.Info.Sender)
  455. }
  456. }
  457. }
  458. puppet := portal.getMessagePuppet(source, &msgEvt.Info)
  459. intent := puppet.IntentFor(portal)
  460. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  461. intent = puppet.DefaultIntent()
  462. }
  463. converted := portal.convertMessage(intent, source, &msgEvt.Info, msgEvt.Message, true)
  464. if converted == nil {
  465. portal.log.Debugfln("Skipping unsupported message %s in backfill", msgEvt.Info.ID)
  466. continue
  467. }
  468. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  469. addMember(puppet)
  470. }
  471. // TODO this won't work for history
  472. if len(converted.ReplyTo) > 0 {
  473. portal.SetReply(converted.Content, converted.ReplyTo)
  474. }
  475. err = portal.appendBatchEvents(converted, &msgEvt.Info, webMsg.GetEphemeralStartTimestamp(), &req.Events, &infos)
  476. if err != nil {
  477. portal.log.Errorfln("Error handling message %s during backfill: %v", msgEvt.Info.ID, err)
  478. }
  479. }
  480. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  481. if len(req.Events) == 0 {
  482. return nil
  483. }
  484. if len(req.BatchID) == 0 || isForward {
  485. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  486. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  487. if err != nil {
  488. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  489. }
  490. }
  491. resp, err := portal.MainIntent().BatchSend(portal.MXID, &req)
  492. if err != nil {
  493. portal.log.Errorln("Error batch sending messages:", err)
  494. return nil
  495. } else {
  496. portal.finishBatch(resp.EventIDs, infos)
  497. portal.NextBatchID = resp.NextBatchID
  498. portal.Update()
  499. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia {
  500. go portal.requestMediaRetries(source, resp.EventIDs, infos)
  501. }
  502. return resp
  503. }
  504. }
  505. func (portal *Portal) requestMediaRetries(source *User, eventIDs []id.EventID, infos []*wrappedInfo) {
  506. for i, info := range infos {
  507. if info != nil && info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  508. switch portal.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod {
  509. case config.MediaRequestMethodImmediate:
  510. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  511. if err != nil {
  512. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  513. } else {
  514. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  515. }
  516. case config.MediaRequestMethodLocalTime:
  517. req := portal.bridge.DB.MediaBackfillRequest.NewMediaBackfillRequestWithValues(source.MXID, &portal.Key, eventIDs[i], info.MediaKey)
  518. req.Upsert()
  519. }
  520. }
  521. }
  522. }
  523. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  524. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  525. if err != nil {
  526. return err
  527. }
  528. if converted.Caption != nil {
  529. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  530. if err != nil {
  531. return err
  532. }
  533. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  534. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn}, nil)
  535. } else {
  536. *eventsArray = append(*eventsArray, mainEvt)
  537. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn})
  538. }
  539. if converted.MultiEvent != nil {
  540. for _, subEvtContent := range converted.MultiEvent {
  541. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil)
  542. if err != nil {
  543. return err
  544. }
  545. *eventsArray = append(*eventsArray, subEvt)
  546. *infoArray = append(*infoArray, nil)
  547. }
  548. }
  549. return nil
  550. }
  551. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  552. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  553. if extraContent == nil {
  554. extraContent = map[string]interface{}{}
  555. }
  556. extraContent[backfillIDField] = info.ID
  557. if intent.IsCustomPuppet {
  558. extraContent[doublePuppetKey] = doublePuppetValue
  559. }
  560. wrappedContent := event.Content{
  561. Parsed: content,
  562. Raw: extraContent,
  563. }
  564. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  565. if err != nil {
  566. return nil, err
  567. }
  568. if newEventType == event.EventEncrypted {
  569. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  570. wrappedContent.Raw = map[string]interface{}{backfillIDField: info.ID}
  571. if intent.IsCustomPuppet {
  572. wrappedContent.Raw[doublePuppetKey] = doublePuppetValue
  573. }
  574. }
  575. return &event.Event{
  576. Sender: intent.UserID,
  577. Type: newEventType,
  578. Timestamp: info.Timestamp.UnixMilli(),
  579. Content: wrappedContent,
  580. }, nil
  581. }
  582. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*wrappedInfo) {
  583. if len(eventIDs) != len(infos) {
  584. portal.log.Errorfln("Length of event IDs (%d) and message infos (%d) doesn't match! Using slow path for mapping event IDs", len(eventIDs), len(infos))
  585. infoMap := make(map[types.MessageID]*wrappedInfo, len(infos))
  586. for _, info := range infos {
  587. infoMap[info.ID] = info
  588. }
  589. for _, eventID := range eventIDs {
  590. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  591. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  592. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  593. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  594. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  595. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  596. } else {
  597. portal.finishBatchEvt(info, eventID)
  598. }
  599. }
  600. } else {
  601. for i := 0; i < len(infos); i++ {
  602. portal.finishBatchEvt(infos[i], eventIDs[i])
  603. }
  604. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  605. }
  606. }
  607. func (portal *Portal) finishBatchEvt(info *wrappedInfo, eventID id.EventID) {
  608. if info == nil {
  609. return
  610. }
  611. portal.markHandled(nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  612. if info.ExpiresIn > 0 {
  613. if info.ExpirationStart > 0 {
  614. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  615. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  616. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  617. } else {
  618. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  619. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  620. }
  621. }
  622. }
  623. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  624. // TODO remove after clients stop using this
  625. _, _ = portal.MainIntent().SendMessageEvent(portal.MXID, BackfillEndDummyEvent, struct{}{})
  626. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, HistorySyncMarker, map[string]interface{}{
  627. "org.matrix.msc2716.marker.insertion": insertionEventId,
  628. //"m.marker.insertion": insertionEventId,
  629. })
  630. if err != nil {
  631. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  632. return
  633. }
  634. msg := portal.bridge.DB.Message.New()
  635. msg.Chat = portal.Key
  636. msg.MXID = resp.EventID
  637. msg.JID = types.MessageID(resp.EventID)
  638. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  639. msg.Sent = true
  640. msg.Type = database.MsgFake
  641. msg.Insert()
  642. }
  643. // endregion