historysync.go 28 KB

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