mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-18 07:30:29 +00:00
* refactor(persistence): adopt generic deluan/rest repository API Pin deluan/rest to the refactor branch. REST-facing repository methods take a context and return typed values. Drop DataStore.Resource and ResourceRepository; the native API names typed repositories directly through a per-request adapter that later commits remove. * refactor(persistence): base repository helpers take a context * refactor(persistence): LibraryRepository takes a context per call * refactor(persistence): PropertyRepository takes a context per call * refactor(persistence): UserPropsRepository takes a context per call * refactor(persistence): TranscodingRepository takes a context per call * refactor(persistence): ShareRepository takes a context per call * refactor(persistence): PlayerRepository takes a context per call * refactor(persistence): RadioRepository takes a context per call * refactor(persistence): PlayQueueRepository takes a context per call * refactor(persistence): Tag and Genre repositories take a context per call * refactor(persistence): PluginRepository takes a context per call * refactor(persistence): Scrobble repositories take a context per call * refactor(persistence): FolderRepository takes a context per call * refactor(persistence): Artwork repositories take a context per call * refactor(persistence): UserRepository takes a context per call * refactor(persistence): ArtistRepository takes a context per call ReadAll no longer rewrites the shared sort mappings for the role filter; it works on a per-call copy. * test(persistence): assert artist role sort sanitization in ReadAll * refactor(persistence): AlbumRepository takes a context per call * test(persistence): pass the test context to album repository helpers * refactor(persistence): MediaFileRepository takes a context per call * refactor(persistence): Playlist repositories take a context per call * refactor(persistence): build all repositories once per store * refactor(core): REST repository wrappers are built once * refactor(persistence): repositories are stateless Remove the context field from the base repository and the per-request REST adapter. Enable the containedctx linter so no repository can hold a request context again. * chore(lint): skip containedctx in test files * refactor: share simplifications from the stateless repositories sweep Add deleteOwnedAll on sqlRepository and use it in player/share Delete to remove the duplicated bulk-delete loop; have Share.Repository() return model.ShareRepository so subsonic sharing.go drops its repeated type assertions. * chore(core): assert REST wrappers implement Persistable * chore: reformat imports * perf(persistence): build repositories on first use Each transaction store used to construct all 21 repositories up front, paying for filter and sort mapping setup the block never touched. Fields are now sync.OnceValue thunks, so a store only builds what it uses. * fix(persistence): clean plugin references per deleted user A bulk user delete that fails on a later id had already removed the earlier rows but skipped their plugin cleanup. Cleanup now runs right after each successful delete. * fix(core): unload disabled plugins even when a user delete fails A bulk delete can fail on a later id after earlier users were removed and their plugins auto-disabled. The wrapper returned before unloading, leaving those plugins running until the next successful delete or a restart. * chore(deps): pin deluan/rest to v1.0.1 Replaces the pseudo-version of the refactor branch with the tagged release. REST error messages now name the bare type (Artist, not model.Artist). * test: use the spec context instead of context.Background() Replace the context.Background()/context.TODO() calls this branch added to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so repository calls are bound to the running spec's lifetime. * test: declare the spec context once per Describe Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
226 lines
6.9 KiB
Go
226 lines
6.9 KiB
Go
package playlists
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/id"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/navidrome/navidrome/utils/ioutils"
|
|
"github.com/zeebo/xxh3"
|
|
"golang.org/x/text/unicode/norm"
|
|
)
|
|
|
|
func (s *playlists) ImportFile(ctx context.Context, absolutePath string, sync bool) (*model.Playlist, error) {
|
|
absPath, err := filepath.Abs(absolutePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolving absolute path: %w", err)
|
|
}
|
|
|
|
dir := filepath.Dir(absPath)
|
|
filename := filepath.Base(absPath)
|
|
|
|
folder, err := s.resolveFolder(ctx, dir)
|
|
if err != nil && !errors.Is(err, errNotInLibrary) {
|
|
return nil, err
|
|
}
|
|
if err == nil {
|
|
pls, err := s.importFromFolder(ctx, folder, filename, sync)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if pls.ID != "" && pls.Sync != sync {
|
|
pls.Sync = sync
|
|
if putErr := s.ds.Playlist().Put(ctx, pls); putErr != nil {
|
|
return nil, putErr
|
|
}
|
|
}
|
|
return pls, nil
|
|
}
|
|
|
|
log.Debug(ctx, "Playlist file is outside all libraries, using path-based import", "path", absPath)
|
|
pls, err := s.newSyncedPlaylist(dir, filename)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading playlist file: %w", err)
|
|
}
|
|
pls.Sync = sync
|
|
|
|
file, err := os.Open(absPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("opening playlist file: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
hasher := xxh3.New()
|
|
reader := io.TeeReader(ioutils.UTF8Reader(file), hasher)
|
|
if err := s.parseM3U(ctx, pls, nil, reader); err != nil {
|
|
return nil, err
|
|
}
|
|
pls.ImportedHash = fingerprint(hasher)
|
|
if err := s.updatePlaylist(ctx, pls, sync); err != nil {
|
|
return nil, err
|
|
}
|
|
return pls, nil
|
|
}
|
|
|
|
var errNotInLibrary = fmt.Errorf("path not in any library")
|
|
|
|
func (s *playlists) resolveFolder(ctx context.Context, dir string) (*model.Folder, error) {
|
|
libs, err := s.ds.Library().GetAll(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
matcher := newLibraryMatcher(libs)
|
|
lib, ok := matcher.findLibrary(dir)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w: %s", errNotInLibrary, dir)
|
|
}
|
|
|
|
folder, err := s.ds.Folder().GetByPath(ctx, lib, dir)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolving folder for path %s: %w", dir, err)
|
|
}
|
|
folder.LibraryPath = lib.Path
|
|
return folder, nil
|
|
}
|
|
|
|
func (s *playlists) ImportFromFolder(ctx context.Context, folder *model.Folder, filename string) (*model.Playlist, error) {
|
|
return s.importFromFolder(ctx, folder, filename, false)
|
|
}
|
|
|
|
func (s *playlists) importFromFolder(ctx context.Context, folder *model.Folder, filename string, forceSync bool) (*model.Playlist, error) {
|
|
pls, err := s.parsePlaylist(ctx, filename, folder)
|
|
if err != nil {
|
|
log.Error(ctx, "Error parsing playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
|
|
return nil, err
|
|
}
|
|
log.Debug(ctx, "Found playlist", "name", pls.Name, "lastUpdated", pls.UpdatedAt, "path", pls.Path, "numTracks", len(pls.Tracks))
|
|
err = s.updatePlaylist(ctx, pls, forceSync)
|
|
if err != nil {
|
|
log.Error(ctx, "Error updating playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
|
|
}
|
|
return pls, err
|
|
}
|
|
|
|
func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error) {
|
|
owner, _ := request.UserFrom(ctx)
|
|
pls := &model.Playlist{
|
|
OwnerID: owner.ID,
|
|
Public: false,
|
|
Sync: false,
|
|
}
|
|
err := s.parseM3U(ctx, pls, nil, reader)
|
|
if err != nil {
|
|
log.Error(ctx, "Error parsing playlist", err)
|
|
return nil, err
|
|
}
|
|
err = s.ds.Playlist().Put(ctx, pls)
|
|
if err != nil {
|
|
log.Error(ctx, "Error saving playlist", err)
|
|
return nil, err
|
|
}
|
|
return pls, nil
|
|
}
|
|
|
|
func (s *playlists) parsePlaylist(ctx context.Context, playlistFile string, folder *model.Folder) (*model.Playlist, error) {
|
|
pls, err := s.newSyncedPlaylist(folder.AbsolutePath(), playlistFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
file, err := os.Open(pls.Path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
|
|
// Hash the bytes the parser consumes, giving every imported playlist a content fingerprint
|
|
hasher := xxh3.New()
|
|
reader := io.TeeReader(ioutils.UTF8Reader(file), hasher)
|
|
extension := strings.ToLower(filepath.Ext(playlistFile))
|
|
switch extension {
|
|
case ".nsp":
|
|
err = s.parseNSP(ctx, pls, reader)
|
|
default:
|
|
err = s.parseM3U(ctx, pls, folder, reader)
|
|
}
|
|
if err != nil {
|
|
return pls, err
|
|
}
|
|
pls.ImportedHash = fingerprint(hasher)
|
|
return pls, nil
|
|
}
|
|
|
|
func fingerprint(h *xxh3.Hasher) string {
|
|
return id.Encode(h.Sum128().Bytes())
|
|
}
|
|
|
|
// findByPathNormalized looks up a playlist by path, trying both NFC and NFD Unicode
|
|
// normalization forms to handle cross-platform filesystem differences.
|
|
func (s *playlists) findByPathNormalized(ctx context.Context, path string) (*model.Playlist, error) {
|
|
pls, err := s.ds.Playlist().FindByPath(ctx, path)
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
altPath := norm.NFD.String(path)
|
|
if altPath == path {
|
|
altPath = norm.NFC.String(path)
|
|
}
|
|
if altPath != path {
|
|
pls, err = s.ds.Playlist().FindByPath(ctx, altPath)
|
|
}
|
|
}
|
|
return pls, err
|
|
}
|
|
|
|
func (s *playlists) updatePlaylist(ctx context.Context, newPls *model.Playlist, forceSync bool) error {
|
|
owner, _ := request.UserFrom(ctx)
|
|
|
|
pls, err := s.findByPathNormalized(ctx, newPls.Path)
|
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
|
return err
|
|
}
|
|
alreadyImportedAndNotSynced := err == nil && !pls.Sync && !forceSync
|
|
if alreadyImportedAndNotSynced {
|
|
log.Debug(ctx, "Playlist already imported and not synced", "playlist", pls.Name, "path", pls.Path)
|
|
return nil
|
|
}
|
|
|
|
if err == nil {
|
|
// Only smart playlists skip on an unchanged file; M3U must re-run so newly-added tracks resolve.
|
|
if !forceSync && newPls.IsSmartPlaylist() && newPls.ImportedHash != "" && newPls.ImportedHash == pls.ImportedHash {
|
|
log.Trace(ctx, "Playlist file unchanged since last import, skipping", "playlist", pls.Name, "path", pls.Path)
|
|
*newPls = *pls // callers must see the stored record, so e.g. ImportFile can still flip Sync
|
|
return nil
|
|
}
|
|
log.Info(ctx, "Updating synced playlist", "playlist", pls.Name, "path", newPls.Path)
|
|
newPls.ID = pls.ID
|
|
newPls.Name = pls.Name
|
|
newPls.Comment = pls.Comment
|
|
newPls.OwnerID = pls.OwnerID
|
|
newPls.Public = pls.Public
|
|
newPls.UploadedImage = pls.UploadedImage // Preserve manual upload
|
|
newPls.EvaluatedAt = nil // force re-evaluation on next read
|
|
if newPls.IsSmartPlaylist() {
|
|
// Tracks aren't materialized at parse time; carry the stored counters so callers see real values
|
|
newPls.SongCount = pls.SongCount
|
|
newPls.Duration = pls.Duration
|
|
newPls.Size = pls.Size
|
|
}
|
|
} else {
|
|
log.Info(ctx, "Adding synced playlist", "playlist", newPls.Name, "path", newPls.Path, "owner", owner.UserName)
|
|
newPls.OwnerID = owner.ID
|
|
// For NSP files, Public may already be set from the file; for M3U, use server default
|
|
if !newPls.IsSmartPlaylist() {
|
|
newPls.Public = conf.Server.DefaultPlaylistPublicVisibility
|
|
}
|
|
}
|
|
return s.ds.Playlist().Put(ctx, newPls)
|
|
}
|