historysync.go 25 KB

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