historysync.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. "sort"
  19. "sync"
  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. )
  28. // region User history sync handling
  29. const (
  30. FastBackfillPortalCount = 20
  31. FastBackfillMessageCount = 20
  32. FastBackfillMessageCap = 30
  33. )
  34. type portalToBackfill struct {
  35. portal *Portal
  36. conv *waProto.Conversation
  37. msgs []*waProto.WebMessageInfo
  38. }
  39. type conversationList []*waProto.Conversation
  40. var _ sort.Interface = (conversationList)(nil)
  41. func (c conversationList) Len() int {
  42. return len(c)
  43. }
  44. func (c conversationList) Less(i, j int) bool {
  45. return c[i].GetConversationTimestamp() < c[j].GetConversationTimestamp()
  46. }
  47. func (c conversationList) Swap(i, j int) {
  48. c[i], c[j] = c[j], c[i]
  49. }
  50. func (user *User) handleHistorySyncsLoop() {
  51. for evt := range user.historySyncs {
  52. user.handleHistorySync(evt.Data)
  53. }
  54. }
  55. func (user *User) handleHistorySync(evt *waProto.HistorySync) {
  56. if evt.GetSyncType() != waProto.HistorySync_RECENT && evt.GetSyncType() != waProto.HistorySync_FULL {
  57. return
  58. }
  59. user.log.Infofln("Handling history sync with type %s, chunk order %d, progress %d%%", evt.GetSyncType(), evt.GetChunkOrder(), evt.GetProgress())
  60. conversations := conversationList(evt.GetConversations())
  61. // We want to handle recent conversations first
  62. sort.Sort(sort.Reverse(conversations))
  63. portalsToBackfill := make(chan portalToBackfill, len(conversations))
  64. var backfillWait, fastBackfillWait sync.WaitGroup
  65. var fastBackfillWaitDoneOnce sync.Once
  66. // We have to add 1 to the waitgroup beforehand to make sure the wait in the goroutine doesn't finish
  67. // before we add the actual numbers.
  68. fastBackfillWait.Add(1)
  69. backfillWait.Add(1)
  70. go func() {
  71. // Wait for the fast parallelized backfill to complete, then start the slow backfill loop (see explanation below)
  72. fastBackfillWait.Wait()
  73. user.slowBackfillLoop(portalsToBackfill, backfillWait.Done)
  74. }()
  75. for i, conv := range conversations {
  76. // This will create portals and start backfilling for them.
  77. //
  78. // The first 20 (FastBackfillPortalCount) portals will be parallelized, where the portal is
  79. // created and recent messages are backfilled in parallel. Other portals will be created
  80. // synchronously (and this will only return when they're created).
  81. //
  82. // For said other portals, and older messages in the parallelized portals, backfilling also
  83. // happens synchronously: the portals and messages to backfill are added to the
  84. // portalsToBackfill channel, which is consumed one-by-one in the slowBackfillLoop method.
  85. // That loop is only started after the fast parallelized backfill is completed.
  86. user.handleHistorySyncConversation(i, conv, &fastBackfillWait, portalsToBackfill)
  87. if i == FastBackfillPortalCount {
  88. // There won't be any more portals going the fast backfill route, so remove the 1 item
  89. // that was added to the wait group at the beginning.
  90. fastBackfillWaitDoneOnce.Do(fastBackfillWait.Done)
  91. }
  92. }
  93. fastBackfillWaitDoneOnce.Do(fastBackfillWait.Done)
  94. // Wait for fast backfill to complete to make sure everything necessary is in the slow backfill queue,
  95. // then close the slow backfill queue and wait for the loop to finish handling the queue.
  96. fastBackfillWait.Wait()
  97. close(portalsToBackfill)
  98. backfillWait.Wait()
  99. user.log.Infofln("Finished handling history sync with type %s, chunk order %d, progress %d%%", evt.GetSyncType(), evt.GetChunkOrder(), evt.GetProgress())
  100. }
  101. func (user *User) slowBackfillLoop(ch chan portalToBackfill, done func()) {
  102. defer done()
  103. for ptb := range ch {
  104. if len(ptb.msgs) > 0 {
  105. user.log.Debugln("Bridging history sync payload for", ptb.portal.Key.JID)
  106. ptb.portal.backfill(user, ptb.msgs)
  107. }
  108. if !ptb.conv.GetMarkedAsUnread() && ptb.conv.GetUnreadCount() == 0 {
  109. user.markSelfReadFull(ptb.portal)
  110. }
  111. }
  112. }
  113. func (user *User) handleHistorySyncConversation(index int, conv *waProto.Conversation, fastBackfillWait *sync.WaitGroup, portalsToBackfill chan portalToBackfill) {
  114. jid, err := types.ParseJID(conv.GetId())
  115. if err != nil {
  116. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  117. return
  118. }
  119. // Update the client store with basic chat settings.
  120. muteEnd := time.Unix(int64(conv.GetMuteEndTime()), 0)
  121. if muteEnd.After(time.Now()) {
  122. _ = user.Client.Store.ChatSettings.PutMutedUntil(jid, muteEnd)
  123. }
  124. if conv.GetArchived() {
  125. _ = user.Client.Store.ChatSettings.PutArchived(jid, true)
  126. }
  127. if conv.GetPinned() > 0 {
  128. _ = user.Client.Store.ChatSettings.PutPinned(jid, true)
  129. }
  130. portal := user.GetPortalByJID(jid)
  131. // Check if portal is too old or doesn't contain anything we can bridge.
  132. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  133. return
  134. }
  135. var msgs []*waProto.WebMessageInfo
  136. if user.bridge.Config.Bridge.HistorySync.Backfill {
  137. msgs = filterMessagesToBackfill(conv.GetMessages())
  138. }
  139. ptb := portalToBackfill{portal: portal, conv: conv, msgs: msgs}
  140. if len(portal.MXID) == 0 {
  141. // For the first few chats, do the portal creation and some backfilling in parallel to populate the chat list ASAP
  142. if index < FastBackfillPortalCount {
  143. fastBackfillWait.Add(1)
  144. go user.fastBackfillRoutine(ptb, fastBackfillWait.Done, portalsToBackfill)
  145. return
  146. }
  147. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  148. err = portal.CreateMatrixRoom(user, getPartialInfoFromConversation(jid, conv), false)
  149. if err != nil {
  150. user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  151. return
  152. }
  153. }
  154. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  155. user.log.Debugln("Backfill is disabled, not bridging history sync payload for", portal.Key.JID)
  156. } else {
  157. portalsToBackfill <- ptb
  158. }
  159. }
  160. func (user *User) shouldCreatePortalForHistorySync(conv *waProto.Conversation, portal *Portal) bool {
  161. maxAge := user.bridge.Config.Bridge.HistorySync.MaxAge
  162. minLastMsgToCreate := time.Now().Add(-time.Duration(maxAge) * time.Second)
  163. lastMsg := time.Unix(int64(conv.GetConversationTimestamp()), 0)
  164. if len(portal.MXID) > 0 {
  165. user.log.Debugfln("Portal for %s already exists, ensuring user is invited", portal.Key.JID)
  166. portal.ensureUserInvited(user)
  167. // Portal exists, let backfill continue
  168. return true
  169. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  170. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  171. } else if !containsSupportedMessages(conv) {
  172. user.log.Debugfln("Not creating portal for %s: no interesting messages found", portal.Key.JID)
  173. } else if maxAge > 0 && !lastMsg.After(minLastMsgToCreate) {
  174. user.log.Debugfln("Not creating portal for %s: last message older than limit (%s)", portal.Key.JID, lastMsg)
  175. } else {
  176. // Portal doesn't exist, but should be created
  177. return true
  178. }
  179. // Portal shouldn't be created, reason logged above
  180. return false
  181. }
  182. func (user *User) fastBackfillRoutine(ptb portalToBackfill, done func(), slowBackfillChan chan portalToBackfill) {
  183. defer done()
  184. user.log.Debugln("Asynchronously creating portal for", ptb.portal.Key.JID, "as part of history sync handling")
  185. err := ptb.portal.CreateMatrixRoom(user, getPartialInfoFromConversation(ptb.portal.Key.JID, ptb.conv), false)
  186. if err != nil {
  187. user.log.Warnfln("Failed to create room for %s during backfill: %v", ptb.portal.Key.JID, err)
  188. }
  189. if user.bridge.Config.Bridge.HistorySync.Backfill {
  190. if len(ptb.msgs) > FastBackfillMessageCap {
  191. user.log.Debugln("Bridging first 20 messages of history sync payload for", ptb.portal.Key.JID, "(async)")
  192. ptb.portal.backfill(user, ptb.msgs[:FastBackfillMessageCount])
  193. // Send the rest of the messages off to the slow backfill queue
  194. ptb.msgs = ptb.msgs[FastBackfillMessageCount:]
  195. slowBackfillChan <- ptb
  196. } else if len(ptb.msgs) > 0 {
  197. user.log.Debugln("Bridging history sync payload for", ptb.portal.Key.JID, "(async)")
  198. ptb.portal.backfill(user, ptb.msgs)
  199. }
  200. } else {
  201. user.log.Debugln("Backfill is disabled, not bridging history sync payload for", ptb.portal.Key.JID)
  202. }
  203. }
  204. func filterMessagesToBackfill(messages []*waProto.HistorySyncMsg) []*waProto.WebMessageInfo {
  205. filtered := make([]*waProto.WebMessageInfo, 0, len(messages))
  206. for _, msg := range messages {
  207. wmi := msg.GetMessage()
  208. msgType := getMessageType(wmi.GetMessage())
  209. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  210. continue
  211. } else {
  212. filtered = append(filtered, wmi)
  213. }
  214. }
  215. return filtered
  216. }
  217. func containsSupportedMessages(conv *waProto.Conversation) bool {
  218. for _, msg := range conv.GetMessages() {
  219. if containsSupportedMessage(msg.GetMessage().GetMessage()) {
  220. return true
  221. }
  222. }
  223. return false
  224. }
  225. func getPartialInfoFromConversation(jid types.JID, conv *waProto.Conversation) *types.GroupInfo {
  226. // TODO broadcast list info?
  227. if jid.Server != types.GroupServer {
  228. return nil
  229. }
  230. participants := make([]types.GroupParticipant, len(conv.GetParticipant()))
  231. for i, pcp := range conv.GetParticipant() {
  232. participantJID, _ := types.ParseJID(pcp.GetUserJid())
  233. participants[i] = types.GroupParticipant{
  234. JID: participantJID,
  235. IsAdmin: pcp.GetRank() == waProto.GroupParticipant_ADMIN,
  236. IsSuperAdmin: pcp.GetRank() == waProto.GroupParticipant_SUPERADMIN,
  237. }
  238. }
  239. return &types.GroupInfo{
  240. JID: jid,
  241. GroupName: types.GroupName{Name: conv.GetName()},
  242. Participants: participants,
  243. }
  244. }
  245. // endregion
  246. // region Portal backfilling
  247. var (
  248. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  249. BackfillDummyStateEvent = event.Type{Type: "fi.mau.dummy.blank_backfill_state", Class: event.StateEventType}
  250. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  251. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  252. )
  253. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo) {
  254. portal.backfillLock.Lock()
  255. defer portal.backfillLock.Unlock()
  256. var historyBatch, newBatch mautrix.ReqBatchSend
  257. var historyBatchInfos, newBatchInfos []*types.MessageInfo
  258. firstMsgTimestamp := time.Unix(int64(messages[len(messages)-1].GetMessageTimestamp()), 0)
  259. historyBatch.StateEventsAtStart = make([]*event.Event, 1)
  260. newBatch.StateEventsAtStart = make([]*event.Event, 1)
  261. // TODO remove the dummy state events after https://github.com/matrix-org/synapse/pull/11188
  262. emptyStr := ""
  263. dummyStateEvent := event.Event{
  264. Type: BackfillDummyStateEvent,
  265. Sender: portal.MainIntent().UserID,
  266. StateKey: &emptyStr,
  267. Timestamp: firstMsgTimestamp.UnixMilli(),
  268. Content: event.Content{},
  269. }
  270. historyBatch.StateEventsAtStart[0] = &dummyStateEvent
  271. newBatch.StateEventsAtStart[0] = &dummyStateEvent
  272. addedMembers := make(map[id.UserID]*event.MemberEventContent)
  273. addMember := func(puppet *Puppet) {
  274. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  275. return
  276. }
  277. mxid := puppet.MXID.String()
  278. content := event.MemberEventContent{
  279. Membership: event.MembershipJoin,
  280. Displayname: puppet.Displayname,
  281. AvatarURL: puppet.AvatarURL.CUString(),
  282. }
  283. inviteContent := content
  284. inviteContent.Membership = event.MembershipInvite
  285. historyBatch.StateEventsAtStart = append(historyBatch.StateEventsAtStart, &event.Event{
  286. Type: event.StateMember,
  287. Sender: portal.MainIntent().UserID,
  288. StateKey: &mxid,
  289. Timestamp: firstMsgTimestamp.UnixMilli(),
  290. Content: event.Content{Parsed: &inviteContent},
  291. }, &event.Event{
  292. Type: event.StateMember,
  293. Sender: puppet.MXID,
  294. StateKey: &mxid,
  295. Timestamp: firstMsgTimestamp.UnixMilli(),
  296. Content: event.Content{Parsed: &content},
  297. })
  298. addedMembers[puppet.MXID] = &content
  299. }
  300. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  301. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  302. var historyMaxTs, newMinTs time.Time
  303. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  304. historyBatch.PrevEventID = portal.FirstEventID
  305. historyBatch.BatchID = portal.NextBatchID
  306. if firstMessage == nil && lastMessage == nil {
  307. historyMaxTs = time.Now()
  308. } else {
  309. historyMaxTs = firstMessage.Timestamp
  310. }
  311. }
  312. if lastMessage != nil {
  313. newBatch.PrevEventID = lastMessage.MXID
  314. newMinTs = lastMessage.Timestamp
  315. }
  316. portal.log.Infofln("Processing history sync with %d messages", len(messages))
  317. // The messages are ordered newest to oldest, so iterate them in reverse order.
  318. for i := len(messages) - 1; i >= 0; i-- {
  319. webMsg := messages[i]
  320. msgType := getMessageType(webMsg.GetMessage())
  321. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  322. if msgType != "ignore" {
  323. portal.log.Debugfln("Skipping message %s with unknown type in backfill", webMsg.GetKey().GetId())
  324. }
  325. continue
  326. }
  327. info := portal.parseWebMessageInfo(webMsg)
  328. if info == nil {
  329. continue
  330. }
  331. var batch *mautrix.ReqBatchSend
  332. var infos *[]*types.MessageInfo
  333. var history bool
  334. if !historyMaxTs.IsZero() && info.Timestamp.Before(historyMaxTs) {
  335. batch, infos, history = &historyBatch, &historyBatchInfos, true
  336. } else if !newMinTs.IsZero() && info.Timestamp.After(newMinTs) {
  337. batch, infos = &newBatch, &newBatchInfos
  338. } else {
  339. continue
  340. }
  341. puppet := portal.getMessagePuppet(source, info)
  342. var intent *appservice.IntentAPI
  343. if portal.Key.JID == puppet.JID {
  344. intent = puppet.DefaultIntent()
  345. } else {
  346. intent = puppet.IntentFor(portal)
  347. if intent.IsCustomPuppet && !portal.bridge.Config.Bridge.HistorySync.DoublePuppetBackfill {
  348. intent = puppet.DefaultIntent()
  349. addMember(puppet)
  350. }
  351. }
  352. converted := portal.convertMessage(intent, source, info, webMsg.GetMessage())
  353. if converted == nil {
  354. portal.log.Debugfln("Skipping unsupported message %s in backfill", info.ID)
  355. continue
  356. }
  357. if history && !portal.IsPrivateChat() && !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  358. addMember(puppet)
  359. }
  360. err := portal.appendBatchEvents(converted, info, &batch.Events, infos)
  361. if err != nil {
  362. portal.log.Errorfln("Error handling message %s during backfill: %v", info.ID, err)
  363. }
  364. }
  365. if (len(historyBatch.Events) > 0 && len(historyBatch.BatchID) == 0) || len(newBatch.Events) > 0 {
  366. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  367. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  368. if err != nil {
  369. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  370. }
  371. }
  372. if len(historyBatch.Events) > 0 && len(historyBatch.PrevEventID) > 0 {
  373. portal.log.Infofln("Sending %d historical messages...", len(historyBatch.Events))
  374. historyResp, err := portal.MainIntent().BatchSend(portal.MXID, &historyBatch)
  375. if err != nil {
  376. portal.log.Errorln("Error sending batch of historical messages:", err)
  377. } else {
  378. portal.finishBatch(historyResp.EventIDs, historyBatchInfos)
  379. portal.NextBatchID = historyResp.NextBatchID
  380. portal.Update()
  381. // If batchID is non-empty, it means this is backfilling very old messages, and we don't need a post-backfill dummy.
  382. if historyBatch.BatchID == "" {
  383. portal.sendPostBackfillDummy(time.UnixMilli(historyBatch.Events[len(historyBatch.Events)-1].Timestamp))
  384. }
  385. }
  386. }
  387. if len(newBatch.Events) > 0 && len(newBatch.PrevEventID) > 0 {
  388. portal.log.Infofln("Sending %d new messages...", len(newBatch.Events))
  389. newResp, err := portal.MainIntent().BatchSend(portal.MXID, &newBatch)
  390. if err != nil {
  391. portal.log.Errorln("Error sending batch of new messages:", err)
  392. } else {
  393. portal.finishBatch(newResp.EventIDs, newBatchInfos)
  394. portal.sendPostBackfillDummy(time.UnixMilli(newBatch.Events[len(newBatch.Events)-1].Timestamp))
  395. }
  396. }
  397. }
  398. func (portal *Portal) parseWebMessageInfo(webMsg *waProto.WebMessageInfo) *types.MessageInfo {
  399. info := types.MessageInfo{
  400. MessageSource: types.MessageSource{
  401. Chat: portal.Key.JID,
  402. IsFromMe: webMsg.GetKey().GetFromMe(),
  403. IsGroup: false,
  404. },
  405. ID: webMsg.GetKey().GetId(),
  406. PushName: webMsg.GetPushName(),
  407. Timestamp: time.Unix(int64(webMsg.GetMessageTimestamp()), 0),
  408. }
  409. var err error
  410. if info.IsFromMe {
  411. info.Sender = portal.Key.Receiver
  412. } else if portal.IsPrivateChat() {
  413. info.Sender = portal.Key.JID
  414. } else if webMsg.GetParticipant() != "" {
  415. info.Sender, err = types.ParseJID(webMsg.GetParticipant())
  416. } else if webMsg.GetKey().GetParticipant() != "" {
  417. info.Sender, err = types.ParseJID(webMsg.GetKey().GetParticipant())
  418. }
  419. if info.Sender.IsEmpty() {
  420. portal.log.Warnfln("Failed to get sender of message %s (parse error: %v)", info.ID, err)
  421. return nil
  422. }
  423. return &info
  424. }
  425. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, eventsArray *[]*event.Event, infoArray *[]*types.MessageInfo) error {
  426. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  427. if err != nil {
  428. return err
  429. }
  430. if converted.Caption != nil {
  431. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  432. if err != nil {
  433. return err
  434. }
  435. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  436. *infoArray = append(*infoArray, nil, info)
  437. } else {
  438. *eventsArray = append(*eventsArray, mainEvt)
  439. *infoArray = append(*infoArray, info)
  440. }
  441. return nil
  442. }
  443. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  444. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  445. if extraContent == nil {
  446. extraContent = map[string]interface{}{}
  447. }
  448. extraContent[backfillIDField] = info.ID
  449. if intent.IsCustomPuppet {
  450. extraContent[doublePuppetField] = intent.IsCustomPuppet
  451. }
  452. wrappedContent := event.Content{
  453. Parsed: content,
  454. Raw: extraContent,
  455. }
  456. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  457. if err != nil {
  458. return nil, err
  459. }
  460. return &event.Event{
  461. Sender: intent.UserID,
  462. Type: newEventType,
  463. Timestamp: info.Timestamp.UnixMilli(),
  464. Content: wrappedContent,
  465. }, nil
  466. }
  467. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*types.MessageInfo) {
  468. if len(eventIDs) != len(infos) {
  469. 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))
  470. infoMap := make(map[types.MessageID]*types.MessageInfo, len(infos))
  471. for _, info := range infos {
  472. infoMap[info.ID] = info
  473. }
  474. for _, eventID := range eventIDs {
  475. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  476. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  477. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  478. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  479. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  480. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  481. } else {
  482. portal.markHandled(nil, info, eventID, true, false, false)
  483. }
  484. }
  485. } else {
  486. for i := 0; i < len(infos); i++ {
  487. if infos[i] != nil {
  488. portal.markHandled(nil, infos[i], eventIDs[i], true, false, false)
  489. }
  490. }
  491. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  492. }
  493. }
  494. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time) {
  495. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, BackfillEndDummyEvent, struct{}{})
  496. if err != nil {
  497. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  498. return
  499. }
  500. msg := portal.bridge.DB.Message.New()
  501. msg.Chat = portal.Key
  502. msg.MXID = resp.EventID
  503. msg.JID = types.MessageID(resp.EventID)
  504. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  505. msg.Sent = true
  506. msg.Insert()
  507. }
  508. // endregion