mautrix-whatsapp/statestore.go

75 lines
2 KiB
Go
Raw Normal View History

2018-08-16 18:20:07 +02:00
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2018 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"encoding/json"
"io/ioutil"
"os"
2018-08-26 21:53:13 +02:00
"maunium.net/go/gomatrix"
"maunium.net/go/mautrix-appservice"
2018-08-16 18:20:07 +02:00
)
type AutosavingStateStore struct {
2018-08-26 22:31:59 +02:00
appservice.StateStore
2018-08-16 18:20:07 +02:00
Path string
}
func NewAutosavingStateStore(path string) *AutosavingStateStore {
return &AutosavingStateStore{
2018-08-26 22:31:59 +02:00
StateStore: appservice.NewBasicStateStore(),
Path: path,
2018-08-16 18:20:07 +02:00
}
}
func (store *AutosavingStateStore) Save() error {
2018-08-26 22:31:59 +02:00
data, err := json.Marshal(store.StateStore)
2018-08-16 18:20:07 +02:00
if err != nil {
return err
}
return ioutil.WriteFile(store.Path, data, 0600)
}
func (store *AutosavingStateStore) Load() error {
data, err := ioutil.ReadFile(store.Path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
2018-08-26 22:31:59 +02:00
return json.Unmarshal(data, store.StateStore)
2018-08-16 18:20:07 +02:00
}
func (store *AutosavingStateStore) MarkRegistered(userID string) {
2018-08-26 22:31:59 +02:00
store.StateStore.MarkRegistered(userID)
2018-08-16 18:20:07 +02:00
store.Save()
}
2018-09-22 17:27:16 +02:00
func (store *AutosavingStateStore) SetMembership(roomID, userID string, membership gomatrix.Membership) {
2018-08-26 22:31:59 +02:00
store.StateStore.SetMembership(roomID, userID, membership)
2018-08-16 18:20:07 +02:00
store.Save()
}
func (store *AutosavingStateStore) SetPowerLevels(roomID string, levels *gomatrix.PowerLevels) {
2018-08-26 22:31:59 +02:00
store.StateStore.SetPowerLevels(roomID, levels)
store.Save()
2018-08-26 21:53:13 +02:00
}