historysync.go 23 KB

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