mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 10:27:08 +02: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.
249 lines
8.2 KiB
Go
249 lines
8.2 KiB
Go
package plugins
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/navidrome/navidrome/core/scrobbler"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/navidrome/navidrome/server/events"
|
|
)
|
|
|
|
// PluginMetadata holds the extracted information from a plugin file
|
|
// without fully initializing the plugin.
|
|
type PluginMetadata struct {
|
|
Manifest *Manifest
|
|
SHA256 string
|
|
}
|
|
|
|
// adminContext returns a context with admin privileges for DB operations.
|
|
func adminContext(ctx context.Context) context.Context {
|
|
return request.WithUser(ctx, model.User{IsAdmin: true})
|
|
}
|
|
|
|
// marshalManifest marshals a manifest to JSON string, returning empty string on error.
|
|
func marshalManifest(m *Manifest) string {
|
|
b, _ := json.Marshal(m)
|
|
return string(b)
|
|
}
|
|
|
|
// ComputeFileSHA256 computes the SHA-256 hash of a file without loading it into memory.
|
|
// This is used for quick change detection before full plugin compilation.
|
|
func ComputeFileSHA256(path string) (string, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer f.Close()
|
|
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(h.Sum(nil)), nil
|
|
}
|
|
|
|
// addPluginToDB adds a new plugin to the database as disabled.
|
|
func (m *Manager) addPluginToDB(ctx context.Context, repo model.PluginRepository, name, path string, metadata *PluginMetadata) error {
|
|
now := time.Now()
|
|
newPlugin := &model.Plugin{
|
|
ID: name,
|
|
Path: path,
|
|
Manifest: marshalManifest(metadata.Manifest),
|
|
SHA256: metadata.SHA256,
|
|
Enabled: false,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
if err := repo.Put(ctx, newPlugin); err != nil {
|
|
return fmt.Errorf("adding plugin to DB: %w", err)
|
|
}
|
|
log.Info(ctx, "Discovered new plugin", "plugin", name)
|
|
m.sendPluginRefreshEvent(ctx, events.Any)
|
|
return nil
|
|
}
|
|
|
|
// updatePluginInDB updates an existing plugin in the database after a file change.
|
|
// If the plugin was enabled, it will be unloaded and disabled.
|
|
func (m *Manager) updatePluginInDB(ctx context.Context, repo model.PluginRepository, dbPlugin *model.Plugin, path string, metadata *PluginMetadata) error {
|
|
wasEnabled := dbPlugin.Enabled
|
|
if wasEnabled {
|
|
if err := m.unloadPlugin(dbPlugin.ID); err != nil {
|
|
log.Debug(ctx, "Plugin not loaded during change", "plugin", dbPlugin.ID, err)
|
|
}
|
|
}
|
|
dbPlugin.Path = path
|
|
dbPlugin.Manifest = marshalManifest(metadata.Manifest)
|
|
dbPlugin.SHA256 = metadata.SHA256
|
|
dbPlugin.Enabled = false
|
|
dbPlugin.LastError = ""
|
|
dbPlugin.UpdatedAt = time.Now()
|
|
if err := repo.Put(ctx, dbPlugin); err != nil {
|
|
return fmt.Errorf("updating plugin in DB: %w", err)
|
|
}
|
|
log.Info(ctx, "Plugin file changed", "plugin", dbPlugin.ID, "wasEnabled", wasEnabled)
|
|
m.sendPluginRefreshEvent(ctx, dbPlugin.ID)
|
|
return nil
|
|
}
|
|
|
|
// removePluginFromDB removes a plugin from the database.
|
|
// If the plugin was enabled, it will be unloaded first.
|
|
func (m *Manager) removePluginFromDB(ctx context.Context, repo model.PluginRepository, dbPlugin *model.Plugin) error {
|
|
pluginID := dbPlugin.ID
|
|
if dbPlugin.Enabled {
|
|
if err := m.unloadPlugin(pluginID); err != nil {
|
|
log.Debug(ctx, "Plugin not loaded during removal", "plugin", pluginID, err)
|
|
}
|
|
}
|
|
if err := repo.Delete(ctx, pluginID); err != nil {
|
|
return fmt.Errorf("deleting plugin from DB: %w", err)
|
|
}
|
|
// Discard any scrobbles still buffered for the removed plugin, so they are
|
|
// not delivered to an unrelated plugin that reuses the same name later.
|
|
// Skip names owned by builtin scrobblers: buffer entries are keyed by
|
|
// service name, so removing a plugin file named e.g. "lastfm.ndp" must not
|
|
// wipe the builtin Last.fm retry queue.
|
|
if scrobbler.IsBuiltinScrobbler(pluginID) {
|
|
log.Debug(ctx, "Keeping buffered scrobbles: name is owned by a builtin scrobbler", "plugin", pluginID)
|
|
} else if err := m.ds.ScrobbleBuffer().Discard(ctx, pluginID); err != nil {
|
|
log.Error(ctx, "Error discarding buffered scrobbles for removed plugin", "plugin", pluginID, err)
|
|
}
|
|
log.Info(ctx, "Plugin removed", "plugin", pluginID)
|
|
m.sendPluginRefreshEvent(ctx, events.Any)
|
|
return nil
|
|
}
|
|
|
|
// syncPlugins scans the plugins folder and synchronizes with the database.
|
|
// It handles new, changed, and removed plugins by comparing SHA-256 hashes.
|
|
// - New plugins are added to DB as disabled
|
|
// - Changed plugins are updated in DB and disabled if they were enabled
|
|
// - Removed plugins are deleted from DB (after unloading if enabled)
|
|
func (m *Manager) syncPlugins(ctx context.Context, folder string) error {
|
|
if m.ds == nil {
|
|
return fmt.Errorf("datastore not configured")
|
|
}
|
|
|
|
adminCtx := adminContext(ctx)
|
|
|
|
// Read current plugins from folder
|
|
entries, err := os.ReadDir(folder)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
log.Debug(ctx, "Plugins folder does not exist", "folder", folder)
|
|
return nil
|
|
}
|
|
return fmt.Errorf("reading plugins folder: %w", err)
|
|
}
|
|
|
|
// Build map of files in folder
|
|
filesOnDisk := make(map[string]string) // name -> path
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), PackageExtension) {
|
|
log.Trace(ctx, "Skipping non-plugin entry", "name", entry.Name(), "isDir", entry.IsDir())
|
|
continue
|
|
}
|
|
name, ok := pluginIDFromPath(entry.Name())
|
|
if !ok {
|
|
log.Warn(ctx, "Skipping plugin with unusable name", "name", entry.Name())
|
|
continue
|
|
}
|
|
filesOnDisk[name] = filepath.Join(folder, entry.Name())
|
|
}
|
|
log.Debug(ctx, "Plugin sync: scanned folder", "folder", folder, "entriesTotal", len(entries), "pluginsFound", len(filesOnDisk))
|
|
|
|
// Get all plugins from DB
|
|
repo := m.ds.Plugin()
|
|
dbPlugins, err := repo.GetAll(adminCtx)
|
|
if err != nil {
|
|
return fmt.Errorf("reading plugins from DB: %w", err)
|
|
}
|
|
pluginsInDB := make(map[string]*model.Plugin)
|
|
for i := range dbPlugins {
|
|
pluginsInDB[dbPlugins[i].ID] = &dbPlugins[i]
|
|
}
|
|
log.Debug(ctx, "Plugin sync: current DB state", "pluginsInDB", len(pluginsInDB))
|
|
|
|
now := time.Now()
|
|
|
|
// Process files on disk
|
|
for name, path := range filesOnDisk {
|
|
dbPlugin, exists := pluginsInDB[name]
|
|
|
|
// Compute SHA256 first (lightweight operation) to check if plugin changed
|
|
sha256Hash, err := ComputeFileSHA256(path)
|
|
if err != nil {
|
|
log.Error(ctx, "Failed to compute SHA256 for plugin", "plugin", name, "path", path, err)
|
|
continue
|
|
}
|
|
|
|
// If plugin exists in DB with same hash, skip full manifest extraction
|
|
if exists && dbPlugin.SHA256 == sha256Hash {
|
|
// Plugin unchanged - just update path in case folder moved
|
|
if dbPlugin.Path != path {
|
|
dbPlugin.Path = path
|
|
dbPlugin.UpdatedAt = now
|
|
if err := repo.Put(adminCtx, dbPlugin); err != nil {
|
|
log.Error(ctx, "Failed to update plugin path in DB", "plugin", name, err)
|
|
}
|
|
}
|
|
delete(pluginsInDB, name)
|
|
continue
|
|
}
|
|
|
|
// Plugin is new or changed - need full manifest extraction
|
|
metadata, err := m.extractManifest(path)
|
|
if err != nil {
|
|
log.Error(ctx, "Failed to extract manifest from plugin", "plugin", name, "path", path, err)
|
|
// Store error in DB if plugin exists
|
|
if exists {
|
|
dbPlugin.LastError = err.Error()
|
|
dbPlugin.UpdatedAt = now
|
|
if dbPlugin.Enabled {
|
|
// Unload broken plugin
|
|
if unloadErr := m.unloadPlugin(name); unloadErr != nil {
|
|
log.Debug(ctx, "Plugin not loaded", "plugin", name)
|
|
}
|
|
dbPlugin.Enabled = false
|
|
}
|
|
if putErr := repo.Put(adminCtx, dbPlugin); putErr != nil {
|
|
log.Error(ctx, "Failed to update plugin in DB", "plugin", name, err)
|
|
}
|
|
}
|
|
delete(pluginsInDB, name)
|
|
continue
|
|
}
|
|
|
|
if !exists {
|
|
// New plugin - add to DB as disabled
|
|
if err := m.addPluginToDB(adminCtx, repo, name, path, metadata); err != nil {
|
|
log.Error(ctx, "Failed to add plugin to DB", "plugin", name, err)
|
|
}
|
|
} else {
|
|
// Plugin changed - update DB
|
|
if err := m.updatePluginInDB(adminCtx, repo, dbPlugin, path, metadata); err != nil {
|
|
log.Error(ctx, "Failed to update plugin in DB", "plugin", name, err)
|
|
}
|
|
}
|
|
// Mark as processed
|
|
delete(pluginsInDB, name)
|
|
}
|
|
|
|
// Remove plugins no longer on disk
|
|
for _, dbPlugin := range pluginsInDB {
|
|
if err := m.removePluginFromDB(adminCtx, repo, dbPlugin); err != nil {
|
|
log.Error(ctx, "Failed to delete plugin from DB", "plugin", dbPlugin.ID, err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|