historysync.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 {
  213. if evt.GetSyncType() != waProto.HistorySync_INITIAL_BOOTSTRAP && evt.GetProgress() < 98 {
  214. return
  215. }
  216. nMostRecent := user.bridge.DB.HistorySyncQuery.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  217. for i, conv := range nMostRecent {
  218. jid, err := types.ParseJID(conv.ConversationID)
  219. if err != nil {
  220. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  221. continue
  222. }
  223. portal := user.GetPortalByJID(jid)
  224. switch evt.GetSyncType() {
  225. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  226. // Enqueue immediate backfills for the most recent messages first.
  227. user.EnqueueImmedateBackfill(portal, i)
  228. case waProto.HistorySync_FULL, waProto.HistorySync_RECENT:
  229. // Enqueue deferred backfills as configured.
  230. user.EnqueueDeferredBackfills(portal, len(nMostRecent), i)
  231. }
  232. }
  233. // Tell the queue to check for new backfill requests.
  234. reCheckQueue <- true
  235. }
  236. }
  237. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  238. convTs := conv.GetConversationTimestamp()
  239. if convTs == 0 && len(conv.GetMessages()) > 0 {
  240. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  241. }
  242. return convTs
  243. }
  244. func (user *User) EnqueueImmedateBackfill(portal *Portal, priority int) {
  245. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  246. initialBackfill := user.bridge.DB.BackfillQuery.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, nil, maxMessages, maxMessages, 0)
  247. initialBackfill.Insert()
  248. }
  249. func (user *User) EnqueueDeferredBackfills(portal *Portal, numConversations, priority int) {
  250. for j, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  251. var startDate *time.Time = nil
  252. if backfillStage.StartDaysAgo > 0 {
  253. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  254. startDate = &startDaysAgo
  255. }
  256. backfill := user.bridge.DB.BackfillQuery.NewWithValues(
  257. user.MXID, database.BackfillDeferred, j*numConversations+priority, &portal.Key, startDate, nil, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  258. backfill.Insert()
  259. }
  260. }
  261. // endregion
  262. // region Portal backfilling
  263. var (
  264. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  265. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  266. // Marker events for when a backfill finishes
  267. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  268. RoomMarker = event.Type{Type: "m.room.marker", Class: event.MessageEventType}
  269. MSC2716Marker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  270. )
  271. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo) []id.EventID {
  272. var historyBatch, newBatch mautrix.ReqBatchSend
  273. var historyBatchInfos, newBatchInfos []*wrappedInfo
  274. firstMsgTimestamp := time.Unix(int64(messages[len(messages)-1].GetMessageTimestamp()), 0)
  275. historyBatch.StateEventsAtStart = make([]*event.Event, 0)
  276. newBatch.StateEventsAtStart = make([]*event.Event, 0)
  277. addedMembers := make(map[id.UserID]*event.MemberEventContent)
  278. addMember := func(puppet *Puppet) {
  279. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  280. return
  281. }
  282. mxid := puppet.MXID.String()
  283. content := event.MemberEventContent{
  284. Membership: event.MembershipJoin,
  285. Displayname: puppet.Displayname,
  286. AvatarURL: puppet.AvatarURL.CUString(),
  287. }
  288. inviteContent := content
  289. inviteContent.Membership = event.MembershipInvite
  290. historyBatch.StateEventsAtStart = append(historyBatch.StateEventsAtStart, &event.Event{
  291. Type: event.StateMember,
  292. Sender: portal.MainIntent().UserID,
  293. StateKey: &mxid,
  294. Timestamp: firstMsgTimestamp.UnixMilli(),
  295. Content: event.Content{Parsed: &inviteContent},
  296. }, &event.Event{
  297. Type: event.StateMember,
  298. Sender: puppet.MXID,
  299. StateKey: &mxid,
  300. Timestamp: firstMsgTimestamp.UnixMilli(),
  301. Content: event.Content{Parsed: &content},
  302. })
  303. addedMembers[puppet.MXID] = &content
  304. }
  305. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  306. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  307. var historyMaxTs, newMinTs time.Time
  308. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  309. historyBatch.PrevEventID = portal.FirstEventID
  310. historyBatch.BatchID = portal.NextBatchID
  311. if firstMessage == nil && lastMessage == nil {
  312. historyMaxTs = time.Now()
  313. } else {
  314. historyMaxTs = firstMessage.Timestamp
  315. }
  316. }
  317. if lastMessage != nil {
  318. newBatch.PrevEventID = lastMessage.MXID
  319. newMinTs = lastMessage.Timestamp
  320. }
  321. portal.log.Infofln("Processing history sync with %d messages", len(messages))
  322. // The messages are ordered newest to oldest, so iterate them in reverse order.
  323. for i := len(messages) - 1; i >= 0; i-- {
  324. webMsg := messages[i]
  325. msgType := getMessageType(webMsg.GetMessage())
  326. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  327. if msgType != "ignore" {
  328. portal.log.Debugfln("Skipping message %s with unknown type in backfill", webMsg.GetKey().GetId())
  329. }
  330. continue
  331. }
  332. info := portal.parseWebMessageInfo(source, webMsg)
  333. if info == nil {
  334. continue
  335. }
  336. var batch *mautrix.ReqBatchSend
  337. var infos *[]*wrappedInfo
  338. if !historyMaxTs.IsZero() && info.Timestamp.Before(historyMaxTs) {
  339. batch, infos = &historyBatch, &historyBatchInfos
  340. } else if !newMinTs.IsZero() && info.Timestamp.After(newMinTs) {
  341. batch, infos = &newBatch, &newBatchInfos
  342. } else {
  343. continue
  344. }
  345. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  346. existingContact, _ := source.Client.Store.Contacts.GetContact(info.Sender)
  347. if !existingContact.Found || existingContact.PushName == "" {
  348. changed, _, err := source.Client.Store.Contacts.PutPushName(info.Sender, webMsg.GetPushName())
  349. if err != nil {
  350. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", info.Sender, err)
  351. } else if changed {
  352. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), info.Sender)
  353. }
  354. }
  355. }
  356. puppet := portal.getMessagePuppet(source, info)
  357. intent := puppet.IntentFor(portal)
  358. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  359. intent = puppet.DefaultIntent()
  360. }
  361. converted := portal.convertMessage(intent, source, info, webMsg.GetMessage())
  362. if converted == nil {
  363. portal.log.Debugfln("Skipping unsupported message %s in backfill", info.ID)
  364. continue
  365. }
  366. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  367. addMember(puppet)
  368. }
  369. // TODO this won't work for history
  370. if len(converted.ReplyTo) > 0 {
  371. portal.SetReply(converted.Content, converted.ReplyTo)
  372. }
  373. err := portal.appendBatchEvents(converted, info, webMsg.GetEphemeralStartTimestamp(), &batch.Events, infos)
  374. if err != nil {
  375. portal.log.Errorfln("Error handling message %s during backfill: %v", info.ID, err)
  376. }
  377. }
  378. if (len(historyBatch.Events) > 0 && len(historyBatch.BatchID) == 0) || len(newBatch.Events) > 0 {
  379. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  380. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  381. if err != nil {
  382. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  383. }
  384. }
  385. insertionEventIds := []id.EventID{}
  386. if len(historyBatch.Events) > 0 && len(historyBatch.PrevEventID) > 0 {
  387. portal.log.Infofln("Sending %d historical messages...", len(historyBatch.Events))
  388. historyResp, err := portal.MainIntent().BatchSend(portal.MXID, &historyBatch)
  389. insertionEventIds = append(insertionEventIds, historyResp.BaseInsertionEventID)
  390. if err != nil {
  391. portal.log.Errorln("Error sending batch of historical messages:", err)
  392. } else {
  393. portal.finishBatch(historyResp.EventIDs, historyBatchInfos)
  394. portal.NextBatchID = historyResp.NextBatchID
  395. portal.Update()
  396. }
  397. }
  398. if len(newBatch.Events) > 0 && len(newBatch.PrevEventID) > 0 {
  399. portal.log.Infofln("Sending %d new messages...", len(newBatch.Events))
  400. newResp, err := portal.MainIntent().BatchSend(portal.MXID, &newBatch)
  401. insertionEventIds = append(insertionEventIds, newResp.BaseInsertionEventID)
  402. if err != nil {
  403. portal.log.Errorln("Error sending batch of new messages:", err)
  404. } else {
  405. portal.finishBatch(newResp.EventIDs, newBatchInfos)
  406. }
  407. }
  408. return insertionEventIds
  409. }
  410. func (portal *Portal) parseWebMessageInfo(source *User, webMsg *waProto.WebMessageInfo) *types.MessageInfo {
  411. info := types.MessageInfo{
  412. MessageSource: types.MessageSource{
  413. Chat: portal.Key.JID,
  414. IsFromMe: webMsg.GetKey().GetFromMe(),
  415. IsGroup: portal.Key.JID.Server == types.GroupServer,
  416. },
  417. ID: webMsg.GetKey().GetId(),
  418. PushName: webMsg.GetPushName(),
  419. Timestamp: time.Unix(int64(webMsg.GetMessageTimestamp()), 0),
  420. }
  421. var err error
  422. if info.IsFromMe {
  423. info.Sender = source.JID.ToNonAD()
  424. } else if portal.IsPrivateChat() {
  425. info.Sender = portal.Key.JID
  426. } else if webMsg.GetParticipant() != "" {
  427. info.Sender, err = types.ParseJID(webMsg.GetParticipant())
  428. } else if webMsg.GetKey().GetParticipant() != "" {
  429. info.Sender, err = types.ParseJID(webMsg.GetKey().GetParticipant())
  430. }
  431. if info.Sender.IsEmpty() {
  432. portal.log.Warnfln("Failed to get sender of message %s (parse error: %v)", info.ID, err)
  433. return nil
  434. }
  435. return &info
  436. }
  437. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  438. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  439. if err != nil {
  440. return err
  441. }
  442. if converted.Caption != nil {
  443. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  444. if err != nil {
  445. return err
  446. }
  447. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  448. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn}, nil)
  449. } else {
  450. *eventsArray = append(*eventsArray, mainEvt)
  451. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn})
  452. }
  453. if converted.MultiEvent != nil {
  454. for _, subEvtContent := range converted.MultiEvent {
  455. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil)
  456. if err != nil {
  457. return err
  458. }
  459. *eventsArray = append(*eventsArray, subEvt)
  460. *infoArray = append(*infoArray, nil)
  461. }
  462. }
  463. return nil
  464. }
  465. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  466. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  467. if extraContent == nil {
  468. extraContent = map[string]interface{}{}
  469. }
  470. extraContent[backfillIDField] = info.ID
  471. if intent.IsCustomPuppet {
  472. extraContent[doublePuppetKey] = doublePuppetValue
  473. }
  474. wrappedContent := event.Content{
  475. Parsed: content,
  476. Raw: extraContent,
  477. }
  478. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  479. if err != nil {
  480. return nil, err
  481. }
  482. if eventType == event.EventEncrypted {
  483. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  484. wrappedContent.Raw = map[string]interface{}{backfillIDField: info.ID}
  485. if intent.IsCustomPuppet {
  486. wrappedContent.Raw[doublePuppetKey] = doublePuppetValue
  487. }
  488. }
  489. return &event.Event{
  490. Sender: intent.UserID,
  491. Type: newEventType,
  492. Timestamp: info.Timestamp.UnixMilli(),
  493. Content: wrappedContent,
  494. }, nil
  495. }
  496. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*wrappedInfo) {
  497. if len(eventIDs) != len(infos) {
  498. 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))
  499. infoMap := make(map[types.MessageID]*wrappedInfo, len(infos))
  500. for _, info := range infos {
  501. infoMap[info.ID] = info
  502. }
  503. for _, eventID := range eventIDs {
  504. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  505. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  506. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  507. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  508. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  509. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  510. } else {
  511. portal.finishBatchEvt(info, eventID)
  512. }
  513. }
  514. } else {
  515. for i := 0; i < len(infos); i++ {
  516. portal.finishBatchEvt(infos[i], eventIDs[i])
  517. }
  518. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  519. }
  520. }
  521. func (portal *Portal) finishBatchEvt(info *wrappedInfo, eventID id.EventID) {
  522. if info == nil {
  523. return
  524. }
  525. portal.markHandled(nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  526. if info.ExpiresIn > 0 {
  527. if info.ExpirationStart > 0 {
  528. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  529. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  530. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  531. } else {
  532. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  533. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  534. }
  535. }
  536. }
  537. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  538. for _, evtType := range []event.Type{BackfillEndDummyEvent, RoomMarker, MSC2716Marker} {
  539. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, evtType, map[string]interface{}{
  540. "org.matrix.msc2716.marker.insertion": insertionEventId,
  541. "m.marker.insertion": insertionEventId,
  542. })
  543. if err != nil {
  544. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  545. return
  546. }
  547. msg := portal.bridge.DB.Message.New()
  548. msg.Chat = portal.Key
  549. msg.MXID = resp.EventID
  550. msg.JID = types.MessageID(resp.EventID)
  551. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  552. msg.Sent = true
  553. msg.Insert()
  554. }
  555. }
  556. // endregion