historysync.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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/database"
  27. )
  28. // region User history sync handling
  29. type wrappedInfo struct {
  30. *types.MessageInfo
  31. Type database.MessageType
  32. Error database.MessageErrorType
  33. ExpirationStart uint64
  34. ExpiresIn uint32
  35. }
  36. func (user *User) handleHistorySyncsLoop() {
  37. reCheckQueue := make(chan bool, 1)
  38. if user.bridge.Config.Bridge.HistorySync.Backfill {
  39. // Start the backfill queue.
  40. user.BackfillQueue = &BackfillQueue{
  41. BackfillQuery: user.bridge.DB.BackfillQuery,
  42. ImmediateBackfillRequests: make(chan *database.Backfill, 1),
  43. DeferredBackfillRequests: make(chan *database.Backfill, 1),
  44. ReCheckQueue: make(chan bool, 1),
  45. log: user.log.Sub("BackfillQueue"),
  46. }
  47. reCheckQueue = user.BackfillQueue.ReCheckQueue
  48. // Immediate backfills can be done in parallel
  49. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  50. go user.handleBackfillRequestsLoop(user.BackfillQueue.ImmediateBackfillRequests)
  51. }
  52. // Deferred backfills should be handled synchronously so as not to
  53. // overload the homeserver. Users can configure their backfill stages
  54. // to be more or less aggressive with backfilling at this stage.
  55. go user.handleBackfillRequestsLoop(user.BackfillQueue.DeferredBackfillRequests)
  56. go user.BackfillQueue.RunLoops(user)
  57. }
  58. // Always save the history syncs for the user. If they want to enable
  59. // backfilling in the future, we will have it in the database.
  60. for evt := range user.historySyncs {
  61. user.handleHistorySync(reCheckQueue, evt.Data)
  62. }
  63. }
  64. func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Backfill) {
  65. for req := range backfillRequests {
  66. user.log.Infof("Backfill request: %v", req)
  67. conv := user.bridge.DB.HistorySyncQuery.GetConversation(user.MXID, req.Portal)
  68. if conv == nil {
  69. user.log.Errorf("Could not find conversation for %s in %s", user.MXID, req.Portal.String())
  70. continue
  71. }
  72. // Update the client store with basic chat settings.
  73. if conv.MuteEndTime.After(time.Now()) {
  74. user.Client.Store.ChatSettings.PutMutedUntil(conv.PortalKey.JID, conv.MuteEndTime)
  75. }
  76. if conv.Archived {
  77. user.Client.Store.ChatSettings.PutArchived(conv.PortalKey.JID, true)
  78. }
  79. if conv.Pinned > 0 {
  80. user.Client.Store.ChatSettings.PutPinned(conv.PortalKey.JID, true)
  81. }
  82. portal := user.GetPortalByJID(conv.PortalKey.JID)
  83. if conv.EphemeralExpiration != nil && portal.ExpirationTime != *conv.EphemeralExpiration {
  84. portal.ExpirationTime = *conv.EphemeralExpiration
  85. portal.Update()
  86. }
  87. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  88. continue
  89. }
  90. if len(portal.MXID) == 0 {
  91. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  92. err := portal.CreateMatrixRoom(user, nil, true, false)
  93. if err != nil {
  94. user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  95. continue
  96. }
  97. } else {
  98. portal.UpdateMatrixRoom(user, nil)
  99. }
  100. allMsgs := user.bridge.DB.HistorySyncQuery.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, req.TimeEnd, req.MaxTotalEvents)
  101. if len(allMsgs) > 0 {
  102. user.log.Debugf("Backfilling %d messages in %s, %d messages at a time", len(allMsgs), portal.Key.JID, req.MaxBatchEvents)
  103. toBackfill := allMsgs[0:]
  104. insertionEventIds := []id.EventID{}
  105. for {
  106. if len(toBackfill) == 0 {
  107. break
  108. }
  109. var msgs []*database.WrappedWebMessageInfo
  110. if len(toBackfill) <= req.MaxBatchEvents {
  111. msgs = toBackfill
  112. toBackfill = toBackfill[0:0]
  113. } else {
  114. msgs = toBackfill[len(toBackfill)-req.MaxBatchEvents:]
  115. toBackfill = toBackfill[:len(toBackfill)-req.MaxBatchEvents]
  116. }
  117. if len(msgs) > 0 {
  118. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  119. user.log.Debugf("Backfilling %d messages in %s", len(msgs), portal.Key.JID)
  120. insertionEventIds = append(insertionEventIds, portal.backfill(user, msgs)...)
  121. }
  122. }
  123. user.log.Debugf("Finished backfilling %d messages in %s", len(allMsgs), portal.Key.JID)
  124. if len(insertionEventIds) > 0 {
  125. portal.sendPostBackfillDummy(
  126. time.Unix(int64(allMsgs[len(allMsgs)-1].Message.GetMessageTimestamp()), 0),
  127. insertionEventIds[0])
  128. }
  129. user.log.Debugf("Deleting %d history sync messages after backfilling", len(allMsgs))
  130. err := user.bridge.DB.HistorySyncQuery.DeleteMessages(allMsgs)
  131. if err != nil {
  132. user.log.Warnf("Failed to delete %d history sync messages after backfilling: %v", len(allMsgs), err)
  133. }
  134. } else {
  135. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  136. }
  137. if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
  138. user.markSelfReadFull(portal)
  139. }
  140. }
  141. }
  142. func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
  143. if len(portal.MXID) > 0 {
  144. user.log.Debugfln("Portal for %s already exists, ensuring user is invited", portal.Key.JID)
  145. portal.ensureUserInvited(user)
  146. // Portal exists, let backfill continue
  147. return true
  148. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  149. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  150. } else {
  151. // Portal doesn't exist, but should be created
  152. return true
  153. }
  154. // Portal shouldn't be created, reason logged above
  155. return false
  156. }
  157. func (user *User) handleHistorySync(reCheckQueue chan bool, evt *waProto.HistorySync) {
  158. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  159. return
  160. }
  161. description := fmt.Sprintf("type %s, %d conversations, chunk order %d", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder())
  162. user.log.Infoln("Storing history sync with", description)
  163. for _, conv := range evt.GetConversations() {
  164. jid, err := types.ParseJID(conv.GetId())
  165. if err != nil {
  166. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  167. continue
  168. }
  169. portal := user.GetPortalByJID(jid)
  170. historySyncConversation := user.bridge.DB.HistorySyncQuery.NewConversationWithValues(
  171. user.MXID,
  172. conv.GetId(),
  173. &portal.Key,
  174. getConversationTimestamp(conv),
  175. conv.GetMuteEndTime(),
  176. conv.GetArchived(),
  177. conv.GetPinned(),
  178. conv.GetDisappearingMode().GetInitiator(),
  179. conv.GetEndOfHistoryTransferType(),
  180. conv.EphemeralExpiration,
  181. conv.GetMarkedAsUnread(),
  182. conv.GetUnreadCount())
  183. historySyncConversation.Upsert()
  184. for _, msg := range conv.GetMessages() {
  185. // Don't store messages that will just be skipped.
  186. wmi := msg.GetMessage()
  187. msgType := getMessageType(wmi.GetMessage())
  188. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  189. continue
  190. }
  191. // Don't store unsupported messages.
  192. if !containsSupportedMessage(msg.GetMessage().GetMessage()) {
  193. continue
  194. }
  195. message, err := user.bridge.DB.HistorySyncQuery.NewMessageWithValues(user.MXID, conv.GetId(), msg)
  196. if err != nil {
  197. user.log.Warnf("Failed to save message %s in %s. Error: %+v", msg.Message.Key.Id, conv.GetId(), err)
  198. continue
  199. }
  200. message.Insert()
  201. }
  202. }
  203. // If this was the initial bootstrap, enqueue immediate backfills for the
  204. // most recent portals. If it's the last history sync event, start
  205. // backfilling the rest of the history of the portals.
  206. if user.bridge.Config.Bridge.HistorySync.Backfill && (evt.GetSyncType() == waProto.HistorySync_INITIAL_BOOTSTRAP || evt.GetSyncType() == waProto.HistorySync_FULL) {
  207. nMostRecent := user.bridge.DB.HistorySyncQuery.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  208. for i, conv := range nMostRecent {
  209. jid, err := types.ParseJID(conv.ConversationID)
  210. if err != nil {
  211. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  212. continue
  213. }
  214. portal := user.GetPortalByJID(jid)
  215. switch evt.GetSyncType() {
  216. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  217. // Enqueue immediate backfills for the most recent messages first.
  218. user.EnqueueImmedateBackfill(portal, i)
  219. case waProto.HistorySync_FULL:
  220. // Enqueue deferred backfills as configured.
  221. user.EnqueueDeferredBackfills(portal, len(nMostRecent), i)
  222. }
  223. }
  224. // Tell the queue to check for new backfill requests.
  225. reCheckQueue <- true
  226. }
  227. }
  228. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  229. convTs := conv.GetConversationTimestamp()
  230. if convTs == 0 && len(conv.GetMessages()) > 0 {
  231. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  232. }
  233. return convTs
  234. }
  235. func (user *User) EnqueueImmedateBackfill(portal *Portal, priority int) {
  236. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  237. initialBackfill := user.bridge.DB.BackfillQuery.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, nil, maxMessages, maxMessages, 0)
  238. initialBackfill.Insert()
  239. }
  240. func (user *User) EnqueueDeferredBackfills(portal *Portal, numConversations, priority int) {
  241. for j, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  242. var startDate *time.Time = nil
  243. if backfillStage.StartDaysAgo > 0 {
  244. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  245. startDate = &startDaysAgo
  246. }
  247. backfill := user.bridge.DB.BackfillQuery.NewWithValues(
  248. user.MXID, database.BackfillDeferred, j*numConversations+priority, &portal.Key, startDate, nil, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  249. backfill.Insert()
  250. }
  251. }
  252. // endregion
  253. // region Portal backfilling
  254. var (
  255. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  256. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  257. // Marker events for when a backfill finishes
  258. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  259. RoomMarker = event.Type{Type: "m.room.marker", Class: event.MessageEventType}
  260. MSC2716Marker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  261. )
  262. func (portal *Portal) backfill(source *User, messages []*database.WrappedWebMessageInfo) []id.EventID {
  263. portal.backfillLock.Lock()
  264. defer portal.backfillLock.Unlock()
  265. var historyBatch, newBatch mautrix.ReqBatchSend
  266. var historyBatchInfos, newBatchInfos []*wrappedInfo
  267. firstMsgTimestamp := time.Unix(int64(messages[len(messages)-1].Message.GetMessageTimestamp()), 0)
  268. historyBatch.StateEventsAtStart = make([]*event.Event, 0)
  269. newBatch.StateEventsAtStart = make([]*event.Event, 0)
  270. addedMembers := make(map[id.UserID]*event.MemberEventContent)
  271. addMember := func(puppet *Puppet) {
  272. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  273. return
  274. }
  275. mxid := puppet.MXID.String()
  276. content := event.MemberEventContent{
  277. Membership: event.MembershipJoin,
  278. Displayname: puppet.Displayname,
  279. AvatarURL: puppet.AvatarURL.CUString(),
  280. }
  281. inviteContent := content
  282. inviteContent.Membership = event.MembershipInvite
  283. historyBatch.StateEventsAtStart = append(historyBatch.StateEventsAtStart, &event.Event{
  284. Type: event.StateMember,
  285. Sender: portal.MainIntent().UserID,
  286. StateKey: &mxid,
  287. Timestamp: firstMsgTimestamp.UnixMilli(),
  288. Content: event.Content{Parsed: &inviteContent},
  289. }, &event.Event{
  290. Type: event.StateMember,
  291. Sender: puppet.MXID,
  292. StateKey: &mxid,
  293. Timestamp: firstMsgTimestamp.UnixMilli(),
  294. Content: event.Content{Parsed: &content},
  295. })
  296. addedMembers[puppet.MXID] = &content
  297. }
  298. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  299. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  300. var historyMaxTs, newMinTs time.Time
  301. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  302. historyBatch.PrevEventID = portal.FirstEventID
  303. historyBatch.BatchID = portal.NextBatchID
  304. if firstMessage == nil && lastMessage == nil {
  305. historyMaxTs = time.Now()
  306. } else {
  307. historyMaxTs = firstMessage.Timestamp
  308. }
  309. }
  310. if lastMessage != nil {
  311. newBatch.PrevEventID = lastMessage.MXID
  312. newMinTs = lastMessage.Timestamp
  313. }
  314. portal.log.Infofln("Processing history sync with %d messages", len(messages))
  315. // The messages are ordered newest to oldest, so iterate them in reverse order.
  316. for i := len(messages) - 1; i >= 0; i-- {
  317. webMsg := messages[i].Message
  318. msgType := getMessageType(webMsg.GetMessage())
  319. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  320. if msgType != "ignore" {
  321. portal.log.Debugfln("Skipping message %s with unknown type in backfill", webMsg.GetKey().GetId())
  322. }
  323. continue
  324. }
  325. info := portal.parseWebMessageInfo(source, webMsg)
  326. if info == nil {
  327. continue
  328. }
  329. var batch *mautrix.ReqBatchSend
  330. var infos *[]*wrappedInfo
  331. if !historyMaxTs.IsZero() && info.Timestamp.Before(historyMaxTs) {
  332. batch, infos = &historyBatch, &historyBatchInfos
  333. } else if !newMinTs.IsZero() && info.Timestamp.After(newMinTs) {
  334. batch, infos = &newBatch, &newBatchInfos
  335. } else {
  336. continue
  337. }
  338. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  339. existingContact, _ := source.Client.Store.Contacts.GetContact(info.Sender)
  340. if !existingContact.Found || existingContact.PushName == "" {
  341. changed, _, err := source.Client.Store.Contacts.PutPushName(info.Sender, webMsg.GetPushName())
  342. if err != nil {
  343. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", info.Sender, err)
  344. } else if changed {
  345. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), info.Sender)
  346. }
  347. }
  348. }
  349. puppet := portal.getMessagePuppet(source, info)
  350. intent := puppet.IntentFor(portal)
  351. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  352. intent = puppet.DefaultIntent()
  353. }
  354. converted := portal.convertMessage(intent, source, info, webMsg.GetMessage())
  355. if converted == nil {
  356. portal.log.Debugfln("Skipping unsupported message %s in backfill", info.ID)
  357. continue
  358. }
  359. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  360. addMember(puppet)
  361. }
  362. // TODO this won't work for history
  363. if len(converted.ReplyTo) > 0 {
  364. portal.SetReply(converted.Content, converted.ReplyTo)
  365. }
  366. err := portal.appendBatchEvents(converted, info, webMsg.GetEphemeralStartTimestamp(), &batch.Events, infos)
  367. if err != nil {
  368. portal.log.Errorfln("Error handling message %s during backfill: %v", info.ID, err)
  369. }
  370. }
  371. if (len(historyBatch.Events) > 0 && len(historyBatch.BatchID) == 0) || len(newBatch.Events) > 0 {
  372. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  373. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  374. if err != nil {
  375. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  376. }
  377. }
  378. insertionEventIds := []id.EventID{}
  379. if len(historyBatch.Events) > 0 && len(historyBatch.PrevEventID) > 0 {
  380. portal.log.Infofln("Sending %d historical messages...", len(historyBatch.Events))
  381. historyResp, err := portal.MainIntent().BatchSend(portal.MXID, &historyBatch)
  382. insertionEventIds = append(insertionEventIds, historyResp.BaseInsertionEventID)
  383. if err != nil {
  384. portal.log.Errorln("Error sending batch of historical messages:", err)
  385. } else {
  386. portal.finishBatch(historyResp.EventIDs, historyBatchInfos)
  387. portal.NextBatchID = historyResp.NextBatchID
  388. portal.Update()
  389. }
  390. }
  391. if len(newBatch.Events) > 0 && len(newBatch.PrevEventID) > 0 {
  392. portal.log.Infofln("Sending %d new messages...", len(newBatch.Events))
  393. newResp, err := portal.MainIntent().BatchSend(portal.MXID, &newBatch)
  394. insertionEventIds = append(insertionEventIds, newResp.BaseInsertionEventID)
  395. if err != nil {
  396. portal.log.Errorln("Error sending batch of new messages:", err)
  397. } else {
  398. portal.finishBatch(newResp.EventIDs, newBatchInfos)
  399. }
  400. }
  401. return insertionEventIds
  402. }
  403. func (portal *Portal) parseWebMessageInfo(source *User, webMsg *waProto.WebMessageInfo) *types.MessageInfo {
  404. info := types.MessageInfo{
  405. MessageSource: types.MessageSource{
  406. Chat: portal.Key.JID,
  407. IsFromMe: webMsg.GetKey().GetFromMe(),
  408. IsGroup: portal.Key.JID.Server == types.GroupServer,
  409. },
  410. ID: webMsg.GetKey().GetId(),
  411. PushName: webMsg.GetPushName(),
  412. Timestamp: time.Unix(int64(webMsg.GetMessageTimestamp()), 0),
  413. }
  414. var err error
  415. if info.IsFromMe {
  416. info.Sender = source.JID.ToNonAD()
  417. } else if portal.IsPrivateChat() {
  418. info.Sender = portal.Key.JID
  419. } else if webMsg.GetParticipant() != "" {
  420. info.Sender, err = types.ParseJID(webMsg.GetParticipant())
  421. } else if webMsg.GetKey().GetParticipant() != "" {
  422. info.Sender, err = types.ParseJID(webMsg.GetKey().GetParticipant())
  423. }
  424. if info.Sender.IsEmpty() {
  425. portal.log.Warnfln("Failed to get sender of message %s (parse error: %v)", info.ID, err)
  426. return nil
  427. }
  428. return &info
  429. }
  430. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  431. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  432. if err != nil {
  433. return err
  434. }
  435. if converted.Caption != nil {
  436. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  437. if err != nil {
  438. return err
  439. }
  440. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  441. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn}, nil)
  442. } else {
  443. *eventsArray = append(*eventsArray, mainEvt)
  444. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn})
  445. }
  446. if converted.MultiEvent != nil {
  447. for _, subEvtContent := range converted.MultiEvent {
  448. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil)
  449. if err != nil {
  450. return err
  451. }
  452. *eventsArray = append(*eventsArray, subEvt)
  453. *infoArray = append(*infoArray, nil)
  454. }
  455. }
  456. return nil
  457. }
  458. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  459. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  460. if extraContent == nil {
  461. extraContent = map[string]interface{}{}
  462. }
  463. extraContent[backfillIDField] = info.ID
  464. if intent.IsCustomPuppet {
  465. extraContent[doublePuppetKey] = doublePuppetValue
  466. }
  467. wrappedContent := event.Content{
  468. Parsed: content,
  469. Raw: extraContent,
  470. }
  471. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  472. if err != nil {
  473. return nil, err
  474. }
  475. return &event.Event{
  476. Sender: intent.UserID,
  477. Type: newEventType,
  478. Timestamp: info.Timestamp.UnixMilli(),
  479. Content: wrappedContent,
  480. }, nil
  481. }
  482. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*wrappedInfo) {
  483. if len(eventIDs) != len(infos) {
  484. 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))
  485. infoMap := make(map[types.MessageID]*wrappedInfo, len(infos))
  486. for _, info := range infos {
  487. infoMap[info.ID] = info
  488. }
  489. for _, eventID := range eventIDs {
  490. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  491. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  492. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  493. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  494. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  495. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  496. } else {
  497. portal.finishBatchEvt(info, eventID)
  498. }
  499. }
  500. } else {
  501. for i := 0; i < len(infos); i++ {
  502. portal.finishBatchEvt(infos[i], eventIDs[i])
  503. }
  504. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  505. }
  506. }
  507. func (portal *Portal) finishBatchEvt(info *wrappedInfo, eventID id.EventID) {
  508. if info == nil {
  509. return
  510. }
  511. portal.markHandled(nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  512. if info.ExpiresIn > 0 {
  513. if info.ExpirationStart > 0 {
  514. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  515. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  516. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  517. } else {
  518. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  519. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  520. }
  521. }
  522. }
  523. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  524. for _, evtType := range []event.Type{BackfillEndDummyEvent, RoomMarker, MSC2716Marker} {
  525. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, evtType, map[string]interface{}{
  526. "org.matrix.msc2716.marker.insertion": insertionEventId,
  527. "m.marker.insertion": insertionEventId,
  528. })
  529. if err != nil {
  530. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  531. return
  532. }
  533. msg := portal.bridge.DB.Message.New()
  534. msg.Chat = portal.Key
  535. msg.MXID = resp.EventID
  536. msg.JID = types.MessageID(resp.EventID)
  537. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  538. msg.Sent = true
  539. msg.Insert()
  540. }
  541. }
  542. // endregion