historysync.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. "crypto/sha256"
  19. "encoding/base64"
  20. "fmt"
  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/bridge/bridgeconfig"
  27. "maunium.net/go/mautrix/event"
  28. "maunium.net/go/mautrix/id"
  29. "maunium.net/go/mautrix/util/dbutil"
  30. "maunium.net/go/mautrix-whatsapp/config"
  31. "maunium.net/go/mautrix-whatsapp/database"
  32. )
  33. // region User history sync handling
  34. type wrappedInfo struct {
  35. *types.MessageInfo
  36. Type database.MessageType
  37. Error database.MessageErrorType
  38. MediaKey []byte
  39. ExpirationStart uint64
  40. ExpiresIn uint32
  41. }
  42. func (user *User) handleHistorySyncsLoop() {
  43. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  44. return
  45. }
  46. // Start the backfill queue.
  47. user.BackfillQueue = &BackfillQueue{
  48. BackfillQuery: user.bridge.DB.Backfill,
  49. reCheckChannels: []chan bool{},
  50. log: user.log.Sub("BackfillQueue"),
  51. }
  52. forwardAndImmediate := []database.BackfillType{database.BackfillImmediate, database.BackfillForward}
  53. // Immediate backfills can be done in parallel
  54. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  55. go user.HandleBackfillRequestsLoop(forwardAndImmediate, []database.BackfillType{})
  56. }
  57. // Deferred backfills should be handled synchronously so as not to
  58. // overload the homeserver. Users can configure their backfill stages
  59. // to be more or less aggressive with backfilling at this stage.
  60. go user.HandleBackfillRequestsLoop([]database.BackfillType{database.BackfillDeferred}, forwardAndImmediate)
  61. if user.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia &&
  62. user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod == config.MediaRequestMethodLocalTime {
  63. go user.dailyMediaRequestLoop()
  64. }
  65. // Always save the history syncs for the user. If they want to enable
  66. // backfilling in the future, we will have it in the database.
  67. for evt := range user.historySyncs {
  68. user.handleHistorySync(user.BackfillQueue, evt.Data)
  69. }
  70. }
  71. func (user *User) dailyMediaRequestLoop() {
  72. // Calculate when to do the first set of media retry requests
  73. now := time.Now()
  74. userTz, err := time.LoadLocation(user.Timezone)
  75. if err != nil {
  76. userTz = now.Local().Location()
  77. }
  78. tonightMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, userTz)
  79. midnightOffset := time.Duration(user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestLocalTime) * time.Minute
  80. requestStartTime := tonightMidnight.Add(midnightOffset)
  81. // If the request time for today has already happened, we need to start the
  82. // request loop tomorrow instead.
  83. if requestStartTime.Before(now) {
  84. requestStartTime = requestStartTime.AddDate(0, 0, 1)
  85. }
  86. // Wait to start the loop
  87. user.log.Infof("Waiting until %s to do media retry requests", requestStartTime)
  88. time.Sleep(time.Until(requestStartTime))
  89. for {
  90. mediaBackfillRequests := user.bridge.DB.MediaBackfillRequest.GetMediaBackfillRequestsForUser(user.MXID)
  91. user.log.Infof("Sending %d media retry requests", len(mediaBackfillRequests))
  92. // Send all of the media backfill requests for the user at once
  93. for _, req := range mediaBackfillRequests {
  94. portal := user.GetPortalByJID(req.PortalKey.JID)
  95. _, err := portal.requestMediaRetry(user, req.EventID, req.MediaKey)
  96. if err != nil {
  97. user.log.Warnf("Failed to send media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  98. req.Status = database.MediaBackfillRequestStatusRequestFailed
  99. req.Error = err.Error()
  100. } else {
  101. user.log.Debugfln("Sent media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  102. req.Status = database.MediaBackfillRequestStatusRequested
  103. }
  104. req.MediaKey = nil
  105. req.Upsert()
  106. }
  107. // Wait for 24 hours before making requests again
  108. time.Sleep(24 * time.Hour)
  109. }
  110. }
  111. func (user *User) backfillInChunks(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
  112. portal.backfillLock.Lock()
  113. defer portal.backfillLock.Unlock()
  114. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  115. return
  116. }
  117. backfillState := user.bridge.DB.Backfill.GetBackfillState(user.MXID, &portal.Key)
  118. if backfillState == nil {
  119. backfillState = user.bridge.DB.Backfill.NewBackfillState(user.MXID, &portal.Key)
  120. }
  121. backfillState.SetProcessingBatch(true)
  122. defer backfillState.SetProcessingBatch(false)
  123. var forwardPrevID id.EventID
  124. var timeEnd *time.Time
  125. var isLatestEvents bool
  126. portal.latestEventBackfillLock.Lock()
  127. if req.BackfillType == database.BackfillForward {
  128. // TODO this overrides the TimeStart set when enqueuing the backfill
  129. // maybe the enqueue should instead include the prev event ID
  130. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  131. forwardPrevID = lastMessage.MXID
  132. start := lastMessage.Timestamp.Add(1 * time.Second)
  133. req.TimeStart = &start
  134. // Sending events at the end of the room (= latest events)
  135. isLatestEvents = true
  136. } else {
  137. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  138. if firstMessage != nil {
  139. end := firstMessage.Timestamp.Add(-1 * time.Second)
  140. timeEnd = &end
  141. user.log.Debugfln("Limiting backfill to end at %v", end)
  142. } else {
  143. // Portal is empty -> events are latest
  144. isLatestEvents = true
  145. }
  146. }
  147. if !isLatestEvents {
  148. // We'll use normal batch sending, so no need to keep blocking new message processing
  149. portal.latestEventBackfillLock.Unlock()
  150. } else {
  151. // This might involve sending events at the end of the room as non-historical events,
  152. // make sure we don't process messages until this is done.
  153. defer portal.latestEventBackfillLock.Unlock()
  154. }
  155. allMsgs := user.bridge.DB.HistorySync.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, timeEnd, req.MaxTotalEvents)
  156. sendDisappearedNotice := false
  157. // If expired messages are on, and a notice has not been sent to this chat
  158. // about it having disappeared messages at the conversation timestamp, send
  159. // a notice indicating so.
  160. if len(allMsgs) == 0 && conv.EphemeralExpiration != nil && *conv.EphemeralExpiration > 0 {
  161. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  162. if lastMessage == nil || conv.LastMessageTimestamp.After(lastMessage.Timestamp) {
  163. sendDisappearedNotice = true
  164. }
  165. }
  166. if !sendDisappearedNotice && len(allMsgs) == 0 {
  167. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  168. return
  169. }
  170. if len(portal.MXID) == 0 {
  171. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  172. err := portal.CreateMatrixRoom(user, nil, true, false)
  173. if err != nil {
  174. user.log.Errorfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  175. return
  176. }
  177. }
  178. // Update the backfill status here after the room has been created.
  179. portal.updateBackfillStatus(backfillState)
  180. if sendDisappearedNotice {
  181. user.log.Debugfln("Sending notice to %s that there are disappeared messages ending at %v", portal.Key.JID, conv.LastMessageTimestamp)
  182. resp, err := portal.sendMessage(portal.MainIntent(), event.EventMessage, &event.MessageEventContent{
  183. MsgType: event.MsgNotice,
  184. Body: portal.formatDisappearingMessageNotice(),
  185. }, nil, conv.LastMessageTimestamp.UnixMilli())
  186. if err != nil {
  187. portal.log.Errorln("Error sending disappearing messages notice event")
  188. return
  189. }
  190. msg := portal.bridge.DB.Message.New()
  191. msg.Chat = portal.Key
  192. msg.MXID = resp.EventID
  193. msg.JID = types.MessageID(resp.EventID)
  194. msg.Timestamp = conv.LastMessageTimestamp
  195. msg.Sent = true
  196. msg.Type = database.MsgFake
  197. msg.Insert(nil)
  198. return
  199. }
  200. user.log.Infofln("Backfilling %d messages in %s, %d messages at a time (queue ID: %d)", len(allMsgs), portal.Key.JID, req.MaxBatchEvents, req.QueueID)
  201. toBackfill := allMsgs[0:]
  202. var insertionEventIds []id.EventID
  203. for len(toBackfill) > 0 {
  204. var msgs []*waProto.WebMessageInfo
  205. if len(toBackfill) <= req.MaxBatchEvents || req.MaxBatchEvents < 0 {
  206. msgs = toBackfill
  207. toBackfill = nil
  208. } else {
  209. msgs = toBackfill[:req.MaxBatchEvents]
  210. toBackfill = toBackfill[req.MaxBatchEvents:]
  211. }
  212. if len(msgs) > 0 {
  213. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  214. user.log.Debugfln("Backfilling %d messages in %s (queue ID: %d)", len(msgs), portal.Key.JID, req.QueueID)
  215. resp := portal.backfill(user, msgs, req.BackfillType == database.BackfillForward, isLatestEvents, forwardPrevID)
  216. if resp != nil && (resp.BaseInsertionEventID != "" || !isLatestEvents) {
  217. insertionEventIds = append(insertionEventIds, resp.BaseInsertionEventID)
  218. }
  219. }
  220. }
  221. user.log.Debugfln("Finished backfilling %d messages in %s (queue ID: %d)", len(allMsgs), portal.Key.JID, req.QueueID)
  222. if len(insertionEventIds) > 0 {
  223. portal.sendPostBackfillDummy(
  224. time.Unix(int64(allMsgs[0].GetMessageTimestamp()), 0),
  225. insertionEventIds[0])
  226. }
  227. user.log.Debugfln("Deleting %d history sync messages after backfilling (queue ID: %d)", len(allMsgs), req.QueueID)
  228. err := user.bridge.DB.HistorySync.DeleteMessages(user.MXID, conv.ConversationID, allMsgs)
  229. if err != nil {
  230. user.log.Warnfln("Failed to delete %d history sync messages after backfilling (queue ID: %d): %v", len(allMsgs), req.QueueID, err)
  231. }
  232. if req.TimeStart == nil {
  233. // If the time start is nil, then there's no more history to backfill.
  234. backfillState.BackfillComplete = true
  235. if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY {
  236. // Since there are more messages on the phone, but we can't
  237. // backfill any more of them, indicate that the last timestamp
  238. // that we expect to be backfilled is the oldest one that was just
  239. // backfilled.
  240. backfillState.FirstExpectedTimestamp = allMsgs[len(allMsgs)-1].GetMessageTimestamp()
  241. } else if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY {
  242. // Since there are no more messages left on the phone, we've
  243. // backfilled everything. Indicate so by setting the expected
  244. // timestamp to 0 which means that the backfill goes to the
  245. // beginning of time.
  246. backfillState.FirstExpectedTimestamp = 0
  247. }
  248. backfillState.Upsert()
  249. portal.updateBackfillStatus(backfillState)
  250. }
  251. if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
  252. user.markSelfReadFull(portal)
  253. } else if user.bridge.Config.Bridge.SyncManualMarkedUnread {
  254. user.markUnread(portal, true)
  255. }
  256. }
  257. func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
  258. if len(portal.MXID) > 0 {
  259. if !user.bridge.AS.StateStore.IsInRoom(portal.MXID, user.MXID) {
  260. portal.ensureUserInvited(user)
  261. }
  262. // Portal exists, let backfill continue
  263. return true
  264. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  265. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  266. return false
  267. } else {
  268. // Portal doesn't exist, but should be created
  269. return true
  270. }
  271. }
  272. func (user *User) handleHistorySync(backfillQueue *BackfillQueue, evt *waProto.HistorySync) {
  273. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  274. return
  275. }
  276. description := fmt.Sprintf("type %s, %d conversations, chunk order %d, progress: %d", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder(), evt.GetProgress())
  277. user.log.Infoln("Storing history sync with", description)
  278. for _, conv := range evt.GetConversations() {
  279. jid, err := types.ParseJID(conv.GetId())
  280. if err != nil {
  281. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  282. continue
  283. } else if jid.Server == types.BroadcastServer {
  284. user.log.Debugfln("Skipping broadcast list %s in history sync", jid)
  285. continue
  286. }
  287. portal := user.GetPortalByJID(jid)
  288. historySyncConversation := user.bridge.DB.HistorySync.NewConversationWithValues(
  289. user.MXID,
  290. conv.GetId(),
  291. &portal.Key,
  292. getConversationTimestamp(conv),
  293. conv.GetMuteEndTime(),
  294. conv.GetArchived(),
  295. conv.GetPinned(),
  296. conv.GetDisappearingMode().GetInitiator(),
  297. conv.GetEndOfHistoryTransferType(),
  298. conv.EphemeralExpiration,
  299. conv.GetMarkedAsUnread(),
  300. conv.GetUnreadCount())
  301. historySyncConversation.Upsert()
  302. for _, rawMsg := range conv.GetMessages() {
  303. // Don't store messages that will just be skipped.
  304. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, rawMsg.GetMessage())
  305. if err != nil {
  306. user.log.Warnln("Dropping historical message due to info parse error:", err)
  307. continue
  308. }
  309. msgType := getMessageType(msgEvt.Message)
  310. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  311. continue
  312. }
  313. // Don't store unsupported messages.
  314. if !containsSupportedMessage(msgEvt.Message) {
  315. continue
  316. }
  317. message, err := user.bridge.DB.HistorySync.NewMessageWithValues(user.MXID, conv.GetId(), msgEvt.Info.ID, rawMsg)
  318. if err != nil {
  319. user.log.Warnfln("Failed to save message %s in %s. Error: %+v", msgEvt.Info.ID, conv.GetId(), err)
  320. continue
  321. }
  322. message.Insert()
  323. }
  324. }
  325. // If this was the initial bootstrap, enqueue immediate backfills for the
  326. // most recent portals. If it's the last history sync event, start
  327. // backfilling the rest of the history of the portals.
  328. if user.bridge.Config.Bridge.HistorySync.Backfill {
  329. if evt.GetSyncType() != waProto.HistorySync_INITIAL_BOOTSTRAP && evt.GetProgress() < 98 {
  330. return
  331. }
  332. nMostRecent := user.bridge.DB.HistorySync.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  333. if len(nMostRecent) > 0 {
  334. // Find the portals for all of the conversations.
  335. portals := []*Portal{}
  336. for _, conv := range nMostRecent {
  337. jid, err := types.ParseJID(conv.ConversationID)
  338. if err != nil {
  339. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  340. continue
  341. }
  342. portals = append(portals, user.GetPortalByJID(jid))
  343. }
  344. switch evt.GetSyncType() {
  345. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  346. // Enqueue immediate backfills for the most recent messages first.
  347. user.EnqueueImmedateBackfills(portals)
  348. case waProto.HistorySync_FULL, waProto.HistorySync_RECENT:
  349. user.EnqueueForwardBackfills(portals)
  350. // Enqueue deferred backfills as configured.
  351. user.EnqueueDeferredBackfills(portals)
  352. }
  353. // Tell the queue to check for new backfill requests.
  354. backfillQueue.ReCheck()
  355. }
  356. }
  357. }
  358. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  359. convTs := conv.GetConversationTimestamp()
  360. if convTs == 0 && len(conv.GetMessages()) > 0 {
  361. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  362. }
  363. return convTs
  364. }
  365. func (user *User) EnqueueImmedateBackfills(portals []*Portal) {
  366. for priority, portal := range portals {
  367. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  368. initialBackfill := user.bridge.DB.Backfill.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, maxMessages, maxMessages, 0)
  369. initialBackfill.Insert()
  370. }
  371. }
  372. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  373. numPortals := len(portals)
  374. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  375. for portalIdx, portal := range portals {
  376. var startDate *time.Time = nil
  377. if backfillStage.StartDaysAgo > 0 {
  378. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  379. startDate = &startDaysAgo
  380. }
  381. backfillMessages := user.bridge.DB.Backfill.NewWithValues(
  382. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  383. backfillMessages.Insert()
  384. }
  385. }
  386. }
  387. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  388. for priority, portal := range portals {
  389. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  390. if lastMsg == nil {
  391. continue
  392. }
  393. backfill := user.bridge.DB.Backfill.NewWithValues(
  394. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, -1, -1, 0)
  395. backfill.Insert()
  396. }
  397. }
  398. // endregion
  399. // region Portal backfilling
  400. func (portal *Portal) deterministicEventID(sender types.JID, messageID types.MessageID, partName string) id.EventID {
  401. data := fmt.Sprintf("%s/whatsapp/%s/%s", portal.MXID, sender.User, messageID)
  402. if partName != "" {
  403. data += "/" + partName
  404. }
  405. sum := sha256.Sum256([]byte(data))
  406. return id.EventID(fmt.Sprintf("$%s:whatsapp.com", base64.RawURLEncoding.EncodeToString(sum[:])))
  407. }
  408. var (
  409. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  410. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  411. HistorySyncMarker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  412. BackfillStatusEvent = event.Type{Type: "com.beeper.backfill_status", Class: event.StateEventType}
  413. )
  414. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward, isLatest bool, prevEventID id.EventID) *mautrix.RespBatchSend {
  415. var req mautrix.ReqBatchSend
  416. var infos []*wrappedInfo
  417. if !isForward {
  418. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  419. req.PrevEventID = portal.FirstEventID
  420. req.BatchID = portal.NextBatchID
  421. } else {
  422. portal.log.Warnfln("Can't backfill %d messages through %s to chat: first event ID not known", len(messages), source.MXID)
  423. return nil
  424. }
  425. } else {
  426. req.PrevEventID = prevEventID
  427. }
  428. req.BeeperNewMessages = isLatest && req.BatchID == ""
  429. beforeFirstMessageTimestampMillis := (int64(messages[len(messages)-1].GetMessageTimestamp()) * 1000) - 1
  430. req.StateEventsAtStart = make([]*event.Event, 0)
  431. addedMembers := make(map[id.UserID]struct{})
  432. addMember := func(puppet *Puppet) {
  433. if portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  434. // Hungryserv doesn't need state_events_at_start, it can figure out memberships automatically
  435. return
  436. } else if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  437. return
  438. }
  439. mxid := puppet.MXID.String()
  440. content := event.MemberEventContent{
  441. Membership: event.MembershipJoin,
  442. Displayname: puppet.Displayname,
  443. AvatarURL: puppet.AvatarURL.CUString(),
  444. }
  445. inviteContent := content
  446. inviteContent.Membership = event.MembershipInvite
  447. req.StateEventsAtStart = append(req.StateEventsAtStart, &event.Event{
  448. Type: event.StateMember,
  449. Sender: portal.MainIntent().UserID,
  450. StateKey: &mxid,
  451. Timestamp: beforeFirstMessageTimestampMillis,
  452. Content: event.Content{Parsed: &inviteContent},
  453. }, &event.Event{
  454. Type: event.StateMember,
  455. Sender: puppet.MXID,
  456. StateKey: &mxid,
  457. Timestamp: beforeFirstMessageTimestampMillis,
  458. Content: event.Content{Parsed: &content},
  459. })
  460. addedMembers[puppet.MXID] = struct{}{}
  461. }
  462. portal.log.Infofln("Processing history sync with %d messages (forward: %t, latest: %t, prev: %s, batch: %s)", len(messages), isForward, isLatest, req.PrevEventID, req.BatchID)
  463. // The messages are ordered newest to oldest, so iterate them in reverse order.
  464. for i := len(messages) - 1; i >= 0; i-- {
  465. webMsg := messages[i]
  466. msgEvt, err := source.Client.ParseWebMessage(portal.Key.JID, webMsg)
  467. if err != nil {
  468. continue
  469. }
  470. msgType := getMessageType(msgEvt.Message)
  471. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  472. if msgType != "ignore" {
  473. portal.log.Debugfln("Skipping message %s with unknown type in backfill", msgEvt.Info.ID)
  474. }
  475. continue
  476. }
  477. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  478. existingContact, _ := source.Client.Store.Contacts.GetContact(msgEvt.Info.Sender)
  479. if !existingContact.Found || existingContact.PushName == "" {
  480. changed, _, err := source.Client.Store.Contacts.PutPushName(msgEvt.Info.Sender, webMsg.GetPushName())
  481. if err != nil {
  482. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", msgEvt.Info.Sender, err)
  483. } else if changed {
  484. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), msgEvt.Info.Sender)
  485. }
  486. }
  487. }
  488. puppet := portal.getMessagePuppet(source, &msgEvt.Info)
  489. if puppet == nil {
  490. continue
  491. }
  492. intent := puppet.IntentFor(portal)
  493. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  494. intent = puppet.DefaultIntent()
  495. }
  496. converted := portal.convertMessage(intent, source, &msgEvt.Info, msgEvt.Message, true)
  497. if converted == nil {
  498. portal.log.Debugfln("Skipping unsupported message %s in backfill", msgEvt.Info.ID)
  499. continue
  500. }
  501. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  502. addMember(puppet)
  503. }
  504. if converted.ReplyTo != nil {
  505. portal.SetReply(converted.Content, converted.ReplyTo, true)
  506. }
  507. err = portal.appendBatchEvents(converted, &msgEvt.Info, webMsg.GetEphemeralStartTimestamp(), &req.Events, &infos)
  508. if err != nil {
  509. portal.log.Errorfln("Error handling message %s during backfill: %v", msgEvt.Info.ID, err)
  510. }
  511. }
  512. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  513. if len(req.Events) == 0 {
  514. return nil
  515. }
  516. if len(req.BatchID) == 0 || isForward {
  517. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  518. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  519. if err != nil {
  520. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  521. }
  522. }
  523. resp, err := portal.MainIntent().BatchSend(portal.MXID, &req)
  524. if err != nil {
  525. portal.log.Errorln("Error batch sending messages:", err)
  526. return nil
  527. } else {
  528. txn, err := portal.bridge.DB.Begin()
  529. if err != nil {
  530. portal.log.Errorln("Failed to start transaction to save batch messages:", err)
  531. return nil
  532. }
  533. // Do the following block in the transaction
  534. {
  535. portal.finishBatch(txn, resp.EventIDs, infos)
  536. portal.NextBatchID = resp.NextBatchID
  537. portal.Update(txn)
  538. }
  539. err = txn.Commit()
  540. if err != nil {
  541. portal.log.Errorln("Failed to commit transaction to save batch messages:", err)
  542. return nil
  543. }
  544. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia {
  545. go portal.requestMediaRetries(source, resp.EventIDs, infos)
  546. }
  547. return resp
  548. }
  549. }
  550. func (portal *Portal) requestMediaRetries(source *User, eventIDs []id.EventID, infos []*wrappedInfo) {
  551. for i, info := range infos {
  552. if info != nil && info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  553. switch portal.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod {
  554. case config.MediaRequestMethodImmediate:
  555. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  556. if err != nil {
  557. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  558. } else {
  559. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  560. }
  561. case config.MediaRequestMethodLocalTime:
  562. req := portal.bridge.DB.MediaBackfillRequest.NewMediaBackfillRequestWithValues(source.MXID, &portal.Key, eventIDs[i], info.MediaKey)
  563. req.Upsert()
  564. }
  565. }
  566. }
  567. }
  568. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  569. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra, "")
  570. if err != nil {
  571. return err
  572. }
  573. if portal.bridge.Config.Bridge.CaptionInMessage {
  574. converted.MergeCaption()
  575. }
  576. if converted.Caption != nil {
  577. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil, "caption")
  578. if err != nil {
  579. return err
  580. }
  581. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  582. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn}, nil)
  583. } else {
  584. *eventsArray = append(*eventsArray, mainEvt)
  585. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn})
  586. }
  587. if converted.MultiEvent != nil {
  588. for i, subEvtContent := range converted.MultiEvent {
  589. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil, fmt.Sprintf("multi-%d", i))
  590. if err != nil {
  591. return err
  592. }
  593. *eventsArray = append(*eventsArray, subEvt)
  594. *infoArray = append(*infoArray, nil)
  595. }
  596. }
  597. return nil
  598. }
  599. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, partName string) (*event.Event, error) {
  600. wrappedContent := event.Content{
  601. Parsed: content,
  602. Raw: extraContent,
  603. }
  604. newEventType, err := portal.encrypt(intent, &wrappedContent, eventType)
  605. if err != nil {
  606. return nil, err
  607. }
  608. if newEventType != eventType {
  609. intent.AddDoublePuppetValue(&wrappedContent)
  610. }
  611. var eventID id.EventID
  612. if portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  613. eventID = portal.deterministicEventID(info.Sender, info.ID, partName)
  614. }
  615. return &event.Event{
  616. ID: eventID,
  617. Sender: intent.UserID,
  618. Type: newEventType,
  619. Timestamp: info.Timestamp.UnixMilli(),
  620. Content: wrappedContent,
  621. }, nil
  622. }
  623. func (portal *Portal) finishBatch(txn dbutil.Transaction, eventIDs []id.EventID, infos []*wrappedInfo) {
  624. for i, info := range infos {
  625. if info == nil {
  626. continue
  627. }
  628. eventID := eventIDs[i]
  629. portal.markHandled(txn, nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  630. if info.ExpiresIn > 0 {
  631. if info.ExpirationStart > 0 {
  632. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  633. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  634. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  635. } else {
  636. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  637. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  638. }
  639. }
  640. }
  641. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  642. }
  643. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  644. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, HistorySyncMarker, map[string]interface{}{
  645. "org.matrix.msc2716.marker.insertion": insertionEventId,
  646. //"m.marker.insertion": insertionEventId,
  647. })
  648. if err != nil {
  649. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  650. return
  651. }
  652. msg := portal.bridge.DB.Message.New()
  653. msg.Chat = portal.Key
  654. msg.MXID = resp.EventID
  655. msg.JID = types.MessageID(resp.EventID)
  656. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  657. msg.Sent = true
  658. msg.Type = database.MsgFake
  659. msg.Insert(nil)
  660. }
  661. func (portal *Portal) updateBackfillStatus(backfillState *database.BackfillState) {
  662. backfillStatus := "backfilling"
  663. if backfillState.BackfillComplete {
  664. backfillStatus = "complete"
  665. }
  666. _, err := portal.MainIntent().SendStateEvent(portal.MXID, BackfillStatusEvent, "", map[string]interface{}{
  667. "status": backfillStatus,
  668. "first_timestamp": backfillState.FirstExpectedTimestamp * 1000,
  669. })
  670. if err != nil {
  671. portal.log.Errorln("Error sending backfill status event:", err)
  672. }
  673. }
  674. // endregion