diff --git a/.golangci.yml b/.golangci.yml index 2b3ccbdbb..dfc62cfae 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,6 +21,7 @@ linters: - ginkgolinter - gocritic - gocyclo + - godoclint - goprintffuncname - gosec - misspell @@ -136,6 +137,14 @@ linters: force-succeed: true force-tonot: true validate-async-intervals: true + godoclint: + # a doc comment that names another symbol (left behind by a move or a paste) is a bug + default: none + enable: + - start-with-name + options: + start-with-name: + include-unexported: true gocritic: disable-all: true enabled-checks: diff --git a/adapters/gotaglib/gotaglib.go b/adapters/gotaglib/gotaglib.go index 7ea98a442..4985dff75 100644 --- a/adapters/gotaglib/gotaglib.go +++ b/adapters/gotaglib/gotaglib.go @@ -246,7 +246,7 @@ func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string) } } -// These are the only roles we support, based on Picard's tag map: +// tiplMapping lists the only roles we support, based on Picard's tag map: // https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html var tiplMapping = map[string]string{ "arranger": "arranger", diff --git a/adapters/lastfm/agent.go b/adapters/lastfm/agent.go index 362801c80..7208c8852 100644 --- a/adapters/lastfm/agent.go +++ b/adapters/lastfm/agent.go @@ -243,8 +243,8 @@ var ( artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`) artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name - // Not a RetryLaterError on purpose: parking the agent would also stall its API-backed - // methods, which the page block does not affect. + // errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its + // API-backed methods, which the page block does not affect. errNoArtistPage = errors.New("no artist image in Last.fm page") ) diff --git a/cmd/root.go b/cmd/root.go index 3a2a29e6d..94217a9bc 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -449,6 +449,7 @@ func startPluginManager(ctx context.Context) func() error { } // TODO: Implement some struct tags to map flags to viper + func init() { cobra.OnInitialize(func() { conf.InitConfig(cfgFile, true) diff --git a/conf/configuration.go b/conf/configuration.go index 929491bd1..5bed45fac 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -728,7 +728,7 @@ func asWrittenInConfigFile(keys []string) []string { }) } -// Matches keys and section headers in all supported config formats. +// configFileKeyRx matches keys and section headers in all supported config formats. var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`) // configKeys maps every accepted option name, lowercased, to its canonical spelling, diff --git a/consts/consts.go b/consts/consts.go index 9ed5c95bd..0b3d6b2e5 100644 --- a/consts/consts.go +++ b/consts/consts.go @@ -212,13 +212,11 @@ var ( var HTTPUserAgent = "Navidrome/" + Version + " - https://github.com/navidrome" var ( - VariousArtists = "Various Artists" - // TODO This will be dynamic when using disambiguation - VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" - UnknownAlbum = "[Unknown Album]" - UnknownArtist = "[Unknown Artist]" - // TODO This will be dynamic when using disambiguation - UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) + VariousArtists = "Various Artists" + VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" // TODO This will be dynamic when using disambiguation + UnknownAlbum = "[Unknown Album]" + UnknownArtist = "[Unknown Artist]" + UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) // TODO This will be dynamic when using disambiguation VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377" ArtistJoiner = " • " diff --git a/consts/version.go b/consts/version.go index cde2449ed..7554404e9 100644 --- a/consts/version.go +++ b/consts/version.go @@ -6,7 +6,7 @@ import ( ) var ( - // This will be set in build time. If not, version will be set to "dev" + // gitTag will be set in build time. If not, version will be set to "dev" gitTag string gitSha string ) diff --git a/core/archiver.go b/core/archiver.go index 60eb44858..227161ce5 100644 --- a/core/archiver.go +++ b/core/archiver.go @@ -61,7 +61,7 @@ func (a *archiver) ZipArtist(ctx context.Context, id string, format string, bitr return a.zipAlbums(ctx, id, format, bitrate, out, filter, model.Artist{ID: id}.CoverArtID()) } -// rootArt, when set, is added to the archive root. +// zipAlbums writes the songs matching filters to out. rootArt, when set, is added to the archive root. func (a *archiver) zipAlbums(ctx context.Context, id string, format string, bitrate int, out io.Writer, filters squirrel.Sqlizer, rootArt model.ArtworkID) error { mfs, err := a.ds.MediaFile().GetAll(ctx, model.QueryOptions{Filters: filters, Sort: "album"}) if err != nil { @@ -112,8 +112,8 @@ func createZipWriter(out io.Writer, format string, bitrate int) *zip.Writer { return z } -// Tried in order; the first one whose values are distinct across the clashing albums wins. -// One album may have an empty value: it keeps the plain name, which the others can't clash with. +// albumDisambiguators are tried in order; the first one whose values are distinct across the clashing +// albums wins. One album may have an empty value: it keeps the plain name, which the others can't clash with. var albumDisambiguators = []func(model.MediaFile) string{ func(mf model.MediaFile) string { return mf.Tags.First(model.TagAlbumVersion) }, func(mf model.MediaFile) string { @@ -346,7 +346,7 @@ func (a *archiver) readCoverArt(ctx context.Context, artID model.ArtworkID) ([]b return io.ReadAll(img) } -// Resizing may re-encode the image, so the type comes from its bytes. +// coverArtExtension takes the type from the image bytes, because resizing may re-encode the image. func coverArtExtension(data []byte) string { switch http.DetectContentType(data) { case "image/jpeg": diff --git a/core/artwork/disc.go b/core/artwork/disc.go index a050f6685..3d183bb93 100644 --- a/core/artwork/disc.go +++ b/core/artwork/disc.go @@ -200,7 +200,7 @@ func (d *discArtworkReader) fromDiscSubtitle(ctx context.Context, subtitle strin } } -// filepath.Match's '\' escape is excluded on purpose: treating it as a metachar +// globMetaChars excludes filepath.Match's '\' escape on purpose: treating it as a metachar // would misalign the literal-prefix extraction in extractDiscNumber. const globMetaChars = "*?[" diff --git a/core/artwork/dominant/dominant.go b/core/artwork/dominant/dominant.go index 2bbda8ae9..16547ea92 100644 --- a/core/artwork/dominant/dominant.go +++ b/core/artwork/dominant/dominant.go @@ -10,14 +10,14 @@ import ( ) const ( - // 4 bits per channel: coarse enough that near-identical pixels land together, fine enough that + // bits per channel: 4 is coarse enough that near-identical pixels land together, fine enough that // distinct colours stay apart. bits = 4 nBins = 1 << (3 * bits) - // Only the heaviest bins can win, and merging is O(n^2) over whatever survives. + // maxBins caps the bins kept: only the heaviest can win, and merging is O(n^2) over whatever survives. maxBins = 64 - // Oklab distance below which two bins are the same colour to the eye. Merging matters because a - // gradient splits across adjacent bins and would otherwise lose to a smaller flat region. + // mergeDist is the Oklab distance below which two bins are the same colour to the eye. Merging matters + // because a gradient splits across adjacent bins and would otherwise lose to a smaller flat region. mergeDist = 0.10 ) diff --git a/core/artwork/resolve.go b/core/artwork/resolve.go index cd58514d4..680ab391d 100644 --- a/core/artwork/resolve.go +++ b/core/artwork/resolve.go @@ -180,8 +180,9 @@ func chainFetchesExternal(priority string) bool { return false } -// Album and artist fetches stop here when the resolver is local-only, rather than at each point in -// the chain walk; resolvePlaylist gates the third network path, the m3u image URL, itself. +// fetchExternalAlbum and fetchExternalArtist are where album and artist fetches stop when the resolver is +// local-only, rather than at each point in the chain walk; resolvePlaylist gates the third network path, +// the m3u image URL, itself. func (r *resolver) fetchExternalAlbum(ctx context.Context, al model.Album) (io.ReadCloser, string, error) { if r.ext == nil { return nil, "", nil diff --git a/core/artwork/sources.go b/core/artwork/sources.go index daa084c16..2ebc5c49e 100644 --- a/core/artwork/sources.go +++ b/core/artwork/sources.go @@ -56,7 +56,7 @@ func fromExternalFile(ctx context.Context, libFS fs.FS, files []string, pattern } } -// These regexes are used to match the picture type in the file, in the order they are listed. +// picTypeRegexes match the picture type in the file, in the order they are listed. var picTypeRegexes = []*regexp.Regexp{ regexp.MustCompile(`(?i).*cover.*front.*|.*front.*cover.*`), regexp.MustCompile(`(?i).*front.*`), diff --git a/core/artwork/thumbhash/thumbhash.go b/core/artwork/thumbhash/thumbhash.go index a255bec42..513a5e5c1 100644 --- a/core/artwork/thumbhash/thumbhash.go +++ b/core/artwork/thumbhash/thumbhash.go @@ -230,7 +230,7 @@ func pack(w, h int, hasAlpha bool, lx, ly int, return hash } -// NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a +// toNRGBA returns NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a // premultiplied *image.RGBA, which draw.Draw un-premultiplies on the way in. func toNRGBA(img image.Image) *image.NRGBA { // Conservative: a sub-image re-slices Pix so the loops would read it correctly too, but the diff --git a/core/common.go b/core/common.go index db2dbbf1b..f6e93aa16 100644 --- a/core/common.go +++ b/core/common.go @@ -18,6 +18,7 @@ func userName(ctx context.Context) string { // BFR We should only access files through the `storage.Storage` interface. This will require changing how // TagLib and ffmpeg access files + var AbsolutePath = func(ctx context.Context, ds model.DataStore, libId int, path string) string { libPath, err := ds.Library().GetPath(ctx, libId) if err != nil { diff --git a/core/external/provider_similarsongs.go b/core/external/provider_similarsongs.go index 305b8d6ec..00fed9785 100644 --- a/core/external/provider_similarsongs.go +++ b/core/external/provider_similarsongs.go @@ -19,8 +19,8 @@ import ( const ( maxSeeds = 5 - // Subsonic passes the client's count through unbounded, and it ends up as a SQL limit. 500 is - // what the widest caller (similarAlbums, limit*5) legitimately asks for. + // maxSimilarSongs caps the client's count, which Subsonic passes through unbounded and ends up as a SQL + // limit. 500 is what the widest caller (similarAlbums, limit*5) legitimately asks for. maxSimilarSongs = 500 ) diff --git a/core/ffmpeg/ffmpeg.go b/core/ffmpeg/ffmpeg.go index f7d1708a9..4adb23f51 100644 --- a/core/ffmpeg/ffmpeg.go +++ b/core/ffmpeg/ffmpeg.go @@ -552,7 +552,7 @@ func bitDepthToSampleFmt(bitDepth int) string { } } -// Path will always be an absolute path +// createFFmpegCommand expects path to always be an absolute path func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string { var args []string for _, s := range fixCmd(cmd) { diff --git a/core/maintenance.go b/core/maintenance.go index 58265ea2c..c616a8399 100644 --- a/core/maintenance.go +++ b/core/maintenance.go @@ -310,9 +310,9 @@ func (s *maintenanceService) refreshStatsAsync(ctx context.Context, affectedAlbu }) } -// Wait waits for all background goroutines to complete. +// wait waits for all background goroutines to complete. // WARNING: This method is ONLY for testing. Never call this in production code. -// Calling Wait() in production will block until ALL background operations complete +// Calling wait() in production will block until ALL background operations complete // and may cause race conditions with new operations starting. func (s *maintenanceService) wait() { s.wg.Wait() diff --git a/core/metrics/prometheus.go b/core/metrics/prometheus.go index c8ab23b2a..b1932a09f 100644 --- a/core/metrics/prometheus.go +++ b/core/metrics/prometheus.go @@ -117,7 +117,7 @@ type prometheusMetrics struct { pluginRequestDuration *prometheus.SummaryVec } -// Prometheus' metrics requires initialization. But not more than once +// getPrometheusMetrics initializes Prometheus' metrics, which must not happen more than once var getPrometheusMetrics = sync.OnceValue(func() *prometheusMetrics { quartilesToEstimate := map[float64]float64{0.5: 0.05, 0.75: 0.025, 0.9: 0.01, 0.99: 0.001} diff --git a/core/playback/mpv/mpv.go b/core/playback/mpv/mpv.go index 2732edd38..3c0da60ad 100644 --- a/core/playback/mpv/mpv.go +++ b/core/playback/mpv/mpv.go @@ -72,7 +72,7 @@ func (j *Executor) wait() { _ = j.out.Close() } -// Path will always be an absolute path +// createMPVCommand expects filename to always be an absolute path func createMPVCommand(deviceName string, filename string, socketName string) []string { // Parse the template structure using shell parsing to handle quoted arguments templateArgs, err := shellquote.Split(conf.Server().MPVCmdTemplate) @@ -102,7 +102,7 @@ func createMPVCommand(deviceName string, filename string, socketName string) []s return templateArgs } -// This is a 1:1 copy of the stuff in ffmpeg.go, need to be unified. +// mpvCommand is a 1:1 copy of the stuff in ffmpeg.go, need to be unified. func mpvCommand() (string, error) { mpvOnce.Do(func() { if conf.Server().MPVPath != "" { diff --git a/core/playback/mpv/track.go b/core/playback/mpv/track.go index 1038b9190..8ee4ec094 100644 --- a/core/playback/mpv/track.go +++ b/core/playback/mpv/track.go @@ -76,7 +76,7 @@ func (t *MpvTrack) String() string { return fmt.Sprintf("Name: %s, Socket: %s", t.MediaFile.Path, t.IPCSocketName) } -// Used to control the playback volume. A float value between 0.0 and 1.0. +// SetVolume controls the playback volume. A float value between 0.0 and 1.0. func (t *MpvTrack) SetVolume(value float32) { // mpv's volume as described in the --volume parameter: // Set the startup volume. 0 means silence, 100 means no volume reduction or amplification. diff --git a/core/playback/queue.go b/core/playback/queue.go index 116db5fe6..4c04cab97 100644 --- a/core/playback/queue.go +++ b/core/playback/queue.go @@ -29,7 +29,7 @@ func (pd *Queue) String() string { return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames.String()) } -// returns the current mediafile or nil +// Current returns the current mediafile or nil func (pd *Queue) Current() *model.MediaFile { if pd.Index == -1 { return nil @@ -42,7 +42,7 @@ func (pd *Queue) Current() *model.MediaFile { return &pd.Items[pd.Index] } -// returns the whole queue +// Get returns the whole queue func (pd *Queue) Get() model.MediaFiles { return pd.Items } @@ -55,13 +55,13 @@ func (pd *Queue) IsEmpty() bool { return len(pd.Items) < 1 } -// set is similar to a clear followed by a add, but will not change the currently playing track. +// Set is similar to a clear followed by an add, but will not change the currently playing track. func (pd *Queue) Set(items model.MediaFiles) { pd.Clear() pd.Items = append(pd.Items, items...) } -// adding mediafiles to the queue +// Add appends mediafiles to the queue func (pd *Queue) Add(items model.MediaFiles) { pd.Items = append(pd.Items, items...) if pd.Index == -1 && len(pd.Items) > 0 { @@ -69,13 +69,13 @@ func (pd *Queue) Add(items model.MediaFiles) { } } -// empties whole queue +// Clear empties the whole queue func (pd *Queue) Clear() { pd.Index = -1 pd.Items = nil } -// idx Zero-based index of the song to skip to or remove. +// Remove removes the song at idx, a zero-based index. func (pd *Queue) Remove(idx int) { current := pd.Current() backupID := "" @@ -119,18 +119,18 @@ func (pd *Queue) getMediaFileIndexByID(id string) (int, error) { return -1, fmt.Errorf("ID not found in playlist: %s", id) } -// Sets the index to a new, valid value inside the Items. Values lower than zero are going to be zero, -// values above will be limited by number of items. +// SetIndex sets the index to a new, valid value inside the Items. Values lower than zero are going to be +// zero, values above will be limited by number of items. func (pd *Queue) SetIndex(idx int) { pd.Index = max(0, min(idx, len(pd.Items)-1)) } -// Are we at the last track? +// IsAtLastElement reports whether we are at the last track. func (pd *Queue) IsAtLastElement() bool { return (pd.Index + 1) >= len(pd.Items) } -// Goto next index +// IncreaseIndex moves to the next index, unless at the last track. func (pd *Queue) IncreaseIndex() { if !pd.IsAtLastElement() { pd.SetIndex(pd.Index + 1) diff --git a/core/quickconnect/quickconnect.go b/core/quickconnect/quickconnect.go index cd19e7e8f..f042b1a36 100644 --- a/core/quickconnect/quickconnect.go +++ b/core/quickconnect/quickconnect.go @@ -19,7 +19,7 @@ import ( const timeout = 10 * time.Minute -// Initiate is unauthenticated, so the number of live requests must be bounded. +// maxPending bounds the number of live requests, because Initiate is unauthenticated. const maxPending = 1000 var ( @@ -197,7 +197,7 @@ func newSecret() string { return hex.EncodeToString(b) } -// Users often type the code in groups ("123 456"). +// normalizeCode removes whitespace: users often type the code in groups ("123 456"). func normalizeCode(code string) string { return strings.Join(strings.Fields(code), "") } diff --git a/core/scrobbler/play_tracker.go b/core/scrobbler/play_tracker.go index 170ed2558..116fa7c7a 100644 --- a/core/scrobbler/play_tracker.go +++ b/core/scrobbler/play_tracker.go @@ -532,7 +532,7 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times }) } -// Take this verdict before incPlay mutates what a filter reads, and independently of +// isFilteredOut must take its verdict before incPlay mutates what a filter reads, and independently of // which scrobblers are active: it can be stored on a session and dispatched much later. // Any parse or query failure fails open, because filtering must not break scrobbling. func (p *playTracker) isFilteredOut(ctx context.Context, t *model.MediaFile) bool { diff --git a/db/db.go b/db/db.go index 5442b125c..fcaa57abe 100644 --- a/db/db.go +++ b/db/db.go @@ -34,8 +34,8 @@ var embedMigrations embed.FS const migrationsFolder = "migrations" -// sql.Register panics if called twice, so guard it: the singleton instance can be reset -// (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once. +// registerDriverOnce guards sql.Register, which panics if called twice: the singleton instance can be +// reset (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once. var registerDriverOnce sync.Once func Db() *sql.DB { diff --git a/db/migrations/20241026183640_support_new_scanner.go b/db/migrations/20241026183640_support_new_scanner.go index f5899f08f..9acba45b3 100644 --- a/db/migrations/20241026183640_support_new_scanner.go +++ b/db/migrations/20241026183640_support_new_scanner.go @@ -126,9 +126,10 @@ create index folder_parent_id on folder(parent_id); `) } -// Use paths from `media_file` table to populate `folder` table. The `folder` table must contain all paths, including -// the ones that do not contain any media_file. We can get all paths from the media_file table to populate a -// fstest.MapFS{}, and then walk the filesystem to insert all folders into the DB, including empty parent ones. +// upSupportNewScanner_PopulateTableFolder uses paths from `media_file` table to populate `folder` table. +// The `folder` table must contain all paths, including the ones that do not contain any media_file. We can +// get all paths from the media_file table to populate a fstest.MapFS{}, and then walk the filesystem to +// insert all folders into the DB, including empty parent ones. func upSupportNewScanner_PopulateTableFolder(ctx context.Context, tx *sql.Tx) execFunc { return func() error { // First, get all folder paths from media_file table diff --git a/db/migrations/20260702152457_backfill_artist_search_normalized.go b/db/migrations/20260702152457_backfill_artist_search_normalized.go index 93902e230..958af9b48 100644 --- a/db/migrations/20260702152457_backfill_artist_search_normalized.go +++ b/db/migrations/20260702152457_backfill_artist_search_normalized.go @@ -13,10 +13,10 @@ func init() { goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized) } -// The FTS5 migration back-filled artist.search_normalized with a SQL approximation that -// cannot transliterate atomic letters (Ø, æ, ß, ...), and the scanner never rewrote the -// column, leaving artists like "GØGGS" unfindable by ASCII searches. Recompute it in Go; -// the artist_fts update trigger re-indexes every row that changes. +// upBackfillArtistSearchNormalized recomputes artist.search_normalized in Go. The FTS5 migration +// back-filled it with a SQL approximation that cannot transliterate atomic letters (Ø, æ, ß, ...), +// and the scanner never rewrote the column, leaving artists like "GØGGS" unfindable by ASCII +// searches. The artist_fts update trigger re-indexes every row that changes. func upBackfillArtistSearchNormalized(ctx context.Context, tx *sql.Tx) error { notice(ctx, tx, "Rebuilding artist search index data. This may take a moment on large libraries.") diff --git a/db/migrations/migration.go b/db/migrations/migration.go index ffc944c39..a120e54fd 100644 --- a/db/migrations/migration.go +++ b/db/migrations/migration.go @@ -11,7 +11,8 @@ import ( "github.com/navidrome/navidrome/log" ) -// Use this in migrations that need to communicate something important (breaking changes, forced reindexes, etc...) +// notice is for migrations that need to communicate something important (breaking changes, forced +// reindexes, etc...) func notice(ctx context.Context, tx *sql.Tx, msg string) { if isDBInitialized(ctx, tx) { line := strings.Repeat("*", len(msg)+8) @@ -19,7 +20,7 @@ func notice(ctx context.Context, tx *sql.Tx, msg string) { } } -// Call this in migrations that requires a full rescan +// forceFullRescan is for migrations that require a full rescan func forceFullRescan(ctx context.Context, tx *sql.Tx) error { _, err := tx.ExecContext(ctx, fmt.Sprintf(` INSERT OR REPLACE into property (id, value) values ('%s', '1'); @@ -64,8 +65,8 @@ func createExecuteFunc(ctx context.Context, tx *sql.Tx) execStmtFunc { } } -// Hack way to add a new `not null` column to a table, setting the initial value for existing rows based on a -// SQL expression. It is done in 3 steps: +// createAddColumnFunc is a hack to add a new `not null` column to a table, setting the initial value for +// existing rows based on a SQL expression. It is done in 3 steps: // 1. Add the column as nullable. Due to the way SQLite manipulates the DDL in memory, we need to add extra padding // to the default value to avoid truncating it when changing the column to not null // 2. Update the column with the initial value diff --git a/db/optimize.go b/db/optimize.go index aff36e8fd..f2b3935a1 100644 --- a/db/optimize.go +++ b/db/optimize.go @@ -144,8 +144,9 @@ func optimizeAt(ctx context.Context, db *sql.DB, now time.Time) error { return nil } -// One ANALYZE per index (whole table if WITHOUT ROWID or lacking a non-partial index) yields the -// same sqlite_stat1 rows as a full ANALYZE, but frees the write lock between steps. +// analyzeTargetsSQL picks one ANALYZE target per index (whole table if WITHOUT ROWID or lacking a +// non-partial index). That yields the same sqlite_stat1 rows as a full ANALYZE, but frees the write lock +// between steps. const analyzeTargetsSQL = ` SELECT i.name FROM sqlite_schema i JOIN pragma_table_list t ON t.schema = 'main' AND t.name = i.tbl_name WHERE i.type = 'index' AND t.wr = 0 AND EXISTS (SELECT 1 FROM pragma_index_list(t.name) l WHERE l.partial = 0) diff --git a/model/artwork.go b/model/artwork.go index d5f62ab13..2233c6528 100644 --- a/model/artwork.go +++ b/model/artwork.go @@ -117,7 +117,8 @@ const ( ArtworkPriorityBump = 100 ) -// Delete* takes the rows to remove; Purge* finds them itself and reports how many went. +// ArtworkRepository stores the artwork images. Delete* takes the rows to remove; Purge* finds them itself +// and reports how many went. type ArtworkRepository interface { GetImage(ctx context.Context, hash string) (*Artwork, error) PutImage(ctx context.Context, a *Artwork) error diff --git a/model/criteria/operators.go b/model/criteria/operators.go index ec32f2d16..b72fcbe3d 100644 --- a/model/criteria/operators.go +++ b/model/criteria/operators.go @@ -1,6 +1,7 @@ package criteria -// Conjunctions need to implement this interface, to allow Criteria to extract child playlist references recursively +// conjunction must be implemented by Conjunctions, to allow Criteria to extract child playlist references +// recursively type conjunction interface { ChildPlaylistIds() []string ChildPlaylistPaths() []string diff --git a/model/get_entity.go b/model/get_entity.go index cfb3968ef..3ce53334d 100644 --- a/model/get_entity.go +++ b/model/get_entity.go @@ -6,6 +6,7 @@ import ( ) // TODO: Should the type be encoded in the ID? + func GetEntityByID(ctx context.Context, ds DataStore, id string) (any, error) { entity, _, err := getEntity(ctx, ds, id) return entity, err diff --git a/model/lyrics_lrc.go b/model/lyrics_lrc.go index e4b5b44b4..0592e14e5 100644 --- a/model/lyrics_lrc.go +++ b/model/lyrics_lrc.go @@ -12,22 +12,24 @@ import ( "github.com/navidrome/navidrome/utils/str" ) -// support the standard [mm:ss.mm], as well as [hh:*] and [*.mmm] +// timeRegexString supports the standard [mm:ss.mm], as well as [hh:*] and [*.mmm] const timeRegexString = `\[([0-9]{1,2}:)?([0-9]{1,2}):([0-9]{1,2})(\.[0-9]{1,3})?\]` var ( - // Should either be at the beginning of file, or beginning of line + // syncRegex only matches at the beginning of file, or beginning of line syncRegex = regexp.MustCompile(`(^|\n)\s*` + timeRegexString) timeRegex = regexp.MustCompile(timeRegexString) lrcIdRegex = regexp.MustCompile(`\[(ar|ti|offset|lang):([^]]+)]`) - // Non-standard background-vocal tag: [bg: word...] attaches to the preceding line + // bgTagRegex matches the non-standard background-vocal tag: [bg: word...] attaches to the + // preceding line bgTagRegex = regexp.MustCompile(`^\[bg:(.*)]$`) - // Any other [name:value] line is a tag we don't support (e.g. [al:], [by:]) and must be skipped whole + // unknownTagRegex matches any other [name:value] line, a tag we don't support (e.g. [al:], [by:]) that + // must be skipped whole unknownTagRegex = regexp.MustCompile(`^\[[A-Za-z][^]:]*:[^]]*]`) - // Enhanced LRC: inline word-level timing markers like <00:12.34> + // enhancedLRCTimeString matches Enhanced LRC inline word-level timing markers like <00:12.34> enhancedLRCTimeString = `<([0-9]{1,2}:)?([0-9]{1,2}):([0-9]{1,2})(\.[0-9]{1,3})?>` enhancedLRCRegex = regexp.MustCompile(enhancedLRCTimeString) ) diff --git a/model/metadata/metadata.go b/model/metadata/metadata.go index 91411a54e..68daab991 100644 --- a/model/metadata/metadata.go +++ b/model/metadata/metadata.go @@ -141,7 +141,7 @@ func nullableFloat(value string) *float64 { return &v } -// Used for tracks and discs +// tuple is used for tracks and discs func (md Metadata) tuple(key model.TagName) (int, int) { tag := md.first(key) if tag == "" { @@ -170,7 +170,7 @@ func (md Metadata) date(tagName model.TagName) Date { return Date(md.first(tagName)) } -// date tries to parse a date from a tag, it tries to get at least the year. See the tests for examples. +// parseDate tries to parse a date from a tag, it tries to get at least the year. See the tests for examples. func parseDate(filePath string, tagName model.TagName, tagValue string) string { if len(tagValue) < 4 { return "" diff --git a/model/metadata/persistent_ids.go b/model/metadata/persistent_ids.go index b66ce824a..62137b664 100644 --- a/model/metadata/persistent_ids.go +++ b/model/metadata/persistent_ids.go @@ -121,6 +121,7 @@ func (md Metadata) albumID(mf model.MediaFile, pidConf string) string { } // BFR Must be configurable? + func (md Metadata) artistID(name string) string { mf := model.MediaFile{AlbumArtist: name} return computePID(mf, md, "albumartistid", "", false, id.NewHash) diff --git a/model/playlist.go b/model/playlist.go index 210622ef8..7674edfc9 100644 --- a/model/playlist.go +++ b/model/playlist.go @@ -198,7 +198,8 @@ func normalizeChildPathRule(rule map[string]any, referencingPlaylistPath string) return normalized } -// filepath.IsAbs rejects a bare leading separator on Windows, but that is how Unix spells absolute. +// isAbsPlaylistRef also accepts a bare leading separator: filepath.IsAbs rejects it on Windows, but that is +// how Unix spells absolute. func isAbsPlaylistRef(path string) bool { return filepath.IsAbs(path) || os.IsPathSeparator(path[0]) } diff --git a/persistence/album_repository.go b/persistence/album_repository.go index e0bc6ae08..5a9d1b044 100644 --- a/persistence/album_repository.go +++ b/persistence/album_repository.go @@ -224,6 +224,7 @@ func (r *albumRepository) Put(ctx context.Context, al *model.Album) error { } // TODO Move external metadata to a separated table + func (r *albumRepository) UpdateExternalInfo(ctx context.Context, al *model.Album) error { _, err := r.put(ctx, al.ID, &dbAlbum{Album: al}, "description", "small_image_url", "medium_image_url", "large_image_url", "external_url", "external_info_updated_at") return err diff --git a/persistence/artwork_hydration.go b/persistence/artwork_hydration.go index b1640e2b7..5333ac172 100644 --- a/persistence/artwork_hydration.go +++ b/persistence/artwork_hydration.go @@ -12,8 +12,8 @@ import ( "github.com/pocketbase/dbx" ) -// Keeps the id IN-list under SQLite's bound-parameter limit; a whole multiple of artworkBatchSize -// so a page re-chunks into even hydration batches. +// artworkChunkSize keeps the id IN-list under SQLite's bound-parameter limit; a whole multiple of +// artworkBatchSize so a page re-chunks into even hydration batches. const artworkChunkSize = artworkBatchSize * 3 // streamByIDs yields rows in id chunks through the caller's hydrating fetch. Resolving ids first diff --git a/persistence/artwork_queue_repository.go b/persistence/artwork_queue_repository.go index 321fe8a95..9e66a4362 100644 --- a/persistence/artwork_queue_repository.go +++ b/persistence/artwork_queue_repository.go @@ -14,11 +14,11 @@ import ( "github.com/pocketbase/dbx" ) -// Keeps each multi-row insert under SQLite's bind-variable limit (at most 7 vars per row). +// enqueueChunkSize keeps each multi-row insert under SQLite's bind-variable limit (at most 7 vars per row). const enqueueChunkSize = 100 -// Every insert writes these, in this order; the INSERT..SELECT forms must project them to match. -// DequeueBatch also selects exactly these, to leave the drain's rows free of the trace it never reads. +// enqueueColumns are written by every insert, in this order; the INSERT..SELECT forms must project them to +// match. DequeueBatch also selects exactly these, to leave the drain's rows free of the trace it never reads. var enqueueColumns = []string{"item_kind", "item_id", "image_type", "priority", "attempts", "retry_at", "enqueued_at"} type artworkQueueRepository struct { @@ -92,7 +92,8 @@ func (r *artworkQueueRepository) EnqueueIfMissing(ctx context.Context, items ... return nil } -// DO NOTHING is deliberate: a recheck must not bump the priority or retry_at of an already-queued item. +// skipIfQueued uses DO NOTHING on purpose: a recheck must not bump the priority or retry_at of an +// already-queued item. const skipIfQueued = ` ON CONFLICT (item_kind, item_id, image_type) DO NOTHING` // insertIfNotQueued inserts the rows selected by the given SQL, optionally prefixed by a CTE. diff --git a/persistence/criteria_sql.go b/persistence/criteria_sql.go index fb40e097b..0c5c3cba8 100644 --- a/persistence/criteria_sql.go +++ b/persistence/criteria_sql.go @@ -378,7 +378,7 @@ func (c smartPlaylistCriteria) inList(values map[string]any, negate bool) (squir return squirrel.Expr("media_file.id IN ("+subSQL+")", subArgs...), nil } -// Filesystems disagree on the Unicode form of a name, so match the path in NFC and NFD. +// pathVariants returns the path in NFC and NFD, because filesystems disagree on the Unicode form of a name. func pathVariants(path string) []string { variants := []string{path} if alt := norm.NFC.String(path); alt != path { diff --git a/persistence/helpers.go b/persistence/helpers.go index 4e3d2e543..c83de9888 100644 --- a/persistence/helpers.go +++ b/persistence/helpers.go @@ -93,7 +93,7 @@ func naturalSort(col string) string { return fmt.Sprintf("(%s collate %s)", col, db.NaturalCollation) } -// Convert the order_* columns to a collated sort expression, falling back to the +// mapSortOrder converts the order_* columns to a collated sort expression, falling back to the // sort_* column when those are preferred. Example: // order_album_name -> (coalesce(nullif(sort_album_name,”),order_album_name) collate nocase) // It finds order column names anywhere in the substring diff --git a/persistence/library_repository.go b/persistence/library_repository.go index b51e6bcac..f4b079c6d 100644 --- a/persistence/library_repository.go +++ b/persistence/library_repository.go @@ -133,8 +133,8 @@ ON CONFLICT (user_id, library_id) DO NOTHING;`, return nil } +// StoreMusicFolder is a temporary method to store the music folder path from the config in the DB // TODO Remove this method when we have a proper UI to add libraries -// This is a temporary method to store the music folder path from the config in the DB func (r *libraryRepository) StoreMusicFolder(ctx context.Context) error { changed := And{Eq{"id": model.DefaultLibraryID}, NotEq{"path": conf.Server().MusicFolder}} // An UPDATE takes the write lock even when nothing matches, and a startup scan may be holding it diff --git a/persistence/persistence.go b/persistence/persistence.go index 44e944bff..53a2ad5d2 100644 --- a/persistence/persistence.go +++ b/persistence/persistence.go @@ -39,7 +39,8 @@ type SQLStore struct { artworkQueue func() model.ArtworkQueueRepository } -// Repositories are built on first use, so a transaction store only pays for the ones its block touches. +// newSQLStore builds repositories on first use, so a transaction store only pays for the ones its block +// touches. func newSQLStore(db dbx.Builder) *SQLStore { return &SQLStore{ db: db, diff --git a/persistence/player_repository.go b/persistence/player_repository.go index ba5d26794..ac6e26fd5 100644 --- a/persistence/player_repository.go +++ b/persistence/player_repository.go @@ -191,7 +191,8 @@ func (r *playerRepository) Delete(ctx context.Context, ids ...string) error { return r.deleteOwnedAll(ctx, ids...) } -// Keys are long random strings, not user-chosen passwords, so a fast unsalted hash is enough and keeps lookups indexed. +// hashAPIKey uses a fast unsalted hash: keys are long random strings, not user-chosen passwords, so that is +// enough and keeps lookups indexed. func hashAPIKey(key string) string { sum := sha256.Sum256([]byte(key)) return hex.EncodeToString(sum[:]) diff --git a/persistence/smart_playlist_repository.go b/persistence/smart_playlist_repository.go index 0e46fd732..3326bb51b 100644 --- a/persistence/smart_playlist_repository.go +++ b/persistence/smart_playlist_repository.go @@ -23,7 +23,8 @@ func (r *playlistRepository) refreshSmartPlaylist(ctx context.Context, pls *mode return r.refreshSmartPlaylistTree(ctx, pls, map[string]struct{}{}) } -// The visited set stops playlists that reference each other from recursing forever. +// refreshSmartPlaylistTree uses the visited set to stop playlists that reference each other from +// recursing forever. func (r *playlistRepository) refreshSmartPlaylistTree(ctx context.Context, pls *model.Playlist, visited map[string]struct{}) bool { if _, seen := visited[pls.ID]; seen { log.Trace(ctx, "Skipping already visited smart playlist", "playlist", pls.Name, "id", pls.ID) diff --git a/persistence/sql_base_repository.go b/persistence/sql_base_repository.go index eb6ba3518..98d4c01c3 100644 --- a/persistence/sql_base_repository.go +++ b/persistence/sql_base_repository.go @@ -169,6 +169,7 @@ func (r sqlRepository) applyOptions(sq SelectBuilder, options ...model.QueryOpti } // TODO Change all sortMappings to have a consistent case + func (r sqlRepository) sortMapping(sort string) string { if mapping, _, ok := r.lookupSortMapping(sort); ok { return mapping diff --git a/persistence/sql_tags.go b/persistence/sql_tags.go index 45c4d44af..169b7c447 100644 --- a/persistence/sql_tags.go +++ b/persistence/sql_tags.go @@ -12,7 +12,7 @@ import ( "github.com/pocketbase/dbx" ) -// Format of a tag in the DB +// dbTag is the format of a tag in the DB type dbTag struct { ID string `json:"id"` Value string `json:"value"` diff --git a/persistence/user_repository.go b/persistence/user_repository.go index b7b70119f..fb624f0d4 100644 --- a/persistence/user_repository.go +++ b/persistence/user_repository.go @@ -449,7 +449,7 @@ func (r *userRepository) initPasswordEncryptionKey(ctx context.Context) error { return nil } -// encrypts u.NewPassword +// encryptPassword encrypts u.NewPassword func (r *userRepository) encryptPassword(ctx context.Context, u *model.User) error { encPassword, err := utils.Encrypt(ctx, encKey, u.NewPassword) if err != nil { @@ -460,7 +460,7 @@ func (r *userRepository) encryptPassword(ctx context.Context, u *model.User) err return nil } -// decrypts u.Password +// decryptPassword decrypts u.Password func (r *userRepository) decryptPassword(ctx context.Context, u *model.User) error { plaintext, err := utils.Decrypt(ctx, encKey, u.Password) if err != nil { diff --git a/scanner/walk_dir_tree.go b/scanner/walk_dir_tree.go index e2d4d5e64..d588c2130 100644 --- a/scanner/walk_dir_tree.go +++ b/scanner/walk_dir_tree.go @@ -310,7 +310,7 @@ func isDirReadable(ctx context.Context, fsys fs.FS, dirPath string) bool { return true } -// List of special directories to ignore +// ignoredDirs lists special directories to ignore var ignoredDirs = []string{ "$RECYCLE.BIN", "#snapshot", diff --git a/server/apiv1/api.go b/server/apiv1/api.go index a39fe8509..dcc270d8f 100644 --- a/server/apiv1/api.go +++ b/server/apiv1/api.go @@ -67,7 +67,8 @@ func problemRecoverer(next http.Handler) http.Handler { var routableMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} -// Looks routes up on mux itself: chi's RouteContext().Routes points at the parent router when mounted. +// allowedMethods looks routes up on mux itself: chi's RouteContext().Routes points at the parent router +// when mounted. func allowedMethods(mux chi.Routes, req *http.Request) []string { path := routePath(req) var allowed []string diff --git a/server/events/sse.go b/server/events/sse.go index e8b75d5ee..9fc133741 100644 --- a/server/events/sse.go +++ b/server/events/sse.go @@ -24,7 +24,8 @@ type Broker interface { const ( keepAliveFrequency = 15 * time.Second - // The timeout must be higher than the keepAliveFrequency, or the lack of activity will cause the channel to close. + // writeTimeOut must be higher than the keepAliveFrequency, or the lack of activity will cause the channel + // to close. writeTimeOut = keepAliveFrequency + 5*time.Second bufferSize = 1 ) diff --git a/server/initial_setup.go b/server/initial_setup.go index 06f69b8db..72b89deb7 100644 --- a/server/initial_setup.go +++ b/server/initial_setup.go @@ -14,7 +14,8 @@ import ( "github.com/navidrome/navidrome/model/id" ) -// Keeps reads out of the transaction: SQLite fails a write that follows a read at once, without waiting for the lock +// initialSetup keeps reads out of the transaction: SQLite fails a write that follows a read at once, +// without waiting for the lock func initialSetup(ctx context.Context, ds model.DataStore) error { if err := ds.Library().StoreMusicFolder(ctx); err != nil { return err @@ -33,7 +34,7 @@ func initialSetup(ctx context.Context, ds model.DataStore) error { }, "initial setup") } -// If the Dev Admin user is not present, create it +// createInitialAdminUser creates the Dev Admin user if it is not present func createInitialAdminUser(ctx context.Context, ds model.DataStore, initialPassword string) error { users := ds.User() c, err := users.CountAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"user_name": consts.DevInitialUserName}}) diff --git a/server/jellyfin/discovery.go b/server/jellyfin/discovery.go index 9bcf6bda4..95d99fb3c 100644 --- a/server/jellyfin/discovery.go +++ b/server/jellyfin/discovery.go @@ -89,7 +89,8 @@ func (d *Discovery) ServeOn(ctx context.Context, conn net.PacketConn) { } } -// Behind a unix socket nothing listens on Port, so only a BaseURL host gives clients an address. +// hasAdvertisableAddress is false behind a unix socket with no BaseURL host: nothing listens on Port +// there, so only a BaseURL host gives clients an address. func hasAdvertisableAddress() bool { return conf.Server().BaseHost != "" || !strings.HasPrefix(conf.Server().Address, "unix:") } @@ -100,7 +101,8 @@ func discoveryAddress(ctx context.Context, remote net.Addr) string { return publicurl.AbsoluteURL(request.WithServerAddress(ctx, scheme, host), consts.URLPathJellyfinAPI, nil) } -// On a multi-homed host, only the interface that routes to the requester is reachable by it. +// localIPFor returns the configured Address when it is a specific IP. Otherwise it picks the interface that +// routes to the requester, since on a multi-homed host only that one is reachable by it. func localIPFor(remote net.Addr) string { if ip := parseIP(conf.Server().Address); ip.IsValid() && !ip.IsUnspecified() { return ip.String() diff --git a/server/jellyfin/dto/mappers.go b/server/jellyfin/dto/mappers.go index 242e89456..4b210f3fb 100644 --- a/server/jellyfin/dto/mappers.go +++ b/server/jellyfin/dto/mappers.go @@ -21,7 +21,7 @@ func sortName(sortTag, orderName, displayName string) string { return cmp.Or(orderName, displayName) } -// Jellyfin wire times are ticks: 100ns units, i.e. 10,000 per millisecond. +// ticksPerMillis converts Jellyfin wire times, which are ticks: 100ns units, i.e. 10,000 per millisecond. const ticksPerMillis = 10_000 func TicksFromSeconds(sec float32) int64 { return int64(float64(sec) * 1000 * ticksPerMillis) } @@ -56,7 +56,7 @@ func premiereDate(date string, year int) *string { return &s } -// Dates use .NET's round-trip layout, 7 fractional digits and all: Manet rejects plain RFC3339. +// jellyfinDateLayout is .NET's round-trip layout, 7 fractional digits and all: Manet rejects plain RFC3339. const jellyfinDateLayout = "2006-01-02T15:04:05.0000000Z07:00" // JellyfinDate formats t as the date string clients expect, or "" for the zero time so the diff --git a/server/jellyfin/playlists.go b/server/jellyfin/playlists.go index 20375f19e..34bf895cb 100644 --- a/server/jellyfin/playlists.go +++ b/server/jellyfin/playlists.go @@ -371,8 +371,9 @@ func (api *Router) movePlaylistItem(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } -// Clients probe these before offering edits. Navidrome has no per-playlist ACL, so CanEdit carries -// only editability; ownership is enforced on write, and a lookup error 404s to prevent probing. +// getPlaylistUsers answers the probe clients make before offering edits. Navidrome has no per-playlist +// ACL, so CanEdit carries only editability; ownership is enforced on write, and a lookup error 404s to +// prevent probing. func (api *Router) getPlaylistUsers(w http.ResponseWriter, r *http.Request) { ctx := r.Context() id, ok := itemIDParam(w, r, "playlistId") diff --git a/server/jellyfin/quickconnect.go b/server/jellyfin/quickconnect.go index b56fa9df3..2c9df9b22 100644 --- a/server/jellyfin/quickconnect.go +++ b/server/jellyfin/quickconnect.go @@ -27,7 +27,8 @@ func (api *Router) quickConnectEnabled(w http.ResponseWriter, r *http.Request) { api.ok(w, r, conf.Server().Jellyfin.QuickConnect) } -// Initiate is unauthenticated and its fields are kept for minutes, so their size must be bounded. +// maxQuickConnectField bounds the field size: Initiate is unauthenticated and its fields are kept for +// minutes. const maxQuickConnectField = 512 func (api *Router) quickConnectInitiate(w http.ResponseWriter, r *http.Request) { diff --git a/server/jellyfin/similar.go b/server/jellyfin/similar.go index 50503160c..62ac747a1 100644 --- a/server/jellyfin/similar.go +++ b/server/jellyfin/similar.go @@ -23,8 +23,8 @@ var similarWait = 10 * time.Second const ( defaultSimilarLimit = 20 maxSimilarLimit = 100 - // A mix is a playback queue, not a "related items" list: Finamp's Radio Mix asks for 250, so the - // Similar ceiling would truncate it. Real Jellyfin builds mixes from a 200-track genre query. + // maxInstantMixLimit is above the Similar ceiling: a mix is a playback queue, not a "related items" + // list, and Finamp's Radio Mix asks for 250. Real Jellyfin builds mixes from a 200-track genre query. maxInstantMixLimit = 500 ) diff --git a/server/jellyfin/system.go b/server/jellyfin/system.go index 360d1595f..b54f56a7a 100644 --- a/server/jellyfin/system.go +++ b/server/jellyfin/system.go @@ -36,11 +36,12 @@ func (api *Router) serverID(ctx context.Context) string { return resolveServerID(ctx, api.ds, &api.serverIDVal) } -// Package-level: the Router and Discovery are separate objects and must not persist different ids. +// serverIDMu is package-level: the Router and Discovery are separate objects and must not persist +// different ids. var serverIDMu sync.Mutex -// Clients cache ServerId across sessions, so it is persisted. Only a successful read or write is -// cached: a transient failure yields a temporary id and retries on the next call. +// resolveServerID persists the ServerId, because clients cache it across sessions. Only a successful read +// or write is cached: a transient failure yields a temporary id and retries on the next call. func resolveServerID(ctx context.Context, ds model.DataStore, cached *string) string { serverIDMu.Lock() defer serverIDMu.Unlock() diff --git a/server/nativeapi/library.go b/server/nativeapi/library.go index f6ecab3e3..68aaa41a6 100644 --- a/server/nativeapi/library.go +++ b/server/nativeapi/library.go @@ -12,7 +12,7 @@ import ( "github.com/navidrome/navidrome/model" ) -// User-library association endpoints (admin only) +// addUserLibraryRoute adds the user-library association endpoints (admin only) func (api *Router) addUserLibraryRoute(r chi.Router) { r.Route("/user/{id}/library", func(r chi.Router) { r.Use(parseUserIDMiddleware) @@ -23,7 +23,7 @@ func (api *Router) addUserLibraryRoute(r chi.Router) { type userIDKey struct{} -// Middleware to parse user ID from URL +// parseUserIDMiddleware parses the user ID from the URL func parseUserIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { userID := chi.URLParam(r, "id") diff --git a/server/nativeapi/native_api.go b/server/nativeapi/native_api.go index 2ee026ea0..438bc23c6 100644 --- a/server/nativeapi/native_api.go +++ b/server/nativeapi/native_api.go @@ -247,7 +247,7 @@ func (api *Router) addInsightsRoute(r chi.Router) { }) } -// Middleware to ensure only admin users can access endpoints +// adminOnlyMiddleware ensures only admin users can access endpoints func adminOnlyMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, ok := request.UserFrom(r.Context()) diff --git a/server/nativeapi/plugin.go b/server/nativeapi/plugin.go index 736fcdb01..72fd58684 100644 --- a/server/nativeapi/plugin.go +++ b/server/nativeapi/plugin.go @@ -41,7 +41,7 @@ func (api *Router) rescanPlugins(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// Middleware to check if plugins feature is enabled +// pluginsEnabledMiddleware checks if the plugins feature is enabled func pluginsEnabledMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !conf.Server().Plugins.Enabled { diff --git a/server/serve_index.go b/server/serve_index.go index 4552a76ec..f6b49dbb5 100644 --- a/server/serve_index.go +++ b/server/serve_index.go @@ -29,7 +29,7 @@ func IndexWithShare(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.H return serveIndex(ds, fs, shareInfo) } -// Injects the config in the `index.html` template +// serveIndex injects the config in the `index.html` template func serveIndex(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { c, err := ds.User().CountAll(r.Context()) diff --git a/server/server.go b/server/server.go index 7d37aae76..b05e06588 100644 --- a/server/server.go +++ b/server/server.go @@ -222,7 +222,7 @@ func (s *Server) mountAuthenticationRoutes() chi.Router { }) } -// Serve UI app assets +// mountRootRedirector redirects the root path to the UI app func (s *Server) mountRootRedirector() { r := s.router // Redirect root to UI URL diff --git a/server/subsonic/api.go b/server/subsonic/api.go index b2c2d31c8..8f33930bc 100644 --- a/server/subsonic/api.go +++ b/server/subsonic/api.go @@ -239,14 +239,14 @@ func (api *Router) routes() http.Handler { return r } -// Add a Subsonic handler +// h adds a Subsonic handler func h(r chi.Router, path string, f handler) { hr(r, path, func(_ http.ResponseWriter, r *http.Request) (*responses.Subsonic, error) { return f(r) }) } -// Add a Subsonic handler that requires an http.ResponseWriter (ex: stream, getCoverArt...) +// hr adds a Subsonic handler that requires an http.ResponseWriter (ex: stream, getCoverArt...) func hr(r chi.Router, path string, f handlerRaw) { handle := func(w http.ResponseWriter, r *http.Request) { res, err := f(w, r) @@ -267,7 +267,8 @@ func hr(r chi.Router, path string, f handlerRaw) { addHandler(r, path, handle) } -// Add a handler that returns 501 - Not implemented. Used to signal that an endpoint is not implemented yet +// h501 adds a handler that returns 501 - Not implemented. Used to signal that an endpoint is not +// implemented yet func h501(r chi.Router, paths ...string) { for _, path := range paths { handle := func(w http.ResponseWriter, r *http.Request) { @@ -279,7 +280,7 @@ func h501(r chi.Router, paths ...string) { } } -// Add a handler that returns 410 - Gone. Used to signal that an endpoint will not be implemented +// h410 adds a handler that returns 410 - Gone. Used to signal that an endpoint will not be implemented func h410(r chi.Router, paths ...string) { for _, path := range paths { handle := func(w http.ResponseWriter, r *http.Request) { diff --git a/server/subsonic/transcode.go b/server/subsonic/transcode.go index 7a011a616..44ff2ec72 100644 --- a/server/subsonic/transcode.go +++ b/server/subsonic/transcode.go @@ -170,7 +170,7 @@ func (r *clientInfoRequest) validate() error { return nil } -// Only support songs for now +// validMediaTypes only supports songs for now var validMediaTypes = []string{ "song", } diff --git a/tests/dns_stub.go b/tests/dns_stub.go index 7cd7faf6d..1104ff071 100644 --- a/tests/dns_stub.go +++ b/tests/dns_stub.go @@ -23,7 +23,8 @@ func StubResolver(records map[string]string) *net.Resolver { } } -// net.Pipe is not a PacketConn, so the resolver sends one query framed with a 2-byte length prefix. +// serveStubDNS answers one query. net.Pipe is not a PacketConn, so the resolver sends it framed with a +// 2-byte length prefix. func serveStubDNS(conn net.Conn, records map[string]string) { defer conn.Close() var size [2]byte diff --git a/tests/mock_mediafile_repo.go b/tests/mock_mediafile_repo.go index 392a4d8e0..954587b92 100644 --- a/tests/mock_mediafile_repo.go +++ b/tests/mock_mediafile_repo.go @@ -307,6 +307,7 @@ func (m *MockMediaFileRepo) DeleteAllMissing(_ context.Context) (int64, error) { } // REST repository methods + func (m *MockMediaFileRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) { return m.CountAll(ctx) } @@ -331,6 +332,7 @@ func (m *MockMediaFileRepo) Search(ctx context.Context, q string, options ...mod } // Cross-library move detection mock methods + func (m *MockMediaFileRepo) FindRecentFilesByMBZTrackID(_ context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) { if m.Err { return nil, errors.New("error") diff --git a/tests/mock_plugin_repo.go b/tests/mock_plugin_repo.go index feaf9b212..9a14bde91 100644 --- a/tests/mock_plugin_repo.go +++ b/tests/mock_plugin_repo.go @@ -151,6 +151,7 @@ func (m *MockPluginRepo) CountAll(_ context.Context, qo ...model.QueryOptions) ( } // REST repository methods + func (m *MockPluginRepo) Count(_ context.Context, _ ...rest.QueryOptions) (int64, error) { if !m.Permitted { return 0, rest.ErrPermissionDenied diff --git a/utils/slice/slice.go b/utils/slice/slice.go index e3677e754..90a147653 100644 --- a/utils/slice/slice.go +++ b/utils/slice/slice.go @@ -142,7 +142,7 @@ func LinesFrom(reader io.Reader) iter.Seq[string] { } } -// From https://stackoverflow.com/a/41433698 +// scanLines is based on https://stackoverflow.com/a/41433698 func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil