mcchunkie/store.go

103 lines
2.2 KiB
Go
Raw Permalink Normal View History

package main
import (
"bytes"
"encoding/gob"
2020-02-04 19:02:18 -07:00
"fmt"
2020-10-20 18:51:53 -06:00
"log"
"os"
"path"
"strings"
"github.com/matrix-org/gomatrix"
)
2020-10-20 18:51:53 -06:00
// FStore is the path to a directory which will contain our data.
type FStore string
2020-10-20 18:51:53 -06: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-20 18:51:53 -06:00
if !fi.IsDir() {
return nil, fmt.Errorf("not a directory")
}
fstore := FStore(s)
return &fstore, nil
}
2020-10-20 18:51:53 -06: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-20 18:51:53 -06: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-20 18:51:53 -06:00
// Set dumps value into a file named key
func (s FStore) Set(key string, value string) {
err := os.WriteFile(path.Join(string(s), key), []byte(value), 0600)
2020-10-20 18:51:53 -06:00
if err != nil {
log.Println(err)
}
}
// Get pulls value from a file named key
func (s FStore) Get(key string) (string, error) {
data, err := os.ReadFile(path.Join(string(s), key))
2020-10-20 18:51:53 -06:00
if err != nil {
return "", nil
}
return strings.TrimSpace(string(data)), nil
2020-10-20 18:51:53 -06:00
}
// SaveFilterID exposed for gomatrix
2020-10-20 18:51:53 -06:00
func (s *FStore) SaveFilterID(userID, filterID string) {
2020-02-05 22:04:04 -07:00
s.Set(fmt.Sprintf("filter_%s", userID), filterID)
}
// LoadFilterID exposed for gomatrix
2020-10-20 18:51:53 -06:00
func (s *FStore) 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
}
2020-10-20 18:51:53 -06:00
func (s *FStore) SaveNextBatch(userID, nextBatchToken string) {
2020-02-05 22:04:04 -07:00
s.Set(fmt.Sprintf("batch_%s", userID), nextBatchToken)
}
// LoadNextBatch exposed for gomatrix
2020-10-20 18:51:53 -06:00
func (s *FStore) 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
2020-10-20 18:51:53 -06:00
func (s *FStore) 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
2020-10-20 18:51:53 -06:00
func (s *FStore) 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
}