88 lines
1.9 KiB
Go
88 lines
1.9 KiB
Go
package matrixbotlib
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/gob"
|
|
|
|
"os"
|
|
|
|
"maunium.net/go/mautrix"
|
|
"maunium.net/go/mautrix/id"
|
|
)
|
|
|
|
//LazyMemStore is a very simple persistent Mautrix.Storer by saving to a statefile
|
|
//It should only be used if for some reason the InMemoryStore or AccountDataStore aren't acceptable
|
|
type LazyMemStore struct {
|
|
mem *mautrix.InMemoryStore
|
|
NextBatch map[id.UserID]string
|
|
saveFile string
|
|
}
|
|
|
|
func NewLazyMemStore(fileloc string) *LazyMemStore {
|
|
return &LazyMemStore{
|
|
mem: mautrix.NewInMemoryStore(),
|
|
NextBatch: make(map[id.UserID]string),
|
|
saveFile: fileloc,
|
|
}
|
|
}
|
|
|
|
func (l *LazyMemStore) SaveFilterID(userID id.UserID, filterID string) {
|
|
l.mem.SaveFilterID(userID, filterID)
|
|
}
|
|
|
|
func (l *LazyMemStore) LoadFilterID(userID id.UserID) string {
|
|
return l.mem.LoadFilterID(userID)
|
|
}
|
|
|
|
func (l *LazyMemStore) SaveNextBatch(userID id.UserID, nextBatchToken string) {
|
|
b := new(bytes.Buffer)
|
|
l.NextBatch[userID] = nextBatchToken
|
|
e := gob.NewEncoder(b)
|
|
err := e.Encode(l.NextBatch)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err := os.WriteFile(l.saveFile, b.Bytes(), 0666); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
}
|
|
|
|
func (l *LazyMemStore) LoadNextBatch(userID id.UserID) string {
|
|
|
|
dat, err := os.ReadFile(l.saveFile)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
b := new(bytes.Buffer)
|
|
e := gob.NewEncoder(b)
|
|
err := e.Encode(l.NextBatch)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err := os.WriteFile(l.saveFile, b.Bytes(), 0666); err != nil {
|
|
panic(err)
|
|
}
|
|
dat, err = os.ReadFile(l.saveFile)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
} else {
|
|
panic(err)
|
|
}
|
|
}
|
|
d := gob.NewDecoder(bytes.NewBuffer(dat))
|
|
err = d.Decode(&l.NextBatch)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return l.NextBatch[userID]
|
|
}
|
|
|
|
func (l *LazyMemStore) SaveRoom(room *mautrix.Room) {
|
|
l.mem.SaveRoom(room)
|
|
}
|
|
|
|
func (l *LazyMemStore) LoadRoom(roomID id.RoomID) *mautrix.Room {
|
|
return l.mem.LoadRoom(roomID)
|
|
}
|