refactor: minor lint fixes

This commit is contained in:
Ash Keel 2024-02-25 14:58:35 +01:00
parent fbb943f307
commit 82b7d51df7
No known key found for this signature in database
GPG Key ID: 53A9E9A6035DD109
15 changed files with 64 additions and 32 deletions

11
.dockerignore Normal file
View File

@ -0,0 +1,11 @@
*.exe
*.db
*.db.lock
/data/
/backups/
.vscode
.idea
strimertul_*
/build/bin/
*.log
api.json

12
.golangci.yml Normal file
View File

@ -0,0 +1,12 @@
linters:
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- revive
- errorlint
- errname
- contextcheck

3
app.go
View File

@ -34,7 +34,7 @@ import (
type App struct { type App struct {
ctx context.Context ctx context.Context
cliParams *cli.Context cliParams *cli.Context
driver database.DatabaseDriver driver database.Driver
ready *sync.RWSync[bool] ready *sync.RWSync[bool]
isFatalError *sync.RWSync[bool] isFatalError *sync.RWSync[bool]
backupOptions database.BackupOptions backupOptions database.BackupOptions
@ -269,6 +269,7 @@ func (a *App) SendCrashReport(errorData string, info string) (string, error) {
logger.Error("Could not send crash report", zap.Error(err)) logger.Error("Could not send crash report", zap.Error(err))
return "", err return "", err
} }
defer resp.Body.Close()
// Check the response // Check the response
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {

View File

@ -13,7 +13,7 @@ import (
"git.sr.ht/~ashkeel/strimertul/utils" "git.sr.ht/~ashkeel/strimertul/utils"
) )
func BackupTask(driver database.DatabaseDriver, options database.BackupOptions) { func BackupTask(driver database.Driver, options database.BackupOptions) {
if options.BackupDir == "" { if options.BackupDir == "" {
logger.Warn("Backup directory not set, database backups are disabled") logger.Warn("Backup directory not set, database backups are disabled")
return return
@ -34,7 +34,7 @@ func BackupTask(driver database.DatabaseDriver, options database.BackupOptions)
} }
} }
func performBackup(driver database.DatabaseDriver, options database.BackupOptions) { func performBackup(driver database.Driver, options database.BackupOptions) {
// Run backup procedure // Run backup procedure
file, err := os.Create(fmt.Sprintf("%s/%s.db", options.BackupDir, time.Now().Format("20060102-150405"))) file, err := os.Create(fmt.Sprintf("%s/%s.db", options.BackupDir, time.Now().Format("20060102-150405")))
if err != nil { if err != nil {

View File

@ -13,8 +13,8 @@ import (
"git.sr.ht/~ashkeel/strimertul/utils" "git.sr.ht/~ashkeel/strimertul/utils"
) )
// DatabaseDriver is a driver wrapping a supported database // Driver is a driver wrapping a supported database
type DatabaseDriver interface { type Driver interface {
Hub() *kv.Hub Hub() *kv.Hub
Close() error Close() error
Import(map[string]string) error Import(map[string]string) error
@ -46,7 +46,7 @@ func getDatabaseDriverName(ctx *cli.Context) string {
return string(file) return string(file)
} }
func GetDatabaseDriver(ctx *cli.Context) (DatabaseDriver, error) { func GetDatabaseDriver(ctx *cli.Context) (Driver, error) {
name := getDatabaseDriverName(ctx) name := getDatabaseDriverName(ctx)
dbDirectory := ctx.String("database-dir") dbDirectory := ctx.String("database-dir")
logger := ctx.Context.Value(utils.ContextLogger).(*zap.Logger) logger := ctx.Context.Value(utils.ContextLogger).(*zap.Logger)

View File

@ -32,7 +32,7 @@ func NewPrediction(teams []string, bettingTime time.Duration) *Prediction {
} }
} }
func (p *Prediction) AddBet(who string, teamId uint, amount uint64) error { func (p *Prediction) AddBet(who string, teamID uint, amount uint64) error {
_, ok := p.Bets[who] _, ok := p.Bets[who]
if ok { if ok {
return ErrPAlreadyBet return ErrPAlreadyBet
@ -40,7 +40,7 @@ func (p *Prediction) AddBet(who string, teamId uint, amount uint64) error {
p.Bets[who] = PredictionBet{ p.Bets[who] = PredictionBet{
Amount: amount, Amount: amount,
Team: teamId, Team: teamID,
} }
return nil return nil
} }

View File

@ -1,6 +1,7 @@
package loyalty package loyalty
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -233,14 +234,13 @@ func (m *Manager) cmdRedeemReward(bot *twitch.Bot, message irc.PrivateMessage) {
Reward: reward, Reward: reward,
RequestText: text, RequestText: text,
}); err != nil { }); err != nil {
switch err { if errors.Is(err, ErrRedeemInCooldown) {
case ErrRedeemInCooldown:
nextAvailable := m.GetRewardCooldown(reward.ID) nextAvailable := m.GetRewardCooldown(reward.ID)
bot.Client.Say(message.Channel, fmt.Sprintf("%s: That reward is in cooldown (available in %s)", message.User.DisplayName, bot.Client.Say(message.Channel, fmt.Sprintf("%s: That reward is in cooldown (available in %s)", message.User.DisplayName,
time.Until(nextAvailable).Truncate(time.Second))) time.Until(nextAvailable).Truncate(time.Second)))
default: return
m.logger.Error("Error while performing redeem", zap.Error(err))
} }
m.logger.Error("Error while performing redeem", zap.Error(err))
return return
} }

View File

@ -105,7 +105,7 @@ func main() {
ctx.Context = context.WithValue(ctx.Context, utils.ContextLogger, logger) ctx.Context = context.WithValue(ctx.Context, utils.ContextLogger, logger)
return nil return nil
}, },
After: func(ctx *cli.Context) error { After: func(_ *cli.Context) error {
if panicLog != nil { if panicLog != nil {
utils.Close(panicLog, logger) utils.Close(panicLog, logger)
} }

3
strimertul.bat Normal file
View File

@ -0,0 +1,3 @@
@echo off
CD /D %~dp0
C:\projects\strimertul\strimertul\build\bin\strimertul.exe

View File

@ -55,7 +55,7 @@ func SetupTimers(bot *Bot) *BotTimerModule {
// Fill messages with zero values // Fill messages with zero values
// (This can probably be done faster) // (This can probably be done faster)
for i := 0; i < AverageMessageWindow; i += 1 { for i := 0; i < AverageMessageWindow; i++ {
mod.messages.Push(0) mod.messages.Push(0)
} }

View File

@ -76,14 +76,14 @@ func (c *Client) connectWebsocket(url string, oldConnection *websocket.Conn, use
continue continue
} }
reconnectURL, err, done := c.processMessage(wsMessage, oldConnection, userClient) reconnectURL, done, err := c.processMessage(wsMessage, oldConnection, userClient)
if done { if done {
return reconnectURL, connection, err return reconnectURL, connection, err
} }
} }
} }
func (c *Client) processMessage(wsMessage EventSubWebsocketMessage, oldConnection *websocket.Conn, userClient *helix.Client) (string, error, bool) { func (c *Client) processMessage(wsMessage EventSubWebsocketMessage, oldConnection *websocket.Conn, userClient *helix.Client) (string, bool, error) {
switch wsMessage.Metadata.MessageType { switch wsMessage.Metadata.MessageType {
case "session_keepalive": case "session_keepalive":
// Nothing to do // Nothing to do
@ -94,7 +94,7 @@ func (c *Client) processMessage(wsMessage EventSubWebsocketMessage, oldConnectio
c.logger.Error("Error decoding EventSub welcome message", zap.String("message-type", wsMessage.Metadata.MessageType), zap.Error(err)) c.logger.Error("Error decoding EventSub welcome message", zap.String("message-type", wsMessage.Metadata.MessageType), zap.Error(err))
break break
} }
c.logger.Info("Connection to EventSub websocket established", zap.String("session-id", welcomeData.Session.Id)) c.logger.Info("Connection to EventSub websocket established", zap.String("session-id", welcomeData.Session.ID))
// We can only close the old connection once the new one has been established // We can only close the old connection once the new one has been established
if oldConnection != nil { if oldConnection != nil {
@ -102,7 +102,7 @@ func (c *Client) processMessage(wsMessage EventSubWebsocketMessage, oldConnectio
} }
// Add subscription to websocket session // Add subscription to websocket session
err = c.addSubscriptionsForSession(userClient, welcomeData.Session.Id) err = c.addSubscriptionsForSession(userClient, welcomeData.Session.ID)
if err != nil { if err != nil {
c.logger.Error("Could not add subscriptions", zap.Error(err)) c.logger.Error("Could not add subscriptions", zap.Error(err))
break break
@ -114,26 +114,26 @@ func (c *Client) processMessage(wsMessage EventSubWebsocketMessage, oldConnectio
c.logger.Error("Error decoding EventSub session reconnect parameters", zap.String("message-type", wsMessage.Metadata.MessageType), zap.Error(err)) c.logger.Error("Error decoding EventSub session reconnect parameters", zap.String("message-type", wsMessage.Metadata.MessageType), zap.Error(err))
break break
} }
c.logger.Info("EventSub websocket requested a reconnection", zap.String("session-id", reconnectData.Session.Id), zap.String("reconnect-url", reconnectData.Session.ReconnectUrl)) c.logger.Info("EventSub websocket requested a reconnection", zap.String("session-id", reconnectData.Session.ID), zap.String("reconnect-url", reconnectData.Session.ReconnectURL))
return reconnectData.Session.ReconnectUrl, nil, true return reconnectData.Session.ReconnectURL, true, nil
case "notification": case "notification":
go c.processEvent(wsMessage) go c.processEvent(wsMessage)
case "revocation": case "revocation":
// TODO idk what to do here // TODO idk what to do here
} }
return "", nil, false return "", false, nil
} }
func (c *Client) processEvent(message EventSubWebsocketMessage) { func (c *Client) processEvent(message EventSubWebsocketMessage) {
// Check if we processed this already // Check if we processed this already
if message.Metadata.MessageId != "" { if message.Metadata.MessageID != "" {
if c.eventCache.Contains(message.Metadata.MessageId) { if c.eventCache.Contains(message.Metadata.MessageID) {
c.logger.Debug("Received duplicate event, ignoring", zap.String("message-id", message.Metadata.MessageId)) c.logger.Debug("Received duplicate event, ignoring", zap.String("message-id", message.Metadata.MessageID))
return return
} }
} }
defer c.eventCache.Add(message.Metadata.MessageId, message.Metadata.MessageTimestamp) defer c.eventCache.Add(message.Metadata.MessageID, message.Metadata.MessageTimestamp)
// Decode data // Decode data
var notificationData NotificationMessagePayload var notificationData NotificationMessagePayload
@ -218,11 +218,11 @@ type EventSubWebsocketMessage struct {
type WelcomeMessagePayload struct { type WelcomeMessagePayload struct {
Session struct { Session struct {
Id string `json:"id"` ID string `json:"id"`
Status string `json:"status"` Status string `json:"status"`
ConnectedAt time.Time `json:"connected_at"` ConnectedAt time.Time `json:"connected_at"`
KeepaliveTimeoutSeconds int `json:"keepalive_timeout_seconds"` KeepaliveTimeoutSeconds int `json:"keepalive_timeout_seconds"`
ReconnectUrl string `json:"reconnect_url,omitempty"` ReconnectURL string `json:"reconnect_url,omitempty"`
} `json:"session"` } `json:"session"`
} }
@ -233,7 +233,7 @@ type NotificationMessagePayload struct {
} }
type EventSubMetadata struct { type EventSubMetadata struct {
MessageId string `json:"message_id"` MessageID string `json:"message_id"`
MessageType string `json:"message_type"` MessageType string `json:"message_type"`
MessageTimestamp time.Time `json:"message_timestamp"` MessageTimestamp time.Time `json:"message_timestamp"`
SubscriptionType string `json:"subscription_type"` SubscriptionType string `json:"subscription_type"`

View File

@ -244,9 +244,8 @@ func (c *Client) runStatusPoll() {
if err != nil { if err != nil {
c.logger.Error("Error checking stream status", zap.Error(err)) c.logger.Error("Error checking stream status", zap.Error(err))
return return
} else {
c.streamOnline.Set(len(status.Data.Streams) > 0)
} }
c.streamOnline.Set(len(status.Data.Streams) > 0)
err = c.db.PutJSON(StreamInfoKey, status.Data.Streams) err = c.db.PutJSON(StreamInfoKey, status.Data.Streams)
if err != nil { if err != nil {

View File

@ -140,7 +140,7 @@ func (s *WebServer) makeMux() *http.ServeMux {
func healthFunc(w http.ResponseWriter, _ *http.Request) { func healthFunc(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK") _, _ = fmt.Fprint(w, "OK")
} }
func (s *WebServer) RegisterRoute(route string, handler http.Handler) { func (s *WebServer) RegisterRoute(route string, handler http.Handler) {

View File

@ -67,6 +67,8 @@ func TestListen(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
t.Fatalf("Expected 200, got %d", resp.StatusCode) t.Fatalf("Expected 200, got %d", resp.StatusCode)
} }
@ -117,6 +119,8 @@ func TestCustomRoute(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
t.Fatalf("Expected 200, got %d", resp.StatusCode) t.Fatalf("Expected 200, got %d", resp.StatusCode)
} }
@ -137,6 +141,8 @@ func TestCustomRoute(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer resp.Body.Close()
if resp.StatusCode != 404 { if resp.StatusCode != 404 {
t.Fatalf("Expected 404, got %d", resp.StatusCode) t.Fatalf("Expected 404, got %d", resp.StatusCode)
} }

View File

@ -40,7 +40,7 @@ func (t *TestServer) Shutdown(_ context.Context) error {
} }
func (t *TestServer) Factory() ServerFactory { func (t *TestServer) Factory() ServerFactory {
return func(h http.Handler, addr string) (Server, error) { return func(h http.Handler, _ string) (Server, error) {
s := httptest.NewUnstartedServer(h) s := httptest.NewUnstartedServer(h)
t.server.Set(s) t.server.Set(s)
return t, nil return t, nil