statestore.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "maunium.net/go/mautrix-appservice"
  19. "encoding/json"
  20. "io/ioutil"
  21. "os"
  22. )
  23. type AutosavingStateStore struct {
  24. *appservice.BasicStateStore
  25. Path string
  26. }
  27. func NewAutosavingStateStore(path string) *AutosavingStateStore {
  28. return &AutosavingStateStore{
  29. BasicStateStore: appservice.NewBasicStateStore(),
  30. Path: path,
  31. }
  32. }
  33. func (store *AutosavingStateStore) Save() error {
  34. data, err := json.Marshal(store.BasicStateStore)
  35. if err != nil {
  36. return err
  37. }
  38. return ioutil.WriteFile(store.Path, data, 0600)
  39. }
  40. func (store *AutosavingStateStore) Load() error {
  41. data, err := ioutil.ReadFile(store.Path)
  42. if err != nil {
  43. if os.IsNotExist(err) {
  44. return nil
  45. }
  46. return err
  47. }
  48. return json.Unmarshal(data, store.BasicStateStore)
  49. }
  50. func (store *AutosavingStateStore) MarkRegistered(userID string) {
  51. store.BasicStateStore.MarkRegistered(userID)
  52. store.Save()
  53. }
  54. func (store *AutosavingStateStore) SetMembership(roomID, userID, membership string) {
  55. store.BasicStateStore.SetMembership(roomID, userID, membership)
  56. store.Save()
  57. }