historysync.go 26 KB

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