statestore.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/gomatrix"
  22. "maunium.net/go/mautrix-appservice"
  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. data, err := json.Marshal(store.StateStore)
  36. if err != nil {
  37. return err
  38. }
  39. return ioutil.WriteFile(store.Path, data, 0600)
  40. }
  41. func (store *AutosavingStateStore) Load() error {
  42. data, err := ioutil.ReadFile(store.Path)
  43. if err != nil {
  44. if os.IsNotExist(err) {
  45. return nil
  46. }
  47. return err
  48. }
  49. return json.Unmarshal(data, store.StateStore)
  50. }
  51. func (store *AutosavingStateStore) MarkRegistered(userID string) {
  52. store.StateStore.MarkRegistered(userID)
  53. store.Save()
  54. }
  55. func (store *AutosavingStateStore) SetMembership(roomID, userID string, membership gomatrix.Membership) {
  56. store.StateStore.SetMembership(roomID, userID, membership)
  57. store.Save()
  58. }
  59. func (store *AutosavingStateStore) SetPowerLevels(roomID string, levels *gomatrix.PowerLevels) {
  60. store.StateStore.SetPowerLevels(roomID, levels)
  61. store.Save()
  62. }