sonda/internal/library/libraries.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

157 lines
4.9 KiB
Go

package library
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"unicode/utf8"
)
// Errors returned by the Libraries service.
var (
ErrLibraryNotFound = errors.New("library not found")
ErrLibraryExists = errors.New("a library with this name or path already exists")
ErrInvalidLibrary = errors.New("invalid library")
)
const maxLibraryNameLen = 100
// Library is a named directory of music.
type Library struct {
ID int64
Name string
Path string // absolute directory
CreatedAt time.Time
}
// LibraryStore persists libraries.
type LibraryStore interface {
ListLibraries(ctx context.Context) ([]Library, error)
// GetLibrary returns ErrLibraryNotFound for an unknown id.
GetLibrary(ctx context.Context, id int64) (Library, error)
// CreateLibrary and UpdateLibrary return ErrLibraryExists when the name
// (case-insensitive) or the path is already used by another library.
CreateLibrary(ctx context.Context, name, path string) (Library, error)
UpdateLibrary(ctx context.Context, id int64, name, path string) (Library, error)
// DeleteLibrary removes the library and its indexed files, never the music
// on disk. It returns ErrLibraryNotFound for an unknown id.
DeleteLibrary(ctx context.Context, id int64) error
}
// Libraries manages the list of libraries and keeps it sane: every path is an
// absolute, existing directory, and no library sits inside or around another
// (that would index the same files twice).
type Libraries struct{ store LibraryStore }
// NewLibraries builds the service.
func NewLibraries(store LibraryStore) *Libraries { return &Libraries{store: store} }
// List returns every library.
func (s *Libraries) List(ctx context.Context) ([]Library, error) {
return s.store.ListLibraries(ctx)
}
// Create adds a library.
func (s *Libraries) Create(ctx context.Context, name, path string) (Library, error) {
name, path, err := s.validate(ctx, name, path, 0)
if err != nil {
return Library{}, err
}
return s.store.CreateLibrary(ctx, name, path)
}
// Update changes the name and/or the path of a library. A nil argument keeps
// the current value. Files keep their identity when the path changes.
func (s *Libraries) Update(ctx context.Context, id int64, name, path *string) (Library, error) {
cur, err := s.store.GetLibrary(ctx, id)
if err != nil {
return Library{}, err
}
newName, newPath := cur.Name, cur.Path
if name != nil {
newName = *name
}
if path != nil {
newPath = *path
}
newName, newPath, err = s.validate(ctx, newName, newPath, id)
if err != nil {
return Library{}, err
}
return s.store.UpdateLibrary(ctx, id, newName, newPath)
}
// Delete removes a library from the index. The music on disk is untouched.
func (s *Libraries) Delete(ctx context.Context, id int64) error {
return s.store.DeleteLibrary(ctx, id)
}
// validate checks a name and a path, ignoring the library skipID when it
// looks for overlaps. It returns the trimmed name and the cleaned path.
func (s *Libraries) validate(ctx context.Context, name, path string, skipID int64) (string, string, error) {
name = strings.TrimSpace(name)
if name == "" || utf8.RuneCountInString(name) > maxLibraryNameLen {
return "", "", fmt.Errorf("%w: name must be 1-%d characters", ErrInvalidLibrary, maxLibraryNameLen)
}
for _, r := range name {
if unicode.IsControl(r) {
return "", "", fmt.Errorf("%w: name has control characters", ErrInvalidLibrary)
}
}
if path == "" || !filepath.IsAbs(path) {
return "", "", fmt.Errorf("%w: path must be absolute", ErrInvalidLibrary)
}
path = filepath.Clean(path)
if filepath.Dir(path) == path {
return "", "", fmt.Errorf("%w: the filesystem root cannot be a library", ErrInvalidLibrary)
}
real, err := filepath.EvalSymlinks(path)
if errors.Is(err, fs.ErrNotExist) {
return "", "", fmt.Errorf("%w: directory does not exist", ErrInvalidLibrary)
}
if err != nil {
return "", "", fmt.Errorf("%w: cannot read the directory: %v", ErrInvalidLibrary, err)
}
info, err := os.Stat(real)
if err != nil || !info.IsDir() {
return "", "", fmt.Errorf("%w: path is not a directory", ErrInvalidLibrary)
}
others, err := s.store.ListLibraries(ctx)
if err != nil {
return "", "", fmt.Errorf("list libraries: %w", err)
}
for _, o := range others {
if o.ID == skipID {
continue
}
if o.Path == path {
return "", "", ErrLibraryExists
}
// Compare real paths so a symlink cannot hide an overlap. A library
// whose directory has vanished is compared by its stored path.
otherReal, err := filepath.EvalSymlinks(o.Path)
if err != nil {
otherReal = o.Path
}
if real == otherReal {
return "", "", ErrLibraryExists
}
if within(real, otherReal) || within(otherReal, real) {
return "", "", fmt.Errorf("%w: overlaps the library %q", ErrInvalidLibrary, o.Name)
}
}
return name, path, nil
}
// within reports whether child is strictly inside parent.
func within(child, parent string) bool {
return strings.HasPrefix(child, parent+string(filepath.Separator))
}