mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 18:37:09 +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.
269 lines
8.9 KiB
Go
269 lines
8.9 KiB
Go
package nativeapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/deluan/rest"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/server"
|
|
)
|
|
|
|
func (api *Router) addPluginRoute(r chi.Router) {
|
|
repo := api.ds.Plugin()
|
|
|
|
r.Route("/plugin", func(r chi.Router) {
|
|
r.Use(pluginsEnabledMiddleware)
|
|
r.Get("/", rest.GetAll(repo))
|
|
r.Post("/rescan", api.rescanPlugins)
|
|
r.Route("/{id}", func(r chi.Router) {
|
|
r.Use(server.URLParamsMiddleware)
|
|
r.Get("/", rest.Get(repo))
|
|
r.Put("/", api.updatePlugin)
|
|
})
|
|
})
|
|
}
|
|
|
|
func (api *Router) rescanPlugins(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
if err := api.pluginManager.RescanPlugins(ctx); err != nil {
|
|
log.Error(ctx, "Error rescanning plugins", err)
|
|
http.Error(w, "Error rescanning plugins: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
// Middleware to check if 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 {
|
|
http.Error(w, "Not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// PluginUpdateRequest represents the fields that can be updated via the API
|
|
type PluginUpdateRequest struct {
|
|
Enabled *bool `json:"enabled,omitempty"`
|
|
Config *string `json:"config,omitempty"`
|
|
Users *string `json:"users,omitempty"`
|
|
AllUsers *bool `json:"allUsers,omitempty"`
|
|
Libraries *string `json:"libraries,omitempty"`
|
|
AllLibraries *bool `json:"allLibraries,omitempty"`
|
|
AllowWriteAccess *bool `json:"allowWriteAccess,omitempty"`
|
|
}
|
|
|
|
func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
ctx := r.Context()
|
|
repo := api.ds.Plugin()
|
|
|
|
// Get existing plugin to verify it exists
|
|
if _, err := repo.Get(ctx, id); err != nil {
|
|
if errors.Is(err, rest.ErrPermissionDenied) {
|
|
http.Error(w, "Access denied: admin privileges required", http.StatusForbidden)
|
|
return
|
|
}
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
http.Error(w, "Plugin not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
log.Error(ctx, "Error getting plugin", "id", id, err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// Parse update request
|
|
var req PluginUpdateRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
log.Error(ctx, "Error decoding request", err)
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Handle config update (if provided)
|
|
if req.Config != nil {
|
|
if err := validateAndUpdateConfig(ctx, api.pluginManager, id, *req.Config, w); err != nil {
|
|
log.Error(ctx, "Error updating plugin config", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Handle users permission update (if provided)
|
|
if req.Users != nil || req.AllUsers != nil {
|
|
if err := validateAndUpdateUsers(ctx, api.pluginManager, repo, id, req, w); err != nil {
|
|
log.Error(ctx, "Error updating plugin users", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Handle libraries permission update (if provided)
|
|
if req.Libraries != nil || req.AllLibraries != nil || req.AllowWriteAccess != nil {
|
|
if err := validateAndUpdateLibraries(ctx, api.pluginManager, repo, id, req, w); err != nil {
|
|
log.Error(ctx, "Error updating plugin libraries", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Handle enable/disable
|
|
if req.Enabled != nil {
|
|
if *req.Enabled {
|
|
if enableErr := api.pluginManager.EnablePlugin(ctx, id); enableErr != nil {
|
|
log.Error(ctx, "Error enabling plugin", "id", id, enableErr)
|
|
// Refresh plugin from DB to get the error
|
|
plugin, err := repo.Get(ctx, id)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting updated plugin after enable failure", "id", id, err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
// Return error response with message field for React-Admin compatibility
|
|
// and include the plugin data so UI can update its state
|
|
errorResponse := struct {
|
|
Message string `json:"message"`
|
|
Plugin *model.Plugin `json:"plugin"`
|
|
}{
|
|
Message: enableErr.Error(),
|
|
Plugin: plugin,
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
|
_ = json.NewEncoder(w).Encode(errorResponse)
|
|
return
|
|
}
|
|
} else {
|
|
if err := api.pluginManager.DisablePlugin(ctx, id); err != nil {
|
|
log.Error(ctx, "Error disabling plugin", "id", id, err)
|
|
http.Error(w, "Error disabling plugin: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// Refresh and return updated plugin
|
|
plugin, err := repo.Get(ctx, id)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting updated plugin", "id", id, err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(plugin); err != nil {
|
|
log.Error(ctx, "Error encoding plugin response", err)
|
|
}
|
|
}
|
|
|
|
// isValidJSON checks if a string is valid JSON
|
|
func isValidJSON(s string) bool {
|
|
var js json.RawMessage
|
|
return json.Unmarshal([]byte(s), &js) == nil
|
|
}
|
|
|
|
// validateAndUpdateConfig validates the config JSON against the plugin's schema and updates the plugin.
|
|
// Returns an error if validation or update fails (error response already written).
|
|
func validateAndUpdateConfig(ctx context.Context, pm PluginManager, id, configJSON string, w http.ResponseWriter) error {
|
|
// Basic JSON syntax check
|
|
if configJSON != "" && !isValidJSON(configJSON) {
|
|
http.Error(w, "Invalid JSON in config field", http.StatusBadRequest)
|
|
return errors.New("invalid JSON")
|
|
}
|
|
|
|
// Validate against plugin's config schema
|
|
if err := pm.ValidatePluginConfig(ctx, id, configJSON); err != nil {
|
|
log.Warn(ctx, "Config validation failed", "id", id, err)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
// Try to return structured validation errors if available
|
|
response := map[string]any{"message": err.Error()}
|
|
_ = json.NewEncoder(w).Encode(response)
|
|
return err
|
|
}
|
|
|
|
if err := pm.UpdatePluginConfig(ctx, id, configJSON); err != nil {
|
|
log.Error(ctx, "Error updating plugin config", "id", id, err)
|
|
http.Error(w, "Error updating plugin configuration: "+err.Error(), http.StatusInternalServerError)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateAndUpdateUsers validates the users JSON and updates the plugin.
|
|
// Returns an error if validation or update fails (error response already written).
|
|
func validateAndUpdateUsers(ctx context.Context, pm PluginManager, repo model.PluginRepository, id string, req PluginUpdateRequest, w http.ResponseWriter) error {
|
|
// Get current values if not provided in request
|
|
plugin, err := repo.Get(ctx, id)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting plugin for users update", "id", id, err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return err
|
|
}
|
|
|
|
usersJSON := plugin.Users
|
|
allUsers := plugin.AllUsers
|
|
|
|
if req.Users != nil {
|
|
if *req.Users != "" && !isValidJSON(*req.Users) {
|
|
http.Error(w, "Invalid JSON in users field", http.StatusBadRequest)
|
|
return errors.New("invalid JSON")
|
|
}
|
|
usersJSON = *req.Users
|
|
}
|
|
if req.AllUsers != nil {
|
|
allUsers = *req.AllUsers
|
|
}
|
|
|
|
if err := pm.UpdatePluginUsers(ctx, id, usersJSON, allUsers); err != nil {
|
|
log.Error(ctx, "Error updating plugin users", "id", id, err)
|
|
http.Error(w, "Error updating plugin users: "+err.Error(), http.StatusInternalServerError)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateAndUpdateLibraries validates the libraries JSON and updates the plugin.
|
|
// Returns an error if validation or update fails (error response already written).
|
|
func validateAndUpdateLibraries(ctx context.Context, pm PluginManager, repo model.PluginRepository, id string, req PluginUpdateRequest, w http.ResponseWriter) error {
|
|
// Get current values if not provided in request
|
|
plugin, err := repo.Get(ctx, id)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting plugin for libraries update", "id", id, err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return err
|
|
}
|
|
|
|
librariesJSON := plugin.Libraries
|
|
allLibraries := plugin.AllLibraries
|
|
allowWriteAccess := plugin.AllowWriteAccess
|
|
|
|
if req.Libraries != nil {
|
|
if *req.Libraries != "" && !isValidJSON(*req.Libraries) {
|
|
http.Error(w, "Invalid JSON in libraries field", http.StatusBadRequest)
|
|
return errors.New("invalid JSON")
|
|
}
|
|
librariesJSON = *req.Libraries
|
|
}
|
|
if req.AllLibraries != nil {
|
|
allLibraries = *req.AllLibraries
|
|
}
|
|
if req.AllowWriteAccess != nil {
|
|
allowWriteAccess = *req.AllowWriteAccess
|
|
}
|
|
|
|
if err := pm.UpdatePluginLibraries(ctx, id, librariesJSON, allLibraries, allowWriteAccess); err != nil {
|
|
log.Error(ctx, "Error updating plugin libraries", "id", id, err)
|
|
http.Error(w, "Error updating plugin libraries: "+err.Error(), http.StatusInternalServerError)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|