navidrome/server/events/events.go
Deluan Quintão 986000db44
chore(lint): enable errchkjson (#6486)
errchkjson flags json.Marshal/MarshalIndent/Encoder.Encode calls whose error is discarded.
Fixed all 27 sites by hand: errors are returned where the caller already returns one, logged
in HTTP handlers and string-returning helpers, and asserted in tests.
check-error-free-encoding stays off so every encode error is handled, even for safe types.
report-no-exported is on, to catch structs that would silently encode as {}.
2026-11-16 23:18:26 -05:00

98 lines
2.1 KiB
Go

package events
import (
"context"
"encoding/json"
"reflect"
"strings"
"time"
"unicode"
"github.com/navidrome/navidrome/log"
)
type eventCtxKey string
const broadcastToAllKey eventCtxKey = "broadcastToAll"
// broadcastToAll is a context key that can be used to broadcast an event to all clients
func broadcastToAll(ctx context.Context) context.Context {
return context.WithValue(ctx, broadcastToAllKey, true)
}
type Event interface {
Name(Event) string
Data(Event) string
}
type baseEvent struct{}
func (e *baseEvent) Name(evt Event) string {
str := strings.TrimPrefix(reflect.TypeOf(evt).String(), "*events.")
return str[:0] + string(unicode.ToLower(rune(str[0]))) + str[1:]
}
func (e *baseEvent) Data(evt Event) string {
data, err := json.Marshal(evt)
if err != nil {
log.Error("Error encoding event", "event", e.Name(evt), err)
}
return string(data)
}
type ScanStatus struct {
baseEvent
Scanning bool `json:"scanning"`
Count int64 `json:"count"`
FolderCount int64 `json:"folderCount"`
Error string `json:"error"`
ScanType string `json:"scanType"`
ElapsedTime time.Duration `json:"elapsedTime"`
}
type KeepAlive struct {
baseEvent
TS int64 `json:"ts"`
}
type ServerStart struct {
baseEvent
StartTime time.Time `json:"startTime"`
Version string `json:"version"`
}
const Any = "*"
type RefreshResource struct {
baseEvent
resources map[string][]string
}
type NowPlayingCount struct {
baseEvent
Count int `json:"count"`
}
func (rr *RefreshResource) With(resource string, ids ...string) *RefreshResource {
if rr.resources == nil {
rr.resources = make(map[string][]string)
}
if len(ids) == 0 {
rr.resources[resource] = append(rr.resources[resource], Any)
}
rr.resources[resource] = append(rr.resources[resource], ids...)
return rr
}
func (rr *RefreshResource) Data(evt Event) string {
if rr.resources == nil {
return `{"*":"*"}`
}
r := evt.(*RefreshResource)
data, err := json.Marshal(r.resources)
if err != nil {
log.Error("Error encoding refresh event", err)
}
return string(data)
}