disappear.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 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. "go.mau.fi/util/dbutil"
  21. "maunium.net/go/mautrix"
  22. "maunium.net/go/mautrix/id"
  23. "maunium.net/go/mautrix-whatsapp/database"
  24. )
  25. func (portal *Portal) MarkDisappearing(txn dbutil.Execable, eventID id.EventID, expiresIn time.Duration, startsAt time.Time) {
  26. if expiresIn == 0 {
  27. return
  28. }
  29. expiresAt := startsAt.Add(expiresIn)
  30. msg := portal.bridge.DB.DisappearingMessage.NewWithValues(portal.MXID, eventID, expiresIn, expiresAt)
  31. msg.Insert(txn)
  32. if expiresAt.Before(time.Now().Add(1 * time.Hour)) {
  33. go portal.sleepAndDelete(msg)
  34. }
  35. }
  36. func (br *WABridge) SleepAndDeleteUpcoming() {
  37. for _, msg := range br.DB.DisappearingMessage.GetUpcomingScheduled(1 * time.Hour) {
  38. portal := br.GetPortalByMXID(msg.RoomID)
  39. if portal == nil {
  40. msg.Delete()
  41. } else {
  42. go portal.sleepAndDelete(msg)
  43. }
  44. }
  45. }
  46. func (portal *Portal) sleepAndDelete(msg *database.DisappearingMessage) {
  47. if _, alreadySleeping := portal.currentlySleepingToDelete.LoadOrStore(msg.EventID, true); alreadySleeping {
  48. return
  49. }
  50. defer portal.currentlySleepingToDelete.Delete(msg.EventID)
  51. sleepTime := msg.ExpireAt.Sub(time.Now())
  52. portal.log.Debugfln("Sleeping for %s to make %s disappear", sleepTime, msg.EventID)
  53. time.Sleep(sleepTime)
  54. _, err := portal.MainIntent().RedactEvent(msg.RoomID, msg.EventID, mautrix.ReqRedact{
  55. Reason: "Message expired",
  56. TxnID: fmt.Sprintf("mxwa_disappear_%s", msg.EventID),
  57. })
  58. if err != nil {
  59. portal.log.Warnfln("Failed to make %s disappear: %v", msg.EventID, err)
  60. } else {
  61. portal.log.Debugfln("Disappeared %s", msg.EventID)
  62. }
  63. msg.Delete()
  64. }