mcchunkie/store.go

97 lines
2.1 KiB
Go
Raw Normal View History

package main
import (
"bytes"
"encoding/gob"
"github.com/matrix-org/gomatrix"
2020-02-04 17:22:19 -07:00
"github.com/peterbourgon/diskv"
)
2020-02-04 17:22:19 -07:00
// MCStore implements a gomatrix.Storer and exposes a diskv db to be used for
// application storage (account info, config info etc).
type MCStore struct {
2020-02-04 17:22:19 -07:00
db *diskv.Diskv
}
// NewStore creates a new MCStore instance populated with the proper buckets.
func NewStore(path string) (*MCStore, error) {
2020-02-04 17:22:19 -07:00
flatTransform := func(s string) []string { return []string{} }
db := diskv.New(diskv.Options{
BasePath: "db",
Transform: flatTransform,
CacheSizeMax: 1024 * 1024,
})
s := &MCStore{db: db}
return s, nil
}
2020-02-04 17:22:19 -07:00
func (s *MCStore) set(key string, value string) {
v := []byte(value)
s.db.Write(key, v)
}
2020-02-04 17:22:19 -07:00
func (s *MCStore) get(key string) (string, error) {
b, err := s.db.Read(key)
return string(b), err
}
func (s *MCStore) encodeRoom(room *gomatrix.Room) ([]byte, error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
err := enc.Encode(room)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (s *MCStore) decodeRoom(room []byte) (*gomatrix.Room, error) {
var r *gomatrix.Room
buf := bytes.NewBuffer(room)
dec := gob.NewDecoder(buf)
err := dec.Decode(&r)
if err != nil {
return nil, err
}
return r, nil
}
// SaveFilterID exposed for gomatrix
func (s *MCStore) SaveFilterID(userID, filterID string) {
2020-02-04 17:22:19 -07:00
s.set(userID, filterID)
}
// LoadFilterID exposed for gomatrix
func (s *MCStore) LoadFilterID(userID string) string {
2020-02-04 17:22:19 -07:00
filter, _ := s.get(userID)
return string(filter)
}
// SaveNextBatch exposed for gomatrix
func (s *MCStore) SaveNextBatch(userID, nextBatchToken string) {
2020-02-04 17:22:19 -07:00
s.set(userID, nextBatchToken)
}
// LoadNextBatch exposed for gomatrix
func (s *MCStore) LoadNextBatch(userID string) string {
2020-02-04 17:22:19 -07:00
batch, _ := s.get(userID)
return string(batch)
}
// SaveRoom exposed for gomatrix
func (s *MCStore) SaveRoom(room *gomatrix.Room) {
b, _ := s.encodeRoom(room)
2020-02-04 17:22:19 -07:00
s.set(room.ID, string(b))
}
// LoadRoom exposed for gomatrix
func (s *MCStore) LoadRoom(roomID string) *gomatrix.Room {
2020-02-04 17:22:19 -07:00
b, _ := s.get(roomID)
room, _ := s.decodeRoom([]byte(b))
return room
}