userportal.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 database
  17. import (
  18. "database/sql"
  19. "errors"
  20. "fmt"
  21. "time"
  22. )
  23. func (user *User) GetLastReadTS(portal PortalKey) time.Time {
  24. var ts int64
  25. err := user.db.QueryRow("SELECT last_read_ts FROM user_portal WHERE user_mxid=$1 AND portal_jid=$2 AND portal_receiver=$3", user.MXID, portal.JID, portal.Receiver).Scan(&ts)
  26. if err != nil && !errors.Is(err, sql.ErrNoRows) {
  27. user.log.Warnfln("Failed to scan last read timestamp from user portal table: %v", err)
  28. }
  29. if ts == 0 {
  30. return time.Time{}
  31. }
  32. return time.Unix(ts, 0)
  33. }
  34. func (user *User) SetLastReadTS(portal PortalKey, ts time.Time) {
  35. var err error
  36. if user.db.dialect == "postgres" {
  37. _, err = user.db.Exec(`
  38. INSERT INTO user_portal (user_mxid, portal_jid, portal_receiver, last_read_ts) VALUES ($1, $2, $3, $4)
  39. ON CONFLICT (user_mxid, portal_jid, portal_receiver) DO UPDATE SET last_read_ts=$4 WHERE user_portal.last_read_ts<$4
  40. `, user.MXID, portal.JID, portal.Receiver, ts.Unix())
  41. } else if user.db.dialect == "sqlite3" {
  42. _, err = user.db.Exec(
  43. "INSERT OR REPLACE INTO user_portal (user_mxid, portal_jid, portal_receiver, last_read_ts) VALUES (?, ?, ?, ?)",
  44. user.MXID, portal.JID, portal.Receiver, ts.Unix())
  45. } else {
  46. err = fmt.Errorf("unsupported dialect %s", user.db.dialect)
  47. }
  48. if err != nil {
  49. user.log.Warnfln("Failed to update last read timestamp: %v", err)
  50. }
  51. }