mcchunkie/store.go

100 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"bytes"
"encoding/gob"
2020-02-04 19:02:18 -07:00
"fmt"
"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
}
2020-02-04 19:07:17 -07:00
// NewStore creates a new MCStore instance.
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{
2020-05-13 16:53:31 -06:00
BasePath: path,
2020-02-04 17:22:19 -07:00
Transform: flatTransform,
CacheSizeMax: 1024 * 1024,
})
s := &MCStore{db: db}
return s, nil
}
2020-02-05 22:04:04 -07:00
// Set takes a key value pair and shoves it in a db.
func (s *MCStore) Set(key string, value string) {
2020-02-04 17:22:19 -07:00
v := []byte(value)
2020-05-13 16:53:31 -06:00
_ = s.db.Write(key, v)
}
2020-02-05 22:04:04 -07:00
// Get retrives a value from the db
func (s *MCStore) Get(key string) (string, error) {
2020-02-04 17:22:19 -07:00
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-05 22:04:04 -07:00
s.Set(fmt.Sprintf("filter_%s", userID), filterID)
}
// LoadFilterID exposed for gomatrix
func (s *MCStore) LoadFilterID(userID string) string {
2020-02-05 22:04:04 -07:00
filter, _ := s.Get(fmt.Sprintf("filter_%s", userID))
2020-05-13 16:53:31 -06:00
return filter
}
// SaveNextBatch exposed for gomatrix
func (s *MCStore) SaveNextBatch(userID, nextBatchToken string) {
2020-02-05 22:04:04 -07:00
s.Set(fmt.Sprintf("batch_%s", userID), nextBatchToken)
}
// LoadNextBatch exposed for gomatrix
func (s *MCStore) LoadNextBatch(userID string) string {
2020-02-05 22:04:04 -07:00
batch, _ := s.Get(fmt.Sprintf("batch_%s", userID))
2020-05-13 16:53:31 -06:00
return batch
}
// SaveRoom exposed for gomatrix
func (s *MCStore) SaveRoom(room *gomatrix.Room) {
b, _ := s.encodeRoom(room)
2020-02-05 22:04:04 -07:00
s.Set(fmt.Sprintf("room_%s", room.ID), string(b))
}
// LoadRoom exposed for gomatrix
func (s *MCStore) LoadRoom(roomID string) *gomatrix.Room {
2020-02-05 22:04:04 -07:00
b, _ := s.Get(fmt.Sprintf("room_%s", roomID))
2020-02-04 17:22:19 -07:00
room, _ := s.decodeRoom([]byte(b))
return room
}