historysync.go 23 KB

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