added config tests and removed logger from sub packages

This commit is contained in:
gempir 2017-03-10 18:09:13 +01:00
parent 44d31878e9
commit 96bc623aab
9 changed files with 84 additions and 54 deletions

View file

@ -7,7 +7,7 @@ install:
go install
test:
go test -v
go test -v $(shell go list ./... | grep -v /vendor/)
cover:
echo "mode: count" > coverage-all.out

View file

@ -61,7 +61,6 @@ func (s *Server) getDatedChannelLogs(c echo.Context) error {
file = file + ".gz"
f, err := os.Open(file)
if err != nil {
s.log.Error(err.Error())
errJSON := new(ErrorJSON)
errJSON.Error = "error finding logs"
return c.JSON(http.StatusNotFound, errJSON)
@ -69,7 +68,6 @@ func (s *Server) getDatedChannelLogs(c echo.Context) error {
gz, err := gzip.NewReader(f)
scanner := bufio.NewScanner(gz)
if err != nil {
s.log.Error(err.Error())
errJSON := new(ErrorJSON)
errJSON.Error = "error finding logs"
return c.JSON(http.StatusNotFound, errJSON)
@ -79,10 +77,8 @@ func (s *Server) getDatedChannelLogs(c echo.Context) error {
line := scanner.Text()
content += line + "\r\n"
}
s.log.Debug(file)
return c.String(http.StatusOK, content)
} else {
s.log.Debug(file)
return c.File(file)
}
@ -121,22 +117,17 @@ func (s *Server) getRandomQuote(c echo.Context) error {
}
file := userLogs[rand.Intn(len(userLogs))]
s.log.Debug(file, len(userLogs))
f, err := os.Open(file)
defer f.Close()
if err != nil {
s.log.Error(err.Error())
return c.JSON(http.StatusNotFound, errJSON)
}
scanner := bufio.NewScanner(f)
if strings.HasSuffix(file, ".gz") {
gz, err := gzip.NewReader(f)
gz, _ := gzip.NewReader(f)
scanner = bufio.NewScanner(gz)
if err != nil {
s.log.Error(err.Error())
}
}
for scanner.Scan() {
@ -145,7 +136,6 @@ func (s *Server) getRandomQuote(c echo.Context) error {
}
if err := scanner.Err(); err != nil {
s.log.Error(scanner.Err().Error())
errJSON := new(ErrorJSON)
errJSON.Error = "error finding logs"
return c.JSON(http.StatusNotFound, errJSON)
@ -158,7 +148,6 @@ func (s *Server) getRandomQuote(c echo.Context) error {
ranNum := rand.Intn(len(lines))
line := lines[ranNum]
s.log.Debug(line)
lineSplit := strings.SplitN(line, "]", 2)
return c.String(http.StatusOK, lineSplit[1])
}

View file

@ -1,7 +1,6 @@
package api
import (
"github.com/op/go-logging"
"github.com/labstack/echo"
"net/http"
)
@ -9,20 +8,19 @@ import (
type Server struct {
port string
logPath string
log logging.Logger
}
func NewServer(port string, logPath string, logger logging.Logger) Server {
func NewServer(port string, logPath string) Server {
return Server{
port: port,
logPath: logPath,
log: logger,
}
}
func (s *Server) Init() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
@ -30,5 +28,5 @@ func (s *Server) Init() {
e.GET("/channel/:channel/user/:username/:year/:month", s.getDatedChannelLogs)
e.GET("/channel/:channel/user/:username/random", s.getRandomQuote)
s.log.Error(e.Start("127.0.0.1:" + s.port).Error())
e.Logger.Fatal(e.Start("127.0.0.1:" + s.port))
}

20
combo/handler.go Normal file
View file

@ -0,0 +1,20 @@
package combo
import (
"github.com/gempir/gempbotgo/twitch"
)
type Handler struct {
}
func NewHandler() Handler {
return Handler{
}
}
func (h *Handler) HandleMessage(msg twitch.Message){
}

View file

@ -1,7 +1,6 @@
package filelog
import (
"github.com/op/go-logging"
"github.com/gempir/gempbotgo/twitch"
"strings"
"os"
@ -9,36 +8,34 @@ import (
)
type Logger struct {
log logging.Logger
logPath string
}
func NewFileLogger(logPath string,logger logging.Logger) Logger {
func NewFileLogger(logPath string) Logger {
return Logger{
log: logger,
logPath: logPath,
}
}
func (l *Logger) LogMessage(msg twitch.Message) {
func (l *Logger) LogMessage(msg twitch.Message) error {
year := msg.Timestamp.Year()
month := msg.Timestamp.Month()
channel := strings.Replace(msg.Channel, "#", "", 1)
err := os.MkdirAll(fmt.Sprintf(l.logPath+"%s/%d/%s/", channel, year, month), 0755)
if err != nil {
l.log.Error(err.Error())
return
return err
}
filename := fmt.Sprintf(l.logPath+"%s/%d/%s/%s.txt", channel, year, month, msg.User.Username)
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
l.log.Error(err.Error())
return err
}
defer file.Close()
contents := fmt.Sprintf("[%s] %s: %s\r\n", msg.Timestamp.Format("2006-01-2 15:04:05"), msg.User.Username, msg.Text)
if _, err = file.WriteString(contents); err != nil {
l.log.Error(err.Error())
return err
}
return nil
}

View file

@ -4,3 +4,7 @@ import:
version: ^1.0.0
- package: gopkg.in/redis.v5
version: ^5.2.9
- package: github.com/stretchr/testify
version: ^1.1.4
- package: github.com/labstack/echo
version: ^3.1.0-rc.1

24
main.go
View file

@ -14,11 +14,12 @@ import (
"github.com/gempir/gempbotgo/command"
"github.com/gempir/gempbotgo/filelog"
"github.com/gempir/gempbotgo/api"
"github.com/gempir/gempbotgo/combo"
)
var (
cfg config
Log logging.Logger
cfg config
logger logging.Logger
)
type config struct {
@ -35,11 +36,11 @@ type config struct {
func main() {
startTime := time.Now()
Log = initLogger()
logger = initLogger()
var err error
cfg, err = readConfig("config.json")
if err != nil {
Log.Fatal(err)
logger.Fatal(err)
}
rClient := redis.NewClient(&redis.Options{
@ -48,22 +49,23 @@ func main() {
DB: cfg.RedisDatabase,
})
apiServer := api.NewServer(cfg.APIPort, cfg.LogPath, Log)
apiServer := api.NewServer(cfg.APIPort, cfg.LogPath)
go apiServer.Init()
bot := twitch.NewBot(cfg.IrcAddress, cfg.IrcUser, cfg.IrcToken, Log, *rClient)
bot := twitch.NewBot(cfg.IrcAddress, cfg.IrcUser, cfg.IrcToken, *rClient)
go bot.CreateConnection()
fileLogger := filelog.NewFileLogger(cfg.LogPath, Log)
cmdHandler := command.NewHandler(cfg.Admin, bot, startTime, Log)
fileLogger := filelog.NewFileLogger(cfg.LogPath)
cmdHandler := command.NewHandler(cfg.Admin, bot, startTime, logger)
comboHandler := combo.NewHandler()
for msg := range bot.Messages {
fileLogger.LogMessage(msg)
go fileLogger.LogMessage(msg)
go comboHandler.HandleMessage(msg)
if strings.HasPrefix(msg.Text, "!") {
cmdHandler.HandleCommand(msg)
go cmdHandler.HandleCommand(msg)
}
}

30
main_test.go Normal file
View file

@ -0,0 +1,30 @@
package main
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCanInitLogger(t *testing.T) {
log := initLogger()
assert.Equal(t, "logging.Logger", reflect.TypeOf(log).String(), "logger has invalid type")
}
func TestCanReadConfig(t *testing.T) {
cfg, err := readConfig("config.example.json")
if err != nil {
t.Fatal("error reading config", err)
}
assert.Equal(t, "irc.chat.twitch.tv:6667", cfg.IrcAddress, "Invalid config data")
assert.Equal(t, "gempbot", cfg.IrcUser, "Invalid config data")
assert.Equal(t, "oauth:123123123", cfg.IrcToken, "Invalid config data")
assert.Equal(t, "gempir", cfg.Admin, "Invalid config data")
assert.Equal(t, "/var/twitch_logs/", cfg.LogPath, "Invalid config data")
assert.Equal(t, "8025", cfg.APIPort, "Invalid config data")
assert.Equal(t, "127.0.0.1:6379", cfg.RedisAddress, "Invalid config data")
assert.Equal(t, "asdasd", cfg.RedisPassword, "Invalid config data")
assert.Equal(t, int64(0), cfg.RedisDatabase, "Invalid config data")
}

View file

@ -3,7 +3,6 @@ package twitch
import (
"bufio"
"fmt"
"github.com/op/go-logging"
"net"
"net/textproto"
"regexp"
@ -16,7 +15,6 @@ type Bot struct {
ircAddress string
ircUser string
ircToken string
log logging.Logger
rClient redis.Client
}
@ -28,30 +26,26 @@ var (
actionReg2 = regexp.MustCompile(`([\x{0001}]+)`)
)
func NewBot(ircAddress string, ircUser string, ircToken string, logger logging.Logger, rClient redis.Client) Bot {
func NewBot(ircAddress string, ircUser string, ircToken string, rClient redis.Client) Bot {
return Bot{
Messages: make(chan Message),
ircAddress: ircAddress,
ircUser: strings.ToLower(ircUser),
ircToken: ircToken,
log: logger,
rClient: rClient,
}
}
func (bot *Bot) Say(text string, channel string) {
bot.log.Infof("PRIVMSG %s :%s", channel, text)
fmt.Fprintf(*mainConn, "PRIVMSG %s :%s\r\n", channel, text)
}
func (bot *Bot) CreateConnection() {
func (bot *Bot) CreateConnection() error {
conn, err := net.Dial("tcp", bot.ircAddress)
mainConn = &conn
if err != nil {
bot.log.Error(err.Error())
return
return err
}
bot.log.Debugf("new IRC connection %s", conn.RemoteAddr())
fmt.Fprintf(*mainConn, "PASS %s\r\n", bot.ircToken)
fmt.Fprintf(*mainConn, "NICK %s\r\n", bot.ircUser)
fmt.Fprint(*mainConn, "CAP REQ :twitch.tv/tags\r\n")
@ -65,8 +59,7 @@ func (bot *Bot) CreateConnection() {
for {
line, err := tp.ReadLine()
if err != nil {
bot.log.Error(err.Error())
break
return err
}
messages := strings.Split(line, "\r\n")
if len(messages) == 0 {
@ -77,13 +70,11 @@ func (bot *Bot) CreateConnection() {
}
}
defer bot.CreateConnection()
return nil
}
func (bot *Bot) joinDefault() {
val, err := bot.rClient.HGetAll("channels").Result()
if err != nil {
bot.log.Error(err.Error())
}
val,_ := bot.rClient.HGetAll("channels").Result()
for _, element := range val {
if element == "1" || element == "0" {
continue
@ -136,6 +127,5 @@ func (bot *Bot) parseMessage(msg string) {
}
func (bot *Bot) join(channel string) {
bot.log.Info("JOIN " + channel)
fmt.Fprintf(*mainConn, "JOIN %s\r\n", channel)
}