Deluan Quintão ae0e0c89d9
feat(plugins): add PlaybackReport to scrobbler capability (#5452)
* feat(plugins): add PlaybackReport to Scrobbler interface and all implementations

* feat(plugins): add PlaybackReport worker and dispatch in PlayTracker

* feat(plugins): add PlaybackReportRequest to plugin scrobbler capability

* chore(plugins): regenerate PDK files with PlaybackReport

* feat(plugins): add PlaybackReport to test scrobbler plugin

* feat(plugins): add PlaybackReport to plugin scrobbler adapter

* refactor(plugins): fix double DB fetch in StateStopped and batch getActiveScrobblers

- Hoist mf from scrobble branch so PlaybackReport reuses it instead of
  fetching again from DB
- Call getActiveScrobblers once per drain batch instead of per-entry

* chore(plugins): include generated scrobbler schema with PlaybackReport

* fix(plugins): skip PlaybackReport for plugins that don't export it

Plugins detected as scrobblers only need to export one scrobbler
function. Older plugins that don't export nd_scrobbler_playback_report
would cause noisy error logs on every reportPlayback call. Now
errFunctionNotFound and errNotImplemented are treated as no-ops.

* refactor: rename NowPlayingInfo to PlaybackReport

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename stopNowPlayingWorker to stopBackgroundWorkers

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: move NowPlaying and PlaybackReport logic to separate worker files

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scrobbler): rename NowPlayingInfo to PlaybackSession and add expired state

Rename NowPlayingInfo struct to PlaybackSession to better reflect its role
as a complete playback session representation. Add UserId field to make
sessions self-contained, removing redundant userId parameters from
PlaybackReport interface method and internal dispatch functions. Introduce
StateExpired internal state that fires when a session cache entry expires
without an explicit stop, ensuring plugins always receive a terminal event
regardless of client behavior.

* fix(scrobbler): update playback state description to include 'expired'

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(scrobbler): resolve data race in OnExpiration callback

Capture conf.Server.EnableNowPlaying at construction time instead of
reading it from the background ttlcache eviction goroutine. The previous
code raced with test config cleanup that writes to the same field
concurrently.

* fix(scrobbler): return error when media file lookup fails in StateStopped

Simplify the MediaFile population logic in the stopped case to return an
error if the track cannot be found. A stop report with an empty MediaFile
is useless to plugins, and returning the error allows clients to retry
or alert the user when auto-scrobble is enabled.

* refactor(scrobbler): use session data directly in PlaybackReport adapter

Use info.Username from PlaybackSession instead of extracting it from
context in the plugin adapter, since the session is now self-contained.
Add debug/trace logging for session expiration and enqueue the expired
report with a user-enriched context so downstream handlers can identify
the user.

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-05-02 16:14:53 -04:00
..

Navidrome Plugin Development Kit for Rust

This directory contains the Rust PDK crates for building Navidrome plugins.

Crate Structure

plugins/pdk/rust/
├── nd-pdk/              # Umbrella crate - use this as your dependency
├── nd-pdk-host/         # Host function wrappers (call Navidrome services)
└── nd-pdk-capabilities/ # Capability traits and types (generated)

Usage

Add the nd-pdk crate as a dependency in your plugin's Cargo.toml:

[package]
name = "my-plugin"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
nd-pdk = { path = "../../pdk/rust/nd-pdk" }
extism-pdk = "1.2"

Implementing a Scrobbler (Required-All Pattern)

The Scrobbler capability requires all methods to be implemented:

use nd_pdk::scrobbler::{
    Error, IsAuthorizedRequest,
    NowPlayingRequest, ScrobbleRequest, Scrobbler,
};

// Register WASM exports for all Scrobbler methods
nd_pdk::register_scrobbler!(MyPlugin);

#[derive(Default)]
struct MyPlugin;

impl Scrobbler for MyPlugin {
    fn is_authorized(&self, req: IsAuthorizedRequest) -> Result<bool, Error> {
        Ok(true)
    }

    fn now_playing(&self, req: NowPlayingRequest) -> Result<(), Error> {
        // Handle now playing notification
        Ok(())
    }

    fn scrobble(&self, req: ScrobbleRequest) -> Result<(), Error> {
        // Submit scrobble
        Ok(())
    }
}

Implementing Metadata Agent (Optional Pattern)

The MetadataAgent capability allows implementing individual methods:

use nd_pdk::metadata::{
    ArtistBiographyProvider, GetArtistBiographyRequest, ArtistBiography, Error,
};

// Register only the methods you implement
nd_pdk::register_artist_biography!(MyPlugin);

#[derive(Default)]
struct MyPlugin;

impl ArtistBiographyProvider for MyPlugin {
    fn get_artist_biography(&self, req: GetArtistBiographyRequest) 
        -> Result<ArtistBiography, Error> 
    {
        // Return artist biography
        Ok(ArtistBiography {
            biography: "Artist bio text...".into(),
            ..Default::default()
        })
    }
}

Using Host Services

Access Navidrome services via the host module:

use nd_pdk::host::{artwork, scheduler, library};

// Get artwork URL for a track
let url = artwork::get_track_url("track-id", 300)?;

// Schedule a one-time callback
scheduler::schedule_one_time(60, "my-payload", "schedule-id")?;

// Get library information
let libs = library::get_all()?;

Available Capabilities

Capability Pattern Description
scrobbler Required-all Submit listening history to external services
metadata Optional Provide artist/album metadata from external sources
lifecycle Optional Handle plugin initialization
scheduler Optional Receive scheduled callbacks
websocket Optional Handle WebSocket messages

Building

Rust plugins must be compiled to WASM using the wasm32-wasip1 target:

cargo build --release --target wasm32-wasip1

The resulting .wasm file can be packaged into an .ndp plugin package.

Examples

See the example plugins for complete implementations:

Code Generation

The capability modules in nd-pdk-capabilities are auto-generated from the Go capability definitions. To regenerate after capability changes:

make gen

This generates both Go and Rust PDK code.