mcchunkie/store.go

104 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"bytes"
"encoding/gob"
2020-02-05 02:02:18 +00:00
"fmt"
2020-10-21 00:51:53 +00:00
"io/ioutil"
"log"
"os"
"path"
"strings"
"github.com/matrix-org/gomatrix"
)
2020-10-21 00:51:53 +00:00
// FStore is the path to a directory which will contain our data.
type FStore string
2020-10-21 00:51:53 +00:00
// NewStore creates a new instance of FStore
func NewStore(s string) (*FStore, error) {
fi, err := os.Lstat(s)
if err != nil {
return nil, err
}
2020-10-21 00:51:53 +00:00
if !fi.IsDir() {
return nil, fmt.Errorf("not a directory")
}
fstore := FStore(s)
return &fstore, nil
}
2020-10-21 00:51:53 +00:00
func (s *FStore) 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
}
2020-10-21 00:51:53 +00:00
func (s *FStore) 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
}
2020-10-21 00:51:53 +00:00
// Set dumps value into a file named key
func (s FStore) Set(key string, value string) {
err := ioutil.WriteFile(path.Join(string(s), key), []byte(value), 0600)
if err != nil {
log.Println(err)
}
}
// Get pulls value from a file named key
func (s FStore) Get(key string) (string, error) {
data, err := ioutil.ReadFile(path.Join(string(s), key))
if err != nil {
return "", nil
}
return strings.TrimSpace(string(data)), nil
2020-10-21 00:51:53 +00:00
}
// SaveFilterID exposed for gomatrix
2020-10-21 00:51:53 +00:00
func (s *FStore) SaveFilterID(userID, filterID string) {
2020-02-06 05:04:04 +00:00
s.Set(fmt.Sprintf("filter_%s", userID), filterID)
}
// LoadFilterID exposed for gomatrix
2020-10-21 00:51:53 +00:00
func (s *FStore) LoadFilterID(userID string) string {
2020-02-06 05:04:04 +00:00
filter, _ := s.Get(fmt.Sprintf("filter_%s", userID))
2020-05-13 22:53:31 +00:00
return filter
}
2020-10-21 00:51:53 +00:00
func (s *FStore) SaveNextBatch(userID, nextBatchToken string) {
2020-02-06 05:04:04 +00:00
s.Set(fmt.Sprintf("batch_%s", userID), nextBatchToken)
}
// LoadNextBatch exposed for gomatrix
2020-10-21 00:51:53 +00:00
func (s *FStore) LoadNextBatch(userID string) string {
2020-02-06 05:04:04 +00:00
batch, _ := s.Get(fmt.Sprintf("batch_%s", userID))
2020-05-13 22:53:31 +00:00
return batch
}
// SaveRoom exposed for gomatrix
2020-10-21 00:51:53 +00:00
func (s *FStore) SaveRoom(room *gomatrix.Room) {
b, _ := s.encodeRoom(room)
2020-02-06 05:04:04 +00:00
s.Set(fmt.Sprintf("room_%s", room.ID), string(b))
}
// LoadRoom exposed for gomatrix
2020-10-21 00:51:53 +00:00
func (s *FStore) LoadRoom(roomID string) *gomatrix.Room {
2020-02-06 05:04:04 +00:00
b, _ := s.Get(fmt.Sprintf("room_%s", roomID))
2020-02-05 00:22:19 +00:00
room, _ := s.decodeRoom([]byte(b))
return room
}