chore(lint): enable staticcheck (#6485)

Enforces the default staticcheck SA, S, ST and QF checks; fixed 76 sites (54 autofixed quick fixes, 22 by hand).
Dot imports are allowed only for squirrel, the established query builder style in persistence.
SA1019 is excluded for the deprecated plugins/types.SongRef wire fields the host still reads and writes for older plugins.
Also fixes an off-by-one in the redactrus test levelThreshold helper that panicked one level past TraceLevel.
This commit is contained in:
Deluan Quintão 2026-11-16 22:48:42 -05:00 committed by GitHub
parent 232a598e75
commit e9c0efa446
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
45 changed files with 132 additions and 113 deletions

View File

@ -26,11 +26,10 @@ linters:
- nilerr
- nolintlint
- rowserrcheck
- staticcheck
- unconvert
- usetesting
- whitespace
disable:
- staticcheck
settings:
depguard:
rules:
@ -153,6 +152,9 @@ linters:
govet:
enable:
- nilness
staticcheck:
dot-import-whitelist:
- github.com/Masterminds/squirrel
exclusions:
rules:
- linters:
@ -171,6 +173,11 @@ linters:
linters:
- forbidigo
text: "in tests use"
# the host must keep reading and writing these deprecated fields for older plugins
- path: ^plugins/
linters:
- staticcheck
text: 'SA1019: \(github\.com/navidrome/navidrome/plugins/types\.SongRef\)\.(Artist|ArtistMBID|Duration) is deprecated'
generated: lax
presets:
- comments

View File

@ -20,7 +20,7 @@ func (t testFileInfo) BirthTime() time.Time {
if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
return ts.BirthTime()
}
return t.FileInfo.ModTime()
return t.ModTime()
}
var _ = Describe("Extractor", func() {

View File

@ -50,11 +50,11 @@ func prettyMarshal(v any) ([]byte, error) {
out := v.([]core.InspectOutput)
var res strings.Builder
for i := range out {
res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File))
fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File)
t, _ := toml.Marshal(out[i].RawTags)
res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t))
fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t)
t, _ = toml.Marshal(out[i].MappedTags)
res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t))
fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t)
}
return []byte(res.String()), nil
}

View File

@ -17,7 +17,7 @@ import (
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/utils"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/slice"
"github.com/navidrome/navidrome/utils/str"
"golang.org/x/sync/errgroup"
@ -125,7 +125,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
return nil, err
}
updatedAt := V(album.ExternalInfoUpdatedAt)
updatedAt := gg.V(album.ExternalInfoUpdatedAt)
albumName := album.Name()
if updatedAt.IsZero() {
log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName)
@ -232,7 +232,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
}
// If we don't have any info, retrieves it now
updatedAt := V(artist.ExternalInfoUpdatedAt)
updatedAt := gg.V(artist.ExternalInfoUpdatedAt)
artistName := artist.Name()
if updatedAt.IsZero() {
log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName)

View File

