historysync.go 20 KB

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