historysync.go 23 KB

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