historysync.go 27 KB

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