@ -157,7 +157,7 @@ func (r *libraryRepositoryWrapper) Save(ctx context.Context, lib *model.Library)
return "", err
}
err := r.LibraryRepository.Put(ctx, lib)
err := r.Put(ctx, lib)
if err != nil {
return "", r.mapError(err)
}
@ -205,7 +205,7 @@ func (r *libraryRepositoryWrapper) Update(ctx context.Context, id string, entity
pidChanged := (updatesColumn(cols, "pidAlbum") && originalLib.PIDAlbum != lib.PIDAlbum) ||
(updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack)
err = r.LibraryRepository.Put(ctx, lib, cols...)
err = r.Put(ctx, lib, cols...)
if err != nil {
return r.mapError(err)
}

View File

@ -1565,7 +1565,7 @@ func (f *fakeScrobbler) PlaybackReport(ctx context.Context, info PlaybackSession
func _p(id, name string, sortName ...string) model.Participant {
p := model.Participant{ID: id, Name: name}
if len(sortName) > 0 {
p.Artist.SortArtistName = sortName[0]
p.SortArtistName = sortName[0]
}
return p
}

View File

@ -12,7 +12,7 @@ import (
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/nanoid"
"github.com/navidrome/navidrome/utils/slice"
"github.com/navidrome/navidrome/utils/str"
@ -41,7 +41,7 @@ func (s *shareService) Load(ctx context.Context, id string) (*model.Share, error
if err != nil {
return nil, err
}
expiresAt := V(share.ExpiresAt)
expiresAt := gg.V(share.ExpiresAt)
if !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
return nil, model.ErrExpired
}
@ -91,7 +91,7 @@ func (r *shareRepositoryWrapper) Save(ctx context.Context, s *model.Share) (stri
return "", err
}
s.ID = id
if V(s.ExpiresAt).IsZero() {
if gg.V(s.ExpiresAt).IsZero() {
s.ExpiresAt = new(time.Now().Add(conf.Server().DefaultShareExpiration))
}
@ -142,7 +142,7 @@ func (r *shareRepositoryWrapper) Update(ctx context.Context, id string, entity m
cols := []string{"description", "downloadable"}
// TODO Better handling of Share expiration
if !V(entity.ExpiresAt).IsZero() {
if !gg.V(entity.ExpiresAt).IsZero() {
cols = append(cols, "expires_at")
}
return r.ShareRepository.Update(ctx, id, entity, cols...)

View File

@ -54,7 +54,7 @@ type levelThresholdTest struct {
// above and including the level given. If the provided level does not exit,
// an empty slice is returned.
func levelThreshold(l logrus.Level) []logrus.Level {
if l < 0 || int(l) > len(logrus.AllLevels) {
if int(l) >= len(logrus.AllLevels) {
return []logrus.Level{}
}
return logrus.AllLevels[:l+1]
@ -68,6 +68,12 @@ func TestLevelThreshold(t *testing.T) {
expected: []logrus.Level{},
description: "An empty Level slice was expected but was not returned",
},
{
name: "levelPastLast",
level: logrus.Level(len(logrus.AllLevels)),
expected: []logrus.Level{},
description: "An empty Level slice was expected for the first level past TraceLevel",
},
{
name: "errorLogLevel",
level: logrus.ErrorLevel,

View File

@ -116,7 +116,7 @@ func isImageHash(s string) bool {
return false
}
for _, c := range s {
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return false
}
}

View File

@ -408,9 +408,10 @@ func parseTime(line string, match []int) (int64, error) {
length := msEnd - msStart
if length == 3 {
switch length {
case 3:
millis *= 10
} else if length == 2 {
case 2:
millis *= 100
}
}

View File

@ -524,9 +524,9 @@ func firstArtPath(currentPath string, currentDisc int, m MediaFile) (string, int
func (mfs MediaFiles) ToM3U8(title string, absolutePaths bool) string {
buf := strings.Builder{}
buf.WriteString("#EXTM3U\n")
buf.WriteString(fmt.Sprintf("#PLAYLIST:%s\n", title))
fmt.Fprintf(&buf, "#PLAYLIST:%s\n", title)
for _, t := range mfs {
buf.WriteString(fmt.Sprintf("#EXTINF:%.f,%s - %s\n", t.Duration, t.Artist, t.Title))
fmt.Fprintf(&buf, "#EXTINF:%.f,%s - %s\n", t.Duration, t.Artist, t.Title)
if absolutePaths {
buf.WriteString(t.AbsolutePath() + "\n")
} else {

View File

@ -31,5 +31,5 @@ func (t testFileInfo) BirthTime() time.Time {
if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
return ts.BirthTime()
}
return t.FileInfo.ModTime()
return t.ModTime()
}

View File

@ -208,7 +208,7 @@ var _ = Describe("ParticipantList", func() {
func _p(id, name string, sortName ...string) Participant {
p := Participant{ID: id, Name: name}
if len(sortName) > 0 {
p.Artist.SortArtistName = sortName[0]
p.SortArtistName = sortName[0]
}
return p
}

View File

@ -74,8 +74,8 @@ func (pls *Playlist) refreshStats() {
pls.Duration = 0
pls.Size = 0
for _, t := range pls.Tracks {
pls.Duration += t.MediaFile.Duration
pls.Size += t.MediaFile.Size
pls.Duration += t.Duration
pls.Size += t.Size
}
}

View File

@ -63,8 +63,8 @@ func (a *dbAlbum) PostScan() error {
}
a.Album.FolderIDs = ids
}
a.Album.RGAlbumGain = a.RgAlbumGain
a.Album.RGAlbumPeak = a.RgAlbumPeak
a.RGAlbumGain = a.RgAlbumGain
a.RGAlbumPeak = a.RgAlbumPeak
return nil
}

View File

@ -726,10 +726,10 @@ var _ = Describe("AlbumRepository", func() {
}
albums := dba.toModels()
for i := range dba {
Expect(albums[i].ID).To(Equal(dba[i].Album.ID))
Expect(albums[i].Name).To(Equal(dba[i].Album.Name))
Expect(albums[i].SongCount).To(Equal(dba[i].Album.SongCount))
Expect(albums[i].PlayCount).To(Equal(dba[i].Album.PlayCount))
Expect(albums[i].ID).To(Equal(dba[i].ID))
Expect(albums[i].Name).To(Equal(dba[i].Name))
Expect(albums[i].SongCount).To(Equal(dba[i].SongCount))
Expect(albums[i].PlayCount).To(Equal(dba[i].PlayCount))
}
})
})
@ -1315,7 +1315,7 @@ var _ = Describe("AlbumRepository", func() {
func _p(id, name string, sortName ...string) model.Participant {
p := model.Participant{ID: id, Name: name}
if len(sortName) > 0 {
p.Artist.SortArtistName = sortName[0]
p.SortArtistName = sortName[0]
}
return p
}

View File

@ -41,7 +41,7 @@ type dbSimilarArtist struct {
}
func (a *dbArtist) PostScan() error {
a.Artist.Stats = make(map[model.Role]model.ArtistStats)
a.Stats = make(map[model.Role]model.ArtistStats)
if a.LibraryStatsJSON != "" {
var rawLibStats map[string]map[string]map[string]int64
@ -61,9 +61,9 @@ func (a *dbArtist) PostScan() error {
// Store total stats into the main attributes
if key == "total" {
a.Artist.Size += artistStats.Size
a.Artist.SongCount += artistStats.SongCount
a.Artist.AlbumCount += artistStats.AlbumCount
a.Size += artistStats.Size
a.SongCount += artistStats.SongCount
a.AlbumCount += artistStats.AlbumCount
}
role := model.RoleFromString(key)
@ -71,11 +71,11 @@ func (a *dbArtist) PostScan() error {
continue
}
current := a.Artist.Stats[role]
current := a.Stats[role]
current.Size += artistStats.Size
current.SongCount += artistStats.SongCount
current.AlbumCount += artistStats.AlbumCount
a.Artist.Stats[role] = current
a.Stats[role] = current
}
}
}

View File

@ -131,10 +131,10 @@ var smartPlaylistFields = map[string]smartPlaylistField{
}
func (c smartPlaylistCriteria) where() (squirrel.Sqlizer, error) {
if c.Criteria.Expression == nil {
if c.Expression == nil {
return squirrel.Expr("1 = 1"), nil
}
return c.exprSQL(c.Criteria.Expression)
return c.exprSQL(c.Expression)
}
func (c smartPlaylistCriteria) exprSQL(expr criteria.Expression) (squirrel.Sqlizer, error) {
@ -805,7 +805,7 @@ func fieldJoinType(name string) smartPlaylistJoinType {
func (c smartPlaylistCriteria) expressionJoins() smartPlaylistJoinType {
var joins smartPlaylistJoinType
_ = criteria.Walk(c.Criteria.Expression, func(expr criteria.Expression) error {
_ = criteria.Walk(c.Expression, func(expr criteria.Expression) error {
for field := range criteria.Fields(expr) {
joins |= fieldJoinType(field)
}
@ -816,7 +816,7 @@ func (c smartPlaylistCriteria) expressionJoins() smartPlaylistJoinType {
func (c smartPlaylistCriteria) requiredJoins() smartPlaylistJoinType {
joins := c.expressionJoins()
for _, name := range c.Criteria.SortFieldNames() {
for _, name := range c.SortFieldNames() {
joins |= fieldJoinType(name)
}
return joins
@ -858,7 +858,7 @@ func (c smartPlaylistCriteria) applyJoins(sq squirrel.SelectBuilder, joins smart
}
func (c smartPlaylistCriteria) orderBy() string {
sortFields := c.Criteria.OrderByFields()
sortFields := c.OrderByFields()
parts := make([]string, 0, len(sortFields))
for _, sf := range sortFields {
mapped, ok := sortExpr(sf.Field)

View File

@ -55,7 +55,7 @@ var matchUnderscore = regexp.MustCompile("_([A-Za-z])")
func toCamelCase(str string) string {
return matchUnderscore.ReplaceAllStringFunc(str, func(s string) string {
return strings.ToUpper(strings.Replace(s, "_", "", -1))
return strings.ToUpper(strings.ReplaceAll(s, "_", ""))
})
}

View File

@ -35,7 +35,7 @@ func (p *dbPlaylist) PostScan() error {
func (p dbPlaylist) PostMapArgs(args map[string]any) error {
var err error
if p.Playlist.IsSmartPlaylist() {
if p.IsSmartPlaylist() {
args["rules"], err = json.Marshal(p.Playlist.Rules)
if err != nil {
return fmt.Errorf("invalid criteria expression: %w", err)

View File

@ -177,7 +177,7 @@ var _ = Describe("ScrobbleBufferRepository", func() {
Expect(entry.MediaFile.Participants).To(HaveLen(1))
artists, ok := entry.MediaFile.Participants[model.RoleArtist]
artists, ok := entry.Participants[model.RoleArtist]
Expect(ok).To(BeTrue(), "no artist role in participants")
Expect(artists).To(HaveLen(1))

View File

@ -195,8 +195,8 @@ func (r *playlistRepository) addCriteria(sql SelectBuilder, cSQL smartPlaylistCr
return sql, err
}
sql = sql.Where(cond)
if cSQL.Criteria.Limit > 0 {
sql = sql.Limit(uint64(cSQL.Criteria.Limit)).Offset(uint64(cSQL.Criteria.Offset))
if cSQL.Limit > 0 {
sql = sql.Limit(uint64(cSQL.Limit)).Offset(uint64(cSQL.Offset))
}
if order := cSQL.orderBy(); order != "" {
sql = sql.OrderBy(order)

View File

@ -35,7 +35,7 @@ type dbUser struct {
func (u *dbUser) PostScan() error {
if u.LibrariesJSON != "" {
if err := json.Unmarshal([]byte(u.LibrariesJSON), &u.User.Libraries); err != nil {
if err := json.Unmarshal([]byte(u.LibrariesJSON), &u.Libraries); err != nil {
return fmt.Errorf("parsing user libraries from db: %w", err)
}
}

View File

@ -625,6 +625,7 @@ var _ = Describe("newCacheService", func() {
}
Expect(runtime.NumGoroutine()).To(BeNumerically(">=", baseline+numServices),
"expected one janitor goroutine per cache service")
runtime.KeepAlive(services)
}()
Eventually(func() int { runtime.GC(); return runtime.NumGoroutine() }).

View File

@ -6,7 +6,7 @@ import (
"time"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/plugins/capabilities"
"github.com/navidrome/navidrome/plugins/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -344,7 +344,7 @@ var _ = Describe("MetadataAgent partial implementation", Ordered, func() {
var _ = Describe("songRefToAgentSong multi-artist", func() {
It("maps ArtistRef to agents.Artist", func() {
ref := capabilities.SongRef{Name: "Collab", Artist: "Drake", Artists: []capabilities.ArtistRef{
ref := types.SongRef{Name: "Collab", Artist: "Drake", Artists: []types.ArtistRef{
{ID: "id-drake", Name: "Drake", MBID: "m-drake"},
{Name: "Future", MBID: "m-future"},
}}
@ -355,17 +355,17 @@ var _ = Describe("songRefToAgentSong multi-artist", func() {
}))
})
It("folds the single Artist/ArtistMBID into a one-element Artists when no Artists provided", func() {
ref := capabilities.SongRef{Name: "Solo", Artist: "Drake", ArtistMBID: "m-drake"}
ref := types.SongRef{Name: "Solo", Artist: "Drake", ArtistMBID: "m-drake"}
got := songRefToAgentSong(ref)
Expect(got.Artists).To(Equal([]agents.Artist{{Name: "Drake", MBID: "m-drake"}}))
})
It("folds an MBID-only single artist (empty name) so the MBID is not dropped", func() {
ref := capabilities.SongRef{Name: "Solo", ArtistMBID: "m-drake"}
ref := types.SongRef{Name: "Solo", ArtistMBID: "m-drake"}
got := songRefToAgentSong(ref)
Expect(got.Artists).To(Equal([]agents.Artist{{MBID: "m-drake"}}))
})
It("leaves Artists nil when neither Artists nor the single Artist/ArtistMBID are provided", func() {
got := songRefToAgentSong(capabilities.SongRef{Name: "Anon"})
got := songRefToAgentSong(types.SongRef{Name: "Anon"})
Expect(got.Artists).To(BeNil())
})
})

View File

@ -1,6 +1,7 @@
package plugins
import (
"context"
"os"
"path/filepath"
"runtime"
@ -13,9 +14,11 @@ import (
)
var _ = Describe("buildMounts", func() {
var ctx context.Context
var libraries model.Libraries
BeforeEach(func() {
ctx = GinkgoT().Context()
libraries = model.Libraries{
{ID: 1, Path: "/music/library1"},
{ID: 2, Path: "/music/library2"},
@ -24,7 +27,7 @@ var _ = Describe("buildMounts", func() {
})
It("mounts all libraries read-only by default", func() {
Expect(buildMounts(nil, libraries, nil, true, false)).To(Equal([]mount{
Expect(buildMounts(ctx, libraries, nil, true, false)).To(Equal([]mount{
{hostPath: "/music/library1", guestPath: "/libraries/1", readOnly: true},
{hostPath: "/music/library2", guestPath: "/libraries/2", readOnly: true},
{hostPath: "/music/library3", guestPath: "/libraries/3", readOnly: true},
@ -32,21 +35,21 @@ var _ = Describe("buildMounts", func() {
})
It("mounts only the selected libraries", func() {
Expect(buildMounts(nil, libraries, []int{1, 3}, false, false)).To(Equal([]mount{
Expect(buildMounts(ctx, libraries, []int{1, 3}, false, false)).To(Equal([]mount{
{hostPath: "/music/library1", guestPath: "/libraries/1", readOnly: true},
{hostPath: "/music/library3", guestPath: "/libraries/3", readOnly: true},
}))
})
It("mounts writable when write access is granted", func() {
Expect(buildMounts(nil, libraries, []int{2}, false, true)).To(Equal([]mount{
Expect(buildMounts(ctx, libraries, []int{2}, false, true)).To(Equal([]mount{
{hostPath: "/music/library2", guestPath: "/libraries/2", readOnly: false},
}))
})
DescribeTable("mounts nothing",
func(libs model.Libraries, allowedIDs []int, allLibraries bool) {
Expect(buildMounts(nil, libs, allowedIDs, allLibraries, false)).To(BeEmpty())
Expect(buildMounts(ctx, libs, allowedIDs, allLibraries, false)).To(BeEmpty())
},
Entry("when no library matches", libraries, []int{99}, false),
Entry("when there are no libraries", model.Libraries(nil), []int{1}, false),

View File

@ -3,7 +3,7 @@ package plugins
import (
"github.com/navidrome/navidrome/core/sonic"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/plugins/capabilities"
"github.com/navidrome/navidrome/plugins/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -119,7 +119,7 @@ var _ = Describe("mediaFileToSongRef multi-artist", func() {
},
}}
ref := mediaFileToSongRef(mf)
Expect(ref.Artists).To(Equal([]capabilities.ArtistRef{
Expect(ref.Artists).To(Equal([]types.ArtistRef{
{ID: "ar-drake", Name: "Drake", MBID: "m-drake", Role: "artist"},
{ID: "ar-future", Name: "Future", MBID: "m-future", Role: "artist"},
}))

View File

@ -110,9 +110,10 @@ var _ = Describe("phaseMissingTracks", func() {
// Both PID A and PID B should be produced even without matches
var pidA, pidB *missingTracks
for _, p := range produced {
if p.pid == "A" {
switch p.pid {
case "A":
pidA = p
} else if p.pid == "B" {
case "B":
pidB = p
}
}

View File

@ -216,9 +216,10 @@ var _ = Describe("ScanFolders", Ordered, func() {
// Store track IDs for later verification
for _, t := range allTracks {
if t.Album == "Revolver" {
switch t.Album {
case "Revolver":
album1TrackIDs = append(album1TrackIDs, t.ID)
} else if t.Album == "Help!" {
case "Help!":
album2TrackIDs = append(album2TrackIDs, t.ID)
}
}
@ -322,9 +323,10 @@ var _ = Describe("ScanFolders", Ordered, func() {
Expect(allTracks).To(HaveLen(6))
for _, track := range allTracks {
if track.Album == "Help!" {
switch track.Album {
case "Help!":
Expect(track.Missing).To(BeTrue(), "All tracks in deleted Help! folder should be marked as missing")
} else if track.Album == "Revolver" {
case "Revolver":
Expect(track.Missing).To(BeFalse(), "Tracks in Revolver folder should not be marked as missing")
}
}

View File

@ -739,10 +739,7 @@ func (fd *fakeDirFile) ReadDir(int) ([]fs.DirEntry, error) {
fd.entries, _ = fd.File.(fs.ReadDirFile).ReadDir(-1)
}
var dirs []fs.DirEntry
for {
if fd.pos >= len(fd.entries) {
break
}
for fd.pos < len(fd.entries) {
e := fd.entries[fd.pos]
fd.pos++
if e.Name() == fd.fail {

View File

@ -258,7 +258,7 @@ func SongToBaseItem(mf model.MediaFile, fields Fields) BaseItemDto {
func embeddedArtPending(mf model.MediaFile) bool {
return mf.HasCoverArt && conf.Server().EnableMediaFileCoverArt &&
mf.ImageHash == "" && !mf.ItemImage.ImageAbsent
mf.ImageHash == "" && !mf.ImageAbsent
}
// primaryImage never fakes a blurhash: clients key their cover cache on the value, which would

View File

@ -552,8 +552,7 @@ var _ = Describe("mappers", func() {
})
It("falls back to the album once the track's art is known absent", func() {
mf := model.MediaFile{ID: testID("mf-3"), AlbumID: testID("alb-1"), HasCoverArt: true}
mf.ItemImage.ImageAbsent = true
mf := model.MediaFile{ID: testID("mf-3"), AlbumID: testID("alb-1"), HasCoverArt: true, ImageAbsent: true}
mf.AlbumImage.ImageHash = "0123456789abcdef"
item := SongToBaseItem(mf, nil)

View File

@ -72,7 +72,7 @@ func hashFromTag(r *http.Request) string {
return ""
}
for _, c := range tag {
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return ""
}
}

View File

@ -21,6 +21,8 @@ func (api *Router) addUserLibraryRoute(r chi.Router) {
})
}
type userIDKey struct{}
// Middleware to parse user ID from URL
func parseUserIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -29,7 +31,7 @@ func parseUserIDMiddleware(next http.Handler) http.Handler {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
ctx := context.WithValue(r.Context(), "userID", userID)
ctx := context.WithValue(r.Context(), userIDKey{}, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@ -38,7 +40,7 @@ func parseUserIDMiddleware(next http.Handler) http.Handler {
func getUserLibraries(service core.Library) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value("userID").(string)
userID := r.Context().Value(userIDKey{}).(string)
libraries, err := service.GetUserLibraries(r.Context(), userID)
if err != nil {
@ -60,7 +62,7 @@ func getUserLibraries(service core.Library) http.HandlerFunc {
func setUserLibraries(service core.Library) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value("userID").(string)
userID := r.Context().Value(userIDKey{}).(string)
var request struct {
LibraryIDs []int `json:"libraryIds"`

View File

@ -10,7 +10,7 @@ import (
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/slice"
)
@ -140,16 +140,16 @@ func saveQueue(ds model.DataStore) http.HandlerFunc {
return
}
user, client := extractUserAndClient(ctx)
ids := V(payload.Ids)
ids := gg.V(payload.Ids)
items := createMediaFileItems(ids)
current := V(payload.Current)
current := gg.V(payload.Current)
if len(ids) > 0 && !validateCurrentIndex(w, current, len(ids)) {
return
}
pq := &model.PlayQueue{
UserID: user.ID,
Current: current,
Position: max(V(payload.Position), 0),
Position: max(gg.V(payload.Position), 0),
ChangedBy: client,
Items: items,
}

View File

@ -14,7 +14,7 @@ import (
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/ui"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/req"
)
@ -120,6 +120,6 @@ func encodeMediafileShare(s model.Share, id string) string {
BitRate: s.MaxBitRate,
ShareID: s.ID,
}
token, _ := auth.CreateExpiringPublicToken(V(s.ExpiresAt), claims)
token, _ := auth.CreateExpiringPublicToken(gg.V(s.ExpiresAt), claims)
return token
}

View File

@ -11,7 +11,7 @@ import (
streampkg "github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/req"
)
@ -31,7 +31,7 @@ func (pub *Router) handleStream(w http.ResponseWriter, r *http.Request) {
checkShareError(ctx, w, err, info.shareID)
return
}
if expiresAt := V(share.ExpiresAt); !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
if expiresAt := gg.V(share.ExpiresAt); !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
checkShareError(ctx, w, model.ErrExpired, info.shareID)
return
}

View File

@ -324,14 +324,14 @@ func artistRefs(participants model.ParticipantList) []responses.ArtistID3Ref {
func fakePath(mf model.MediaFile) string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("%s/%s/", sanitizeSlashes(mf.AlbumArtist), sanitizeSlashes(mf.FullAlbumName())))
fmt.Fprintf(&builder, "%s/%s/", sanitizeSlashes(mf.AlbumArtist), sanitizeSlashes(mf.FullAlbumName()))
if mf.DiscNumber != 0 {
builder.WriteString(fmt.Sprintf("%02d-", mf.DiscNumber))
fmt.Fprintf(&builder, "%02d-", mf.DiscNumber)
}
if mf.TrackNumber != 0 {
builder.WriteString(fmt.Sprintf("%02d - ", mf.TrackNumber))
fmt.Fprintf(&builder, "%02d - ", mf.TrackNumber)
}
builder.WriteString(fmt.Sprintf("%s.%s", sanitizeSlashes(mf.FullTitle()), mf.Suffix))
fmt.Fprintf(&builder, "%s.%s", sanitizeSlashes(mf.FullTitle()), mf.Suffix)
return builder.String()
}

View File

@ -24,7 +24,7 @@ import (
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/server/subsonic/responses"
. "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/req"
)
@ -112,7 +112,7 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
username, isInternalAuth := fromInternalOrProxyAuth(r)
switch {
case username != "":
authType := If(isInternalAuth, "internal", "reverse-proxy")
authType := gg.If(isInternalAuth, "internal", "reverse-proxy")
usr, err = ds.User().FindByUsername(ctx, username)
if errors.Is(err, context.Canceled) {
log.Debug(ctx, "API: Request canceled when authenticating", "auth", authType, "username", username, "remoteAddr", r.RemoteAddr, err)

View File

@ -6,7 +6,6 @@ import (
"time"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/server/subsonic/responses"
. "github.com/navidrome/navidrome/server/subsonic/responses"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -546,12 +545,12 @@ var _ = Describe("Responses", func() {
CoverArt: "pl-123123123123",
Created: timestamp,
Changed: timestamp,
OpenSubsonicPlaylist: &responses.OpenSubsonicPlaylist{
OpenSubsonicPlaylist: &OpenSubsonicPlaylist{
Readonly: true,
ValidUntil: &timestamp,
},
}
pls[1] = Playlist{Id: "333", Name: "ccc", OpenSubsonicPlaylist: &responses.OpenSubsonicPlaylist{}}
pls[1] = Playlist{Id: "333", Name: "ccc", OpenSubsonicPlaylist: &OpenSubsonicPlaylist{}}
pls[2] = Playlist{Id: "222", Name: "bbb"}
response.Playlists.Playlist = pls
})

View File

@ -35,7 +35,7 @@ func (m *MockArtistRepo) SetData(artists model.Artists) {
func (m *MockArtistRepo) Exists(_ context.Context, id string) (bool, error) {
if m.Err {
return false, errors.New("Error!")
return false, errors.New("error")
}
_, found := m.Data[id]
return found, nil
@ -43,7 +43,7 @@ func (m *MockArtistRepo) Exists(_ context.Context, id string) (bool, error) {
func (m *MockArtistRepo) Get(_ context.Context, id string) (*model.Artist, error) {
if m.Err {
return nil, errors.New("Error!")
return nil, errors.New("error")
}
if d, ok := m.Data[id]; ok {
return d, nil

View File

@ -33,7 +33,7 @@ func (m *MockedRadioRepo) CountAll(_ context.Context, options ...model.QueryOpti
func (m *MockedRadioRepo) Delete(_ context.Context, ids ...string) error {
if m.Err {
return errors.New("Error!")
return errors.New("error")
}
for _, id := range ids {
if _, found := m.Data[id]; !found {
@ -46,7 +46,7 @@ func (m *MockedRadioRepo) Delete(_ context.Context, ids ...string) error {
func (m *MockedRadioRepo) Exists(_ context.Context, id string) (bool, error) {
if m.Err {
return false, errors.New("Error!")
return false, errors.New("error")
}
_, found := m.Data[id]
return found, nil
@ -54,7 +54,7 @@ func (m *MockedRadioRepo) Exists(_ context.Context, id string) (bool, error) {
func (m *MockedRadioRepo) Get(_ context.Context, id string) (*model.Radio, error) {
if m.Err {
return nil, errors.New("Error!")
return nil, errors.New("error")
}
if d, ok := m.Data[id]; ok {
return d, nil
@ -67,7 +67,7 @@ func (m *MockedRadioRepo) GetAll(_ context.Context, qo ...model.QueryOptions) (m
m.Options = qo[0]
}
if m.Err {
return nil, errors.New("Error!")
return nil, errors.New("error")
}
return m.All, nil
}

View File

@ -75,7 +75,7 @@ func (m *MockedScrobbleBufferRepo) Dequeue(_ context.Context, entry *model.Scrob
defer m.mu.Unlock()
newData := model.ScrobbleEntries{}
for _, e := range m.Data {
if e.Service == entry.Service && e.UserID == entry.UserID && e.PlayTime == entry.PlayTime && e.MediaFile.ID == entry.MediaFile.ID {
if e.Service == entry.Service && e.UserID == entry.UserID && e.PlayTime.Equal(entry.PlayTime) && e.MediaFile.ID == entry.MediaFile.ID {
continue
}
newData = append(newData, e)

View File

@ -114,12 +114,13 @@ func (cr *reader) Read(p []byte) (int, error) {
// Otherwise, consume and discard
case stateMaybeBlockEnd:
if b == '/' {
switch b {
case '/':
cr.state = stateNormal
} else if b == '*' {
case '*':
// Stay in stateMaybeBlockEnd (consecutive *'s)
cr.state = stateMaybeBlockEnd
} else {
default:
cr.state = stateBlockComment
}
}

View File

@ -33,8 +33,8 @@ func Split(input string) ([]string, error) {
switch parseState {
case stateUnquoted:
switch {
case ch == '\\':
switch ch {
case '\\':
if i+1 >= len(input) {
return nil, ErrUnterminatedEscape
}
@ -46,13 +46,13 @@ func Split(input string) ([]string, error) {
i++
word.WriteByte(input[i])
inWord = true
case ch == '\'':
case '\'':
parseState = stateSingleQuoted
inWord = true
case ch == '"':
case '"':
parseState = stateDoubleQuoted
inWord = true
case ch == ' ' || ch == '\t' || ch == '\n':
case ' ', '\t', '\n':
if inWord {
words = append(words, word.String())
word.Reset()
@ -71,10 +71,10 @@ func Split(input string) ([]string, error) {
}
case stateDoubleQuoted:
switch {
case ch == '"':
switch ch {
case '"':
parseState = stateUnquoted
case ch == '\\':
case '\\':
if i+1 >= len(input) {
return nil, ErrUnterminatedEscape
}