102 lines
2.2 KiB
Go
102 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
slack "git.bullercodeworks.com/brian/go-slack"
|
|
"git.bullercodeworks.com/brian/helperbot"
|
|
"github.com/br0xen/boltease"
|
|
)
|
|
|
|
type BotModel struct {
|
|
db *boltease.DB
|
|
|
|
messages chan helperbot.Message
|
|
|
|
slack *slack.Slack
|
|
|
|
cache map[string][]byte
|
|
}
|
|
|
|
func NewBotModel() (*BotModel, error) {
|
|
var err error
|
|
m := new(BotModel)
|
|
m.cache = make(map[string][]byte)
|
|
m.messages = make(chan helperbot.Message, 100)
|
|
m.db, err = boltease.Create("helperbot.db", 0600, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.db.MkBucketPath([]string{"slack", "users"})
|
|
m.db.MkBucketPath([]string{"slack", "channels"})
|
|
|
|
return m, nil
|
|
}
|
|
|
|
func (m *BotModel) SendMessage(src, dst string, msg slack.Message) {
|
|
m.messages <- NewBotMessage(src, dst, msg)
|
|
}
|
|
|
|
func (m *BotModel) getPluginDir() string {
|
|
ret, err := m.GetString([]string{"config", "plugin_dir"})
|
|
if err != nil || strings.TrimSpace(ret) == "" {
|
|
ret = "./plugins/"
|
|
if err = m.SetString([]string{"config", "plugin_dir"}, ret); err != nil {
|
|
fmt.Println("Error setting plugin directory")
|
|
fmt.Println(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
fmt.Println("Plugin Dir: ", ret)
|
|
return ret
|
|
}
|
|
|
|
func (m *BotModel) GetBytes(path []string) ([]byte, error) {
|
|
var err error
|
|
var v []byte
|
|
var ok bool
|
|
joinedPath := strings.Join(path, "/")
|
|
if v, ok = m.cache[joinedPath]; !ok {
|
|
// Value is not cached, try to pull it from the DB
|
|
if len(path) > 2 {
|
|
path, key := path[:len(path)-1], path[len(path)-1]
|
|
v, err = m.db.GetBytes(path, key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.cache[joinedPath] = v
|
|
}
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
func (m *BotModel) SetBytes(path []string, val []byte) error {
|
|
if len(path) > 1 {
|
|
joinedPath := strings.Join(path, "/")
|
|
path, key := path[:len(path)-1], path[len(path)-1]
|
|
err := m.db.SetBytes(path, key, val)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Update the cache
|
|
m.cache[joinedPath] = val
|
|
return nil
|
|
}
|
|
return errors.New("Invalid path")
|
|
}
|
|
|
|
func (m *BotModel) GetString(path []string) (string, error) {
|
|
bts, err := m.GetBytes(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(bts), nil
|
|
}
|
|
|
|
func (m *BotModel) SetString(path []string, val string) error {
|
|
return m.SetBytes(path, []byte(val))
|
|
}
|