86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/gob"
|
|
|
|
"os"
|
|
|
|
"maunium.net/go/mautrix"
|
|
"maunium.net/go/mautrix/id"
|
|
)
|
|
|
|
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)
|
|
}
|