historysync.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. "sort"
  19. "sync"
  20. "time"
  21. waProto "go.mau.fi/whatsmeow/binary/proto"
  22. "go.mau.fi/whatsmeow/types"
  23. "maunium.net/go/mautrix"
  24. "maunium.net/go/mautrix/appservice"
  25. "maunium.net/go/mautrix/event"
  26. "maunium.net/go/mautrix/id"
  27. "maunium.net/go/mautrix-whatsapp/database"
  28. )
  29. // region User history sync handling
  30. const (
  31. FastBackfillPortalCount = 20
  32. FastBackfillMessageCount = 20
  33. FastBackfillMessageCap = 30
  34. )
  35. type portalToBackfill struct {
  36. portal *Portal
  37. conv *waProto.Conversation
  38. msgs []*waProto.WebMessageInfo
  39. }
  40. type wrappedInfo struct {
  41. *types.MessageInfo
  42. Type database.MessageType
  43. Error database.MessageErrorType
  44. ExpirationStart uint64
  45. ExpiresIn uint32
  46. }
  47. type conversationList []*waProto.Conversation
  48. var _ sort.Interface = (conversationList)(nil)
  49. func (c conversationList) Len() int {
  50. return len(c)
  51. }
  52. func (c conversationList) Less(i, j int) bool {
  53. return getConversationTimestamp(c[i]) < getConversationTimestamp(c[j])
  54. }
  55. func (c conversationList) Swap(i, j int) {
  56. c[i], c[j] = c[j], c[i]
  57. }
  58. func (user *User) handleHistorySyncsLoop() {
  59. for evt := range user.historySyncs {
  60. go user.sendBridgeState(BridgeState{StateEvent: StateBackfilling})
  61. user.handleHistorySync(evt.Data)
  62. if len(user.historySyncs) == 0 && user.IsConnected() {
  63. go user.sendBridgeState(BridgeState{StateEvent: StateConnected})
  64. }
  65. }
  66. }
  67. func (user *User) handleHistorySync(evt *waProto.HistorySync) {
  68. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  69. return
  70. }
  71. user.log.Infofln("Handling history sync with type %s, %d conversations, chunk order %d, progress %d%%", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder(), evt.GetProgress())
  72. conversations := conversationList(evt.GetConversations())
  73. // We want to handle recent conversations first
  74. sort.Sort(sort.Reverse(conversations))
  75. portalsToBackfill := make(chan portalToBackfill, len(conversations))
  76. var backfillWait, fastBackfillWait sync.WaitGroup
  77. var fastBackfillWaitDoneOnce sync.Once
  78. // We have to add 1 to the waitgroup beforehand to make sure the wait in the goroutine doesn't finish
  79. // before we add the actual numbers.
  80. fastBackfillWait.Add(1)
  81. backfillWait.Add(1)
  82. go func() {
  83. // Wait for the fast parallelized backfill to complete, then start the slow backfill loop (see explanation below)
  84. fastBackfillWait.Wait()
  85. user.slowBackfillLoop(portalsToBackfill, backfillWait.Done)
  86. }()
  87. for i, conv := range conversations {
  88. // This will create portals and start backfilling for them.
  89. //
  90. // The first 20 (FastBackfillPortalCount) portals will be parallelized, where the portal is
  91. // created and recent messages are backfilled in parallel. Other portals will be created
  92. // synchronously (and this will only return when they're created).
  93. //
  94. // For said other portals, and older messages in the parallelized portals, backfilling also
  95. // happens synchronously: the portals and messages to backfill are added to the
  96. // portalsToBackfill channel, which is consumed one-by-one in the slowBackfillLoop method.
  97. // That loop is only started after the fast parallelized backfill is completed.
  98. user.handleHistorySyncConversation(i, conv, &fastBackfillWait, portalsToBackfill)
  99. if i == FastBackfillPortalCount {
  100. // There won't be any more portals going the fast backfill route, so remove the 1 item
  101. // that was added to the wait group at the beginning.
  102. fastBackfillWaitDoneOnce.Do(fastBackfillWait.Done)
  103. }
  104. }
  105. fastBackfillWaitDoneOnce.Do(fastBackfillWait.Done)
  106. // Wait for fast backfill to complete to make sure everything necessary is in the slow backfill queue,
  107. // then close the slow backfill queue and wait for the loop to finish handling the queue.
  108. fastBackfillWait.Wait()
  109. close(portalsToBackfill)
  110. backfillWait.Wait()
  111. user.log.Infofln("Finished handling history sync with type %s, %d conversations, chunk order %d, progress %d%%", evt.GetSyncType(), len(conversations), evt.GetChunkOrder(), evt.GetProgress())
  112. }
  113. func (user *User) slowBackfillLoop(ch chan portalToBackfill, done func()) {
  114. defer done()
  115. for ptb := range ch {
  116. if len(ptb.msgs) > 0 {
  117. user.log.Debugln("Bridging history sync payload for", ptb.portal.Key.JID)
  118. ptb.portal.backfill(user, ptb.msgs)
  119. } else {
  120. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", ptb.portal.Key.JID)
  121. }
  122. if !ptb.conv.GetMarkedAsUnread() && ptb.conv.GetUnreadCount() == 0 {
  123. user.markSelfReadFull(ptb.portal)
  124. }
  125. }
  126. }
  127. func (user *User) handleHistorySyncConversation(index int, conv *waProto.Conversation, fastBackfillWait *sync.WaitGroup, portalsToBackfill chan portalToBackfill) {
  128. jid, err := types.ParseJID(conv.GetId())
  129. if err != nil {
  130. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  131. return
  132. }
  133. // Update the client store with basic chat settings.
  134. muteEnd := time.Unix(int64(conv.GetMuteEndTime()), 0)
  135. if muteEnd.After(time.Now()) {
  136. _ = user.Client.Store.ChatSettings.PutMutedUntil(jid, muteEnd)
  137. }
  138. if conv.GetArchived() {
  139. _ = user.Client.Store.ChatSettings.PutArchived(jid, true)
  140. }
  141. if conv.GetPinned() > 0 {
  142. _ = user.Client.Store.ChatSettings.PutPinned(jid, true)
  143. }
  144. portal := user.GetPortalByJID(jid)
  145. if conv.EphemeralExpiration != nil && portal.ExpirationTime != conv.GetEphemeralExpiration() {
  146. portal.ExpirationTime = conv.GetEphemeralExpiration()
  147. portal.Update()
  148. }
  149. // Check if portal is too old or doesn't contain anything we can bridge.
  150. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  151. return
  152. }
  153. var msgs []*waProto.WebMessageInfo
  154. if user.bridge.Config.Bridge.HistorySync.Backfill {
  155. msgs = filterMessagesToBackfill(conv.GetMessages())
  156. }
  157. ptb := portalToBackfill{portal: portal, conv: conv, msgs: msgs}
  158. if len(portal.MXID) == 0 {
  159. // For the first few chats, do the portal creation and some backfilling in parallel to populate the chat list ASAP
  160. if index < FastBackfillPortalCount {
  161. fastBackfillWait.Add(1)
  162. go user.fastBackfillRoutine(ptb, fastBackfillWait.Done, portalsToBackfill)
  163. return
  164. }
  165. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  166. err = portal.CreateMatrixRoom(user, getPartialInfoFromConversation(jid, conv), false)
  167. if err != nil {
  168. user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  169. return
  170. }
  171. } else {
  172. portal.UpdateMatrixRoom(user, nil)
  173. }
  174. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  175. user.log.Debugln("Backfill is disabled, not bridging history sync payload for", portal.Key.JID)
  176. } else {
  177. portalsToBackfill <- ptb
  178. }
  179. }
  180. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  181. convTs := conv.GetConversationTimestamp()
  182. if convTs == 0 && len(conv.GetMessages()) > 0 {
  183. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  184. }
  185. return convTs
  186. }
  187. func (user *User) shouldCreatePortalForHistorySync(conv *waProto.Conversation, portal *Portal) bool {
  188. maxAge := user.bridge.Config.Bridge.HistorySync.MaxAge
  189. minLastMsgToCreate := time.Now().Add(-time.Duration(maxAge) * time.Second)
  190. lastMsg := time.Unix(int64(getConversationTimestamp(conv)), 0)
  191. if len(portal.MXID) > 0 {
  192. user.log.Debugfln("Portal for %s already exists, ensuring user is invited", portal.Key.JID)
  193. portal.ensureUserInvited(user)
  194. // Portal exists, let backfill continue
  195. return true
  196. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  197. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  198. } else if !containsSupportedMessages(conv) {
  199. user.log.Debugfln("Not creating portal for %s: no interesting messages found", portal.Key.JID)
  200. } else if maxAge > 0 && !lastMsg.After(minLastMsgToCreate) {
  201. user.log.Debugfln("Not creating portal for %s: last message older than limit (%s)", portal.Key.JID, lastMsg)
  202. } else {
  203. // Portal doesn't exist, but should be created
  204. return true
  205. }
  206. // Portal shouldn't be created, reason logged above
  207. return false
  208. }
  209. func (user *User) fastBackfillRoutine(ptb portalToBackfill, done func(), slowBackfillChan chan portalToBackfill) {
  210. defer done()
  211. user.log.Debugln("Asynchronously creating portal for", ptb.portal.Key.JID, "as part of history sync handling")
  212. err := ptb.portal.CreateMatrixRoom(user, getPartialInfoFromConversation(ptb.portal.Key.JID, ptb.conv), false)
  213. if err != nil {
  214. user.log.Warnfln("Failed to create room for %s during backfill: %v", ptb.portal.Key.JID, err)
  215. return
  216. }
  217. if user.bridge.Config.Bridge.HistorySync.Backfill {
  218. if len(ptb.msgs) > FastBackfillMessageCap {
  219. user.log.Debugfln("Bridging first %d messages of history sync payload for %s (async)", FastBackfillMessageCount, ptb.portal.Key.JID)
  220. ptb.portal.backfill(user, ptb.msgs[:FastBackfillMessageCount])
  221. // Send the rest of the messages off to the slow backfill queue
  222. ptb.msgs = ptb.msgs[FastBackfillMessageCount:]
  223. slowBackfillChan <- ptb
  224. } else if len(ptb.msgs) > 0 {
  225. user.log.Debugfln("Bridging all messages (%d) of history sync payload for %s (async)", len(ptb.msgs), ptb.portal.Key.JID)
  226. ptb.portal.backfill(user, ptb.msgs)
  227. } else {
  228. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", ptb.portal.Key.JID)
  229. }
  230. } else {
  231. user.log.Debugln("Backfill is disabled, not bridging history sync payload for", ptb.portal.Key.JID)
  232. }
  233. }
  234. func filterMessagesToBackfill(messages []*waProto.HistorySyncMsg) []*waProto.WebMessageInfo {
  235. filtered := make([]*waProto.WebMessageInfo, 0, len(messages))
  236. for _, msg := range messages {
  237. wmi := msg.GetMessage()
  238. msgType := getMessageType(wmi.GetMessage())
  239. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  240. continue
  241. } else {
  242. filtered = append(filtered, wmi)
  243. }
  244. }
  245. return filtered
  246. }
  247. func containsSupportedMessages(conv *waProto.Conversation) bool {
  248. for _, msg := range conv.GetMessages() {
  249. if containsSupportedMessage(msg.GetMessage().GetMessage()) {
  250. return true
  251. }
  252. }
  253. return false
  254. }
  255. func getPartialInfoFromConversation(jid types.JID, conv *waProto.Conversation) *types.GroupInfo {
  256. // TODO broadcast list info?
  257. if jid.Server != types.GroupServer {
  258. return nil
  259. }
  260. participants := make([]types.GroupParticipant, len(conv.GetParticipant()))
  261. for i, pcp := range conv.GetParticipant() {
  262. participantJID, _ := types.ParseJID(pcp.GetUserJid())
  263. participants[i] = types.GroupParticipant{
  264. JID: participantJID,
  265. IsAdmin: pcp.GetRank() == waProto.GroupParticipant_ADMIN,
  266. IsSuperAdmin: pcp.GetRank() == waProto.GroupParticipant_SUPERADMIN,
  267. }
  268. }
  269. return &types.GroupInfo{
  270. JID: jid,
  271. GroupName: types.GroupName{Name: conv.GetName()},
  272. Participants: participants,
  273. }
  274. }
  275. // endregion
  276. // region Portal backfilling
  277. var (
  278. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  279. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  280. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  281. )
  282. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo) {
  283. portal.backfillLock.Lock()
  284. defer portal.backfillLock.Unlock()
  285. var historyBatch, newBatch mautrix.ReqBatchSend
  286. var historyBatchInfos, newBatchInfos []*wrappedInfo
  287. firstMsgTimestamp := time.Unix(int64(messages[len(messages)-1].GetMessageTimestamp()), 0)
  288. historyBatch.StateEventsAtStart = make([]*event.Event, 0)
  289. newBatch.StateEventsAtStart = make([]*event.Event, 0)
  290. addedMembers := make(map[id.UserID]*event.MemberEventContent)
  291. addMember := func(puppet *Puppet) {
  292. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  293. return
  294. }
  295. mxid := puppet.MXID.String()
  296. content := event.MemberEventContent{
  297. Membership: event.MembershipJoin,
  298. Displayname: puppet.Displayname,
  299. AvatarURL: puppet.AvatarURL.CUString(),
  300. }
  301. inviteContent := content
  302. inviteContent.Membership = event.MembershipInvite
  303. historyBatch.StateEventsAtStart = append(historyBatch.StateEventsAtStart, &event.Event{
  304. Type: event.StateMember,
  305. Sender: portal.MainIntent().UserID,
  306. StateKey: &mxid,
  307. Timestamp: firstMsgTimestamp.UnixMilli(),
  308. Content: event.Content{Parsed: &inviteContent},
  309. }, &event.Event{
  310. Type: event.StateMember,
  311. Sender: puppet.MXID,
  312. StateKey: &mxid,
  313. Timestamp: firstMsgTimestamp.UnixMilli(),
  314. Content: event.Content{Parsed: &content},
  315. })
  316. addedMembers[puppet.MXID] = &content
  317. }
  318. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  319. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  320. var historyMaxTs, newMinTs time.Time
  321. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  322. historyBatch.PrevEventID = portal.FirstEventID
  323. historyBatch.BatchID = portal.NextBatchID
  324. if firstMessage == nil && lastMessage == nil {
  325. historyMaxTs = time.Now()
  326. } else {
  327. historyMaxTs = firstMessage.Timestamp
  328. }
  329. }
  330. if lastMessage != nil {
  331. newBatch.PrevEventID = lastMessage.MXID
  332. newMinTs = lastMessage.Timestamp
  333. }
  334. portal.log.Infofln("Processing history sync with %d messages", len(messages))
  335. // The messages are ordered newest to oldest, so iterate them in reverse order.
  336. for i := len(messages) - 1; i >= 0; i-- {
  337. webMsg := messages[i]
  338. msgType := getMessageType(webMsg.GetMessage())
  339. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  340. if msgType != "ignore" {
  341. portal.log.Debugfln("Skipping message %s with unknown type in backfill", webMsg.GetKey().GetId())
  342. }
  343. continue
  344. }
  345. info := portal.parseWebMessageInfo(source, webMsg)
  346. if info == nil {
  347. continue
  348. }
  349. var batch *mautrix.ReqBatchSend
  350. var infos *[]*wrappedInfo
  351. if !historyMaxTs.IsZero() && info.Timestamp.Before(historyMaxTs) {
  352. batch, infos = &historyBatch, &historyBatchInfos
  353. } else if !newMinTs.IsZero() && info.Timestamp.After(newMinTs) {
  354. batch, infos = &newBatch, &newBatchInfos
  355. } else {
  356. continue
  357. }
  358. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  359. existingContact, _ := source.Client.Store.Contacts.GetContact(info.Sender)
  360. if !existingContact.Found || existingContact.PushName == "" {
  361. changed, _, err := source.Client.Store.Contacts.PutPushName(info.Sender, webMsg.GetPushName())
  362. if err != nil {
  363. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", info.Sender, err)
  364. } else if changed {
  365. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), info.Sender)
  366. }
  367. }
  368. }
  369. puppet := portal.getMessagePuppet(source, info)
  370. intent := puppet.IntentFor(portal)
  371. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  372. intent = puppet.DefaultIntent()
  373. }
  374. converted := portal.convertMessage(intent, source, info, webMsg.GetMessage())
  375. if converted == nil {
  376. portal.log.Debugfln("Skipping unsupported message %s in backfill", info.ID)
  377. continue
  378. }
  379. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  380. addMember(puppet)
  381. }
  382. // TODO this won't work for history
  383. if len(converted.ReplyTo) > 0 {
  384. portal.SetReply(converted.Content, converted.ReplyTo)
  385. }
  386. err := portal.appendBatchEvents(converted, info, webMsg.GetEphemeralStartTimestamp(), &batch.Events, infos)
  387. if err != nil {
  388. portal.log.Errorfln("Error handling message %s during backfill: %v", info.ID, err)
  389. }
  390. }
  391. if (len(historyBatch.Events) > 0 && len(historyBatch.BatchID) == 0) || len(newBatch.Events) > 0 {
  392. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  393. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  394. if err != nil {
  395. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  396. }
  397. }
  398. if len(historyBatch.Events) > 0 && len(historyBatch.PrevEventID) > 0 {
  399. portal.log.Infofln("Sending %d historical messages...", len(historyBatch.Events))
  400. historyResp, err := portal.MainIntent().BatchSend(portal.MXID, &historyBatch)
  401. if err != nil {
  402. portal.log.Errorln("Error sending batch of historical messages:", err)
  403. } else {
  404. portal.finishBatch(historyResp.EventIDs, historyBatchInfos)
  405. portal.NextBatchID = historyResp.NextBatchID
  406. portal.Update()
  407. // If batchID is non-empty, it means this is backfilling very old messages, and we don't need a post-backfill dummy.
  408. if historyBatch.BatchID == "" {
  409. portal.sendPostBackfillDummy(time.UnixMilli(historyBatch.Events[len(historyBatch.Events)-1].Timestamp))
  410. }
  411. }
  412. }
  413. if len(newBatch.Events) > 0 && len(newBatch.PrevEventID) > 0 {
  414. portal.log.Infofln("Sending %d new messages...", len(newBatch.Events))
  415. newResp, err := portal.MainIntent().BatchSend(portal.MXID, &newBatch)
  416. if err != nil {
  417. portal.log.Errorln("Error sending batch of new messages:", err)
  418. } else {
  419. portal.finishBatch(newResp.EventIDs, newBatchInfos)
  420. portal.sendPostBackfillDummy(time.UnixMilli(newBatch.Events[len(newBatch.Events)-1].Timestamp))
  421. }
  422. }
  423. }
  424. func (portal *Portal) parseWebMessageInfo(source *User, webMsg *waProto.WebMessageInfo) *types.MessageInfo {
  425. info := types.MessageInfo{
  426. MessageSource: types.MessageSource{
  427. Chat: portal.Key.JID,
  428. IsFromMe: webMsg.GetKey().GetFromMe(),
  429. IsGroup: portal.Key.JID.Server == types.GroupServer,
  430. },
  431. ID: webMsg.GetKey().GetId(),
  432. PushName: webMsg.GetPushName(),
  433. Timestamp: time.Unix(int64(webMsg.GetMessageTimestamp()), 0),
  434. }
  435. var err error
  436. if info.IsFromMe {
  437. info.Sender = source.JID.ToNonAD()
  438. } else if portal.IsPrivateChat() {
  439. info.Sender = portal.Key.JID
  440. } else if webMsg.GetParticipant() != "" {
  441. info.Sender, err = types.ParseJID(webMsg.GetParticipant())
  442. } else if webMsg.GetKey().GetParticipant() != "" {
  443. info.Sender, err = types.ParseJID(webMsg.GetKey().GetParticipant())
  444. }
  445. if info.Sender.IsEmpty() {
  446. portal.log.Warnfln("Failed to get sender of message %s (parse error: %v)", info.ID, err)
  447. return nil
  448. }
  449. return &info
  450. }
  451. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  452. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  453. if err != nil {
  454. return err
  455. }
  456. if converted.Caption != nil {
  457. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  458. if err != nil {
  459. return err
  460. }
  461. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  462. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn}, nil)
  463. } else {
  464. *eventsArray = append(*eventsArray, mainEvt)
  465. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, expirationStart, converted.ExpiresIn})
  466. }
  467. if converted.MultiEvent != nil {
  468. for _, subEvtContent := range converted.MultiEvent {
  469. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil)
  470. if err != nil {
  471. return err
  472. }
  473. *eventsArray = append(*eventsArray, subEvt)
  474. *infoArray = append(*infoArray, nil)
  475. }
  476. }
  477. return nil
  478. }
  479. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  480. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  481. if extraContent == nil {
  482. extraContent = map[string]interface{}{}
  483. }
  484. extraContent[backfillIDField] = info.ID
  485. if intent.IsCustomPuppet {
  486. extraContent[doublePuppetKey] = doublePuppetValue
  487. }
  488. wrappedContent := event.Content{
  489. Parsed: content,
  490. Raw: extraContent,
  491. }
  492. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  493. if err != nil {
  494. return nil, err
  495. }
  496. return &event.Event{
  497. Sender: intent.UserID,
  498. Type: newEventType,
  499. Timestamp: info.Timestamp.UnixMilli(),
  500. Content: wrappedContent,
  501. }, nil
  502. }
  503. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*wrappedInfo) {
  504. if len(eventIDs) != len(infos) {
  505. 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))
  506. infoMap := make(map[types.MessageID]*wrappedInfo, len(infos))
  507. for _, info := range infos {
  508. infoMap[info.ID] = info
  509. }
  510. for _, eventID := range eventIDs {
  511. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  512. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  513. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  514. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  515. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  516. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  517. } else {
  518. portal.finishBatchEvt(info, eventID)
  519. }
  520. }
  521. } else {
  522. for i := 0; i < len(infos); i++ {
  523. portal.finishBatchEvt(infos[i], eventIDs[i])
  524. }
  525. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  526. }
  527. }
  528. func (portal *Portal) finishBatchEvt(info *wrappedInfo, eventID id.EventID) {
  529. if info == nil {
  530. return
  531. }
  532. portal.markHandled(nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  533. if info.ExpiresIn > 0 {
  534. if info.ExpirationStart > 0 {
  535. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  536. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  537. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  538. } else {
  539. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  540. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  541. }
  542. }
  543. }
  544. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time) {
  545. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, BackfillEndDummyEvent, struct{}{})
  546. if err != nil {
  547. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  548. return
  549. }
  550. msg := portal.bridge.DB.Message.New()
  551. msg.Chat = portal.Key
  552. msg.MXID = resp.EventID
  553. msg.JID = types.MessageID(resp.EventID)
  554. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  555. msg.Sent = true
  556. msg.Insert()
  557. }
  558. // endregion