statestore.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2018 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. "encoding/json"
  19. "io/ioutil"
  20. "os"
  21. "maunium.net/go/mautrix-appservice"
  22. "maunium.net/go/mautrix"
  23. )
  24. type AutosavingStateStore struct {
  25. appservice.StateStore
  26. Path string
  27. }
  28. func NewAutosavingStateStore(path string) *AutosavingStateStore {
  29. return &AutosavingStateStore{
  30. StateStore: appservice.NewBasicStateStore(),
  31. Path: path,
  32. }
  33. }
  34. func (store *AutosavingStateStore) Save() error {
  35. store.RLock()
  36. defer store.RUnlock()
  37. data, err := json.Marshal(store.StateStore)
  38. if err != nil {
  39. return err
  40. }
  41. return ioutil.WriteFile(store.Path, data, 0600)
  42. }
  43. func (store *AutosavingStateStore) Load() error {
  44. store.Lock()
  45. defer store.Unlock()
  46. data, err := ioutil.ReadFile(store.Path)
  47. if err != nil {
  48. if os.IsNotExist(err) {
  49. return nil
  50. }
  51. return err
  52. }
  53. return json.Unmarshal(data, store.StateStore)
  54. }
  55. func (store *AutosavingStateStore) MarkRegistered(userID string) {
  56. store.StateStore.MarkRegistered(userID)
  57. store.Save()
  58. }
  59. func (store *AutosavingStateStore) SetMembership(roomID, userID string, membership mautrix.Membership) {
  60. store.StateStore.SetMembership(roomID, userID, membership)
  61. store.Save()
  62. }
  63. func (store *AutosavingStateStore) SetPowerLevels(roomID string, levels *mautrix.PowerLevels) {
  64. store.StateStore.SetPowerLevels(roomID, levels)
  65. store.Save()
  66. }