historysync.go 27 KB

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