historysync.go 27 KB

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