helperbot/cmd/model.go

112 lines
2.4 KiB
Go
Raw Normal View History

2019-11-13 00:45:56 +00:00
package main
import (
"errors"
"fmt"
"os"
"strings"
2019-11-22 18:37:15 +00:00
"time"
2019-11-13 00:45:56 +00:00
"git.bullercodeworks.com/brian/helperbot"
"github.com/br0xen/boltease"
2019-11-21 23:45:04 +00:00
"github.com/nlopes/slack"
2019-11-13 00:45:56 +00:00
)
type BotModel struct {
db *boltease.DB
messages chan helperbot.Message
2019-11-22 18:37:15 +00:00
slackApiToken string
slackApi *slack.Client
slackRTM *slack.RTM
slackRTMLatency time.Duration
slackIdToFriendly map[string]string
IncomingSlackMessages chan *slack.MessageEvent
OtherRTMEvents chan *slack.RTMEvent
2019-11-13 00:45:56 +00:00
2019-11-22 18:37:15 +00:00
dataCache map[string][]byte
2019-11-13 00:45:56 +00:00
}
func NewBotModel() (*BotModel, error) {
var err error
m := new(BotModel)
2019-11-22 18:37:15 +00:00
m.dataCache = make(map[string][]byte)
2019-11-13 00:45:56 +00:00
m.messages = make(chan helperbot.Message, 100)
m.db, err = boltease.Create("helperbot.db", 0600, nil)
if err != nil {
return nil, err
}
2019-11-22 18:37:15 +00:00
if err = m.NewSlack(); err != nil {
return nil, err
}
2019-11-13 00:45:56 +00:00
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, "/")
2019-11-22 18:37:15 +00:00
if v, ok = m.dataCache[joinedPath]; !ok {
2019-11-13 00:45:56 +00:00
// 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
}
2019-11-22 18:37:15 +00:00
m.dataCache[joinedPath] = v
2019-11-13 00:45:56 +00:00
}
}
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
2019-11-22 18:37:15 +00:00
m.dataCache[joinedPath] = val
2019-11-13 00:45:56 +00:00
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
}
2019-11-21 23:45:04 +00:00
if len(bts) == 0 {
return "", nil
}
2019-11-13 00:45:56 +00:00
return string(bts), nil
}
func (m *BotModel) SetString(path []string, val string) error {
return m.SetBytes(path, []byte(val))
}