historysync.go 25 KB

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