justlog/filelog/userlog.go

92 lines
1.9 KiB
Go
Raw Normal View History

2017-03-08 20:08:44 +01:00
package filelog
import (
2018-12-02 14:53:01 +01:00
"bufio"
"compress/gzip"
"errors"
2017-03-11 21:51:08 +01:00
"fmt"
2018-12-02 14:53:01 +01:00
"io"
"os"
2018-12-02 14:53:01 +01:00
"strings"
2017-09-11 19:51:29 +02:00
"github.com/gempir/go-twitch-irc"
2018-12-02 19:23:54 +01:00
log "github.com/sirupsen/logrus"
2017-03-08 20:08:44 +01:00
)
type Logger struct {
logPath string
}
2018-11-29 22:20:57 +01:00
func NewFileLogger(logPath string) Logger {
2017-03-08 20:08:44 +01:00
return Logger{
2018-11-29 22:20:57 +01:00
logPath: logPath,
2017-03-08 20:08:44 +01:00
}
}
func (l *Logger) LogMessageForUser(channel string, user twitch.User, message twitch.Message) error {
year := message.Time.Year()
2018-12-02 14:53:01 +01:00
month := int(message.Time.Month())
2018-12-07 22:59:58 +01:00
err := os.MkdirAll(fmt.Sprintf(l.logPath+"/%s/%d/%d/", message.Tags["room-id"], year, month), 0750)
2017-03-08 20:08:44 +01:00
if err != nil {
return err
2017-03-08 20:08:44 +01:00
}
2018-12-02 14:53:01 +01:00
filename := fmt.Sprintf(l.logPath+"/%s/%d/%d/%s.txt", message.Tags["room-id"], year, month, user.UserID)
2017-03-08 20:08:44 +01:00
2018-12-02 14:53:01 +01:00
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0640)
2017-03-08 20:08:44 +01:00
if err != nil {
return err
2017-03-08 20:08:44 +01:00
}
defer file.Close()
2018-12-05 22:41:31 +01:00
if _, err = file.WriteString(message.Raw + "\n"); err != nil {
return err
2017-03-08 20:08:44 +01:00
}
return nil
2017-03-11 11:06:50 +01:00
}
2018-12-02 14:53:01 +01:00
func (l *Logger) ReadLogForUser(channelID string, userID string, year int, month int) ([]string, error) {
2018-12-08 15:41:40 +01:00
if channelID == "" || userID == "" {
return []string{}, fmt.Errorf("Invalid channelID: %s or userID: %s", channelID, userID)
}
2018-12-02 14:53:01 +01:00
filename := fmt.Sprintf(l.logPath+"/%s/%d/%d/%s.txt", channelID, year, month, userID)
if _, err := os.Stat(filename); err != nil {
filename = filename + ".gz"
}
2018-12-02 19:23:54 +01:00
log.Debug("Opening " + filename)
2018-12-02 14:53:01 +01:00
f, err := os.Open(filename)
if err != nil {
2018-12-02 19:23:54 +01:00
return []string{}, errors.New("file not found: " + filename)
2018-12-02 14:53:01 +01:00
}
defer f.Close()
var reader io.Reader
if strings.HasSuffix(filename, ".gz") {
gz, err := gzip.NewReader(f)
if err != nil {
return []string{}, errors.New("file gzip not readable")
}
reader = gz
} else {
reader = f
}
scanner := bufio.NewScanner(reader)
if err != nil {
return []string{}, errors.New("file not readable")
}
content := []string{}
for scanner.Scan() {
line := scanner.Text()
content = append(content, line)
}
return content, nil
}