statestore.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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/gomatrix"
  19. "maunium.net/go/mautrix-appservice"
  20. "encoding/json"
  21. "io/ioutil"
  22. "os"
  23. )
  24. type AutosavingStateStore struct {
  25. *appservice.BasicStateStore
  26. Path string
  27. }
  28. func NewAutosavingStateStore(path string) *AutosavingStateStore {
  29. return &AutosavingStateStore{
  30. BasicStateStore: appservice.NewBasicStateStore(),
  31. Path: path,
  32. }
  33. }
  34. func (store *AutosavingStateStore) Save() error {
  35. data, err := json.Marshal(store.BasicStateStore)
  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.BasicStateStore)
  50. }
  51. func (store *AutosavingStateStore) MarkRegistered(userID string) {
  52. store.BasicStateStore.MarkRegistered(userID)
  53. store.Save()
  54. }
  55. func (store *AutosavingStateStore) SetMembership(roomID, userID, membership string) {
  56. store.BasicStateStore.SetMembership(roomID, userID, membership)
  57. store.Save()
  58. }
  59. func (store *AutosavingStateStore) SetPowerLevels(roomID string, levels gomatrix.PowerLevels) {
  60. store.BasicStateStore.SetPowerLevels(roomID, levels)
  61. store.Save()
  62. }