feat(plugins): add scrobbles access to PDK (#5795)

* initial scrobble api

* feat: add scrobble retrieval api

* address feedback (1)

* fix spelling

* be explicit about get

* add primary key field, update index, remove rowid references

* use unix timestamp for input and output

* initial api, some testing

* add tests, add count retrieval

* add docs, test for rejected user

* add permission validation for scrobble retriever

* chore(plugins): fix typos in scrobble retriever

Rename newScrobbleRetreverService, and fix FromTImestamp/nonero in the
ScrobbleRetriever doc comments, which generate into the Go and Rust PDKs.
Also corrects two mislabelled test entries.

* fix(plugins): make scrobble pagination order deterministic

Sorting only by submission_time left the order of equal timestamps up to the
query planner, but the cursor skips ties by offset, so an unstable order can
repeat or drop scrobbles between pages. Break ties on scrobbles.id, which the
existing scrobbles_user_time index already yields for free.

Descending is now honoured for every combination of From/To rather than only
when both or neither is set. This changes the default for a lone ToTimestamp
from newest-first to oldest-first.

* refactor(plugins): return the next page's options from GetScrobbles

Paging previously meant reading NextTimestamp and Cursor off the response and
deciding where each belonged: NextTimestamp into FromTimestamp when ascending
or ToTimestamp when descending, and Cursor copied every time, including when 0.
Both are silent data-loss bugs when a plugin gets them wrong.

GetScrobbles now returns the options for the following page, or nil when the
range is exhausted, so a plugin passes the value straight back and repeats.
ScrobbleCursor and ScrobbleList are gone; the query itself is unchanged.

* docs(plugins): warn against setting ScrobbleOptions.Offset manually

The all-ties carry rule assumes Offset counts already-returned rows at the
boundary timestamp, which only holds for the options GetScrobbles returns.
A hand-built From+Offset combination can silently skip scrobbles, so document
the field as managed pagination state instead of a generic skip.

* docs(plugins): document the ScrobbleRetriever host service in the README

Covers the manifest permissions (including the users requirement), the four
host functions, the options/ref field tables, and the pagination loop with
its two gotchas: the host-managed offset and the adjusted range on the
returned next options.

* chore(plugins): regenerate scrobble retriever stub with nil-safe accessors

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
This commit is contained in:
Kendall Garner 2026-08-08 19:13:29 -07:00 • committed by GitHub
commit b0c6d2e444
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 1826 additions and 2 deletions

View file

@ -43,6 +43,7 @@ The following host services are available:
- Library: provides access to music library metadata for plugins.
- Matcher: resolves externally-obtained songs to local library tracks,
- Scheduler: provides task scheduling capabilities for plugins.
- ScrobbleRetriever: allows a plugin to retrieve scrobbles for one or more authorized users.
- Storage: provides access to a plugin-specific directory with read/write permissions
- SubsonicAPI: provides access to Navidrome's Subsonic API from plugins.
- Task: provides persistent task queues for plugins.

View file

@ -0,0 +1,266 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the ScrobbleRetriever host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package host
import (
"encoding/json"
"errors"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
// ScrobbleCountOptions represents the ScrobbleCountOptions data structure.
// ScrobbleCountOptions carries optional parameters for counting user scrobbles
type ScrobbleCountOptions struct {
FromTimestamp *int64 `json:"fromTimestamp"`
ToTimestamp *int64 `json:"toTimestamp"`
}
// ScrobbleOptions represents the ScrobbleOptions data structure.
// ScrobbleOptions carries optional parameters for retrieving user scrobbles
type ScrobbleOptions struct {
FromTimestamp *int64 `json:"fromTimestamp"`
ToTimestamp *int64 `json:"toTimestamp"`
Descending bool `json:"descending"`
MaxItems int `json:"maxItems"`
Offset int `json:"offset"`
}
// ScrobbleRef represents the ScrobbleRef data structure.
// ScrobbleRef represents one instance of a scrobble (instance id, file id, submission time)
type ScrobbleRef struct {
ID int64 `json:"id"`
MediaFileID string `json:"mediaFileId"`
SubmissionTime int64 `json:"submissionTime"`
}
// scrobbleretriever_getfirsttimestamp is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user scrobbleretriever_getfirsttimestamp
func scrobbleretriever_getfirsttimestamp(uint64) uint64
// scrobbleretriever_getlasttimestamp is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user scrobbleretriever_getlasttimestamp
func scrobbleretriever_getlasttimestamp(uint64) uint64
// scrobbleretriever_getscrobbles is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user scrobbleretriever_getscrobbles
func scrobbleretriever_getscrobbles(uint64) uint64
// scrobbleretriever_getscrobblecount is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user scrobbleretriever_getscrobblecount
func scrobbleretriever_getscrobblecount(uint64) uint64
type scrobbleRetrieverGetFirstTimestampRequest struct {
Username string `json:"username"`
}
type scrobbleRetrieverGetFirstTimestampResponse struct {
Result *int64 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
type scrobbleRetrieverGetLastTimestampRequest struct {
Username string `json:"username"`
}
type scrobbleRetrieverGetLastTimestampResponse struct {
Result *int64 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
type scrobbleRetrieverGetScrobblesRequest struct {
Username string `json:"username"`
Options ScrobbleOptions `json:"options"`
}
type scrobbleRetrieverGetScrobblesResponse struct {
Scrobbles []ScrobbleRef `json:"scrobbles,omitempty"`
Next *ScrobbleOptions `json:"next,omitempty"`
Error string `json:"error,omitempty"`
}
type scrobbleRetrieverGetScrobbleCountRequest struct {
Username string `json:"username"`
Options ScrobbleCountOptions `json:"options"`
}
type scrobbleRetrieverGetScrobbleCountResponse struct {
Result int64 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// ScrobbleRetrieverGetFirstTimestamp calls the scrobbleretriever_getfirsttimestamp host function.
// GetFirstTimestamp returns the unix timestamp of the oldest scrobble for the user.
// If the user has no scrobbles, returns nil
func ScrobbleRetrieverGetFirstTimestamp(username string) (*int64, error) {
// Marshal request to JSON
req := scrobbleRetrieverGetFirstTimestampRequest{
Username: username,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := scrobbleretriever_getfirsttimestamp(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response scrobbleRetrieverGetFirstTimestampResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, err
}
// Convert Error field to Go error
if response.Error != "" {
return nil, errors.New(response.Error)
}
return response.Result, nil
}
// ScrobbleRetrieverGetLastTimestamp calls the scrobbleretriever_getlasttimestamp host function.
// GetLastTimestamp returns the unix timestamp of the most recent scrobble for the user
// If the user has no scrobbles, return nil
func ScrobbleRetrieverGetLastTimestamp(username string) (*int64, error) {
// Marshal request to JSON
req := scrobbleRetrieverGetLastTimestampRequest{
Username: username,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := scrobbleretriever_getlasttimestamp(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response scrobbleRetrieverGetLastTimestampResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, err
}
// Convert Error field to Go error
if response.Error != "" {
return nil, errors.New(response.Error)
}
return response.Result, nil
}
// ScrobbleRetrieverGetScrobbles calls the scrobbleretriever_getscrobbles host function.
// GetScrobbles returns one page of scrobbles for a user.
//
// Parameters:
// - username: the user to query for scrobbles
// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
// - options.Descending: If true, order from newest to oldest. Otherwise, oldest to newest
// - options.MaxItems: The maximum number of items to retrieve. The maximum value (and default) if not specified is 5000
// - options.Offset: Pagination state; only valid as received on the options returned by a previous call. Never set it manually
//
// Returns:
// - scrobbles: The scrobbles in the requested range, ordered by submission time
// (ties broken by scrobble ID) in the direction given by options.Descending
// - next: The options for the following page, or nil once no scrobbles remain.
// Pass it back to GetScrobbles unchanged and repeat until it is nil. It carries an
// adjusted FromTimestamp/ToTimestamp, so keep a copy if you still need the original range
func ScrobbleRetrieverGetScrobbles(username string, options ScrobbleOptions) ([]ScrobbleRef, *ScrobbleOptions, error) {
// Marshal request to JSON
req := scrobbleRetrieverGetScrobblesRequest{
Username: username,
Options: options,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, nil, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := scrobbleretriever_getscrobbles(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response scrobbleRetrieverGetScrobblesResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return nil, nil, err
}
// Convert Error field to Go error
if response.Error != "" {
return nil, nil, errors.New(response.Error)
}
return response.Scrobbles, response.Next, nil
}
// ScrobbleRetrieverGetScrobbleCount calls the scrobbleretriever_getscrobblecount host function.
// GetScrobbleCount returns the number of scrobbles for a user in a given range
//
// Parameters:
// - username: the user to query for scrobbles
// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
//
// Returns:
// - the number of scrobbles in the given range, or 0
func ScrobbleRetrieverGetScrobbleCount(username string, options ScrobbleCountOptions) (int64, error) {
// Marshal request to JSON
req := scrobbleRetrieverGetScrobbleCountRequest{
Username: username,
Options: options,
}
reqBytes, err := json.Marshal(req)
if err != nil {
return 0, err
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
// Call the host function
responsePtr := scrobbleretriever_getscrobblecount(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
// Parse the response
var response scrobbleRetrieverGetScrobbleCountResponse
if err := json.Unmarshal(responseBytes, &response); err != nil {
return 0, err
}
// Convert Error field to Go error
if response.Error != "" {
return 0, errors.New(response.Error)
}
return response.Result, nil
}

View file

@ -0,0 +1,136 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains mock implementations for non-WASM builds.
// These mocks allow IDE support, compilation, and unit testing on non-WASM platforms.
// Plugin authors can use the exported mock instances to set expectations in tests.
//
//go:build !wasip1
package host
import (
"github.com/stretchr/testify/mock"
)
// ScrobbleCountOptions represents the ScrobbleCountOptions data structure.
// ScrobbleCountOptions carries optional parameters for counting user scrobbles
type ScrobbleCountOptions struct {
FromTimestamp *int64 `json:"fromTimestamp"`
ToTimestamp *int64 `json:"toTimestamp"`
}
// ScrobbleOptions represents the ScrobbleOptions data structure.
// ScrobbleOptions carries optional parameters for retrieving user scrobbles
type ScrobbleOptions struct {
FromTimestamp *int64 `json:"fromTimestamp"`
ToTimestamp *int64 `json:"toTimestamp"`
Descending bool `json:"descending"`
MaxItems int `json:"maxItems"`
Offset int `json:"offset"`
}
// ScrobbleRef represents the ScrobbleRef data structure.
// ScrobbleRef represents one instance of a scrobble (instance id, file id, submission time)
type ScrobbleRef struct {
ID int64 `json:"id"`
MediaFileID string `json:"mediaFileId"`
SubmissionTime int64 `json:"submissionTime"`
}
// mockScrobbleRetrieverService is the mock implementation for testing.
type mockScrobbleRetrieverService struct {
mock.Mock
}
// ScrobbleRetrieverMock is the auto-instantiated mock instance for testing.
// Use this to set expectations: host.ScrobbleRetrieverMock.On("MethodName", args...).Return(values...)
var ScrobbleRetrieverMock = &mockScrobbleRetrieverService{}
// GetFirstTimestamp is the mock method for ScrobbleRetrieverGetFirstTimestamp.
func (m *mockScrobbleRetrieverService) GetFirstTimestamp(username string) (*int64, error) {
args := m.Called(username)
var r0 *int64
if v := args.Get(0); v != nil {
r0 = v.(*int64)
}
return r0, args.Error(1)
}
// ScrobbleRetrieverGetFirstTimestamp delegates to the mock instance.
// GetFirstTimestamp returns the unix timestamp of the oldest scrobble for the user.
// If the user has no scrobbles, returns nil
func ScrobbleRetrieverGetFirstTimestamp(username string) (*int64, error) {
return ScrobbleRetrieverMock.GetFirstTimestamp(username)
}
// GetLastTimestamp is the mock method for ScrobbleRetrieverGetLastTimestamp.
func (m *mockScrobbleRetrieverService) GetLastTimestamp(username string) (*int64, error) {
args := m.Called(username)
var r0 *int64
if v := args.Get(0); v != nil {
r0 = v.(*int64)
}
return r0, args.Error(1)
}
// ScrobbleRetrieverGetLastTimestamp delegates to the mock instance.
// GetLastTimestamp returns the unix timestamp of the most recent scrobble for the user
// If the user has no scrobbles, return nil
func ScrobbleRetrieverGetLastTimestamp(username string) (*int64, error) {
return ScrobbleRetrieverMock.GetLastTimestamp(username)
}
// GetScrobbles is the mock method for ScrobbleRetrieverGetScrobbles.
func (m *mockScrobbleRetrieverService) GetScrobbles(username string, options ScrobbleOptions) ([]ScrobbleRef, *ScrobbleOptions, error) {
args := m.Called(username, options)
var r0 []ScrobbleRef
if v := args.Get(0); v != nil {
r0 = v.([]ScrobbleRef)
}
var r1 *ScrobbleOptions
if v := args.Get(1); v != nil {
r1 = v.(*ScrobbleOptions)
}
return r0, r1, args.Error(2)
}
// ScrobbleRetrieverGetScrobbles delegates to the mock instance.
// GetScrobbles returns one page of scrobbles for a user.
//
// Parameters:
// - username: the user to query for scrobbles
// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
// - options.Descending: If true, order from newest to oldest. Otherwise, oldest to newest
// - options.MaxItems: The maximum number of items to retrieve. The maximum value (and default) if not specified is 5000
// - options.Offset: Pagination state; only valid as received on the options returned by a previous call. Never set it manually
//
// Returns:
// - scrobbles: The scrobbles in the requested range, ordered by submission time
// (ties broken by scrobble ID) in the direction given by options.Descending
// - next: The options for the following page, or nil once no scrobbles remain.
// Pass it back to GetScrobbles unchanged and repeat until it is nil. It carries an
// adjusted FromTimestamp/ToTimestamp, so keep a copy if you still need the original range
func ScrobbleRetrieverGetScrobbles(username string, options ScrobbleOptions) ([]ScrobbleRef, *ScrobbleOptions, error) {
return ScrobbleRetrieverMock.GetScrobbles(username, options)
}
// GetScrobbleCount is the mock method for ScrobbleRetrieverGetScrobbleCount.
func (m *mockScrobbleRetrieverService) GetScrobbleCount(username string, options ScrobbleCountOptions) (int64, error) {
args := m.Called(username, options)
return args.Get(0).(int64), args.Error(1)
}
// ScrobbleRetrieverGetScrobbleCount delegates to the mock instance.
// GetScrobbleCount returns the number of scrobbles for a user in a given range
//
// Parameters:
// - username: the user to query for scrobbles
// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
//
// Returns:
// - the number of scrobbles in the given range, or 0
func ScrobbleRetrieverGetScrobbleCount(username string, options ScrobbleCountOptions) (int64, error) {
return ScrobbleRetrieverMock.GetScrobbleCount(username, options)
}

View file

@ -40,6 +40,7 @@
//! - [`library`] - provides access to music library metadata for plugins.
//! - [`matcher`] - resolves externally-obtained songs to local library tracks,
//! - [`scheduler`] - provides task scheduling capabilities for plugins.
//! - [`scrobbleretriever`] - allows a plugin to retrieve scrobbles for one or more authorized users.
//! - [`storage`] - provides access to a plugin-specific directory with read/write permissions
//! - [`subsonicapi`] - provides access to Navidrome's Subsonic API from plugins.
//! - [`task`] - provides persistent task queues for plugins.
@ -102,6 +103,13 @@ pub mod scheduler {
pub use super::nd_host_scheduler::*;
}
#[doc(hidden)]
mod nd_host_scrobbleretriever;
/// allows a plugin to retrieve scrobbles for one or more authorized users.
pub mod scrobbleretriever {
pub use super::nd_host_scrobbleretriever::*;
}
#[doc(hidden)]
mod nd_host_storage;
/// provides access to a plugin-specific directory with read/write permissions

View file

@ -0,0 +1,237 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the ScrobbleRetriever host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
/// ScrobbleCountOptions carries optional parameters for counting user scrobbles
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScrobbleCountOptions {
#[serde(default)]
pub from_timestamp: Option<i64>,
#[serde(default)]
pub to_timestamp: Option<i64>,
}
/// ScrobbleOptions carries optional parameters for retrieving user scrobbles
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScrobbleOptions {
#[serde(default)]
pub from_timestamp: Option<i64>,
#[serde(default)]
pub to_timestamp: Option<i64>,
pub descending: bool,
pub max_items: i32,
#[serde(default)]
pub offset: i32,
}
/// ScrobbleRef represents one instance of a scrobble (instance id, file id, submission time)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScrobbleRef {
pub id: i64,
pub media_file_id: String,
pub submission_time: i64,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetFirstTimestampRequest {
username: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetFirstTimestampResponse {
#[serde(default)]
result: Option<i64>,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetLastTimestampRequest {
username: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetLastTimestampResponse {
#[serde(default)]
result: Option<i64>,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetScrobblesRequest {
username: String,
options: ScrobbleOptions,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetScrobblesResponse {
#[serde(default)]
scrobbles: Vec<ScrobbleRef>,
#[serde(default)]
next: Option<ScrobbleOptions>,
#[serde(default)]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetScrobbleCountRequest {
username: String,
options: ScrobbleCountOptions,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ScrobbleRetrieverGetScrobbleCountResponse {
#[serde(default)]
result: i64,
#[serde(default)]
error: Option<String>,
}
#[host_fn]
extern "ExtismHost" {
fn scrobbleretriever_getfirsttimestamp(input: Json<ScrobbleRetrieverGetFirstTimestampRequest>) -> Json<ScrobbleRetrieverGetFirstTimestampResponse>;
fn scrobbleretriever_getlasttimestamp(input: Json<ScrobbleRetrieverGetLastTimestampRequest>) -> Json<ScrobbleRetrieverGetLastTimestampResponse>;
fn scrobbleretriever_getscrobbles(input: Json<ScrobbleRetrieverGetScrobblesRequest>) -> Json<ScrobbleRetrieverGetScrobblesResponse>;
fn scrobbleretriever_getscrobblecount(input: Json<ScrobbleRetrieverGetScrobbleCountRequest>) -> Json<ScrobbleRetrieverGetScrobbleCountResponse>;
}
/// GetFirstTimestamp returns the unix timestamp of the oldest scrobble for the user.
/// If the user has no scrobbles, returns nil
///
/// # Arguments
/// * `username` - String parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get_first_timestamp(username: &str) -> Result<Option<i64>, Error> {
let response = unsafe {
scrobbleretriever_getfirsttimestamp(Json(ScrobbleRetrieverGetFirstTimestampRequest {
username: username.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// GetLastTimestamp returns the unix timestamp of the most recent scrobble for the user
/// If the user has no scrobbles, return nil
///
/// # Arguments
/// * `username` - String parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get_last_timestamp(username: &str) -> Result<Option<i64>, Error> {
let response = unsafe {
scrobbleretriever_getlasttimestamp(Json(ScrobbleRetrieverGetLastTimestampRequest {
username: username.to_owned(),
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}
/// GetScrobbles returns one page of scrobbles for a user.
///
/// Parameters:
/// - username: the user to query for scrobbles
/// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
/// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
/// - options.Descending: If true, order from newest to oldest. Otherwise, oldest to newest
/// - options.MaxItems: The maximum number of items to retrieve. The maximum value (and default) if not specified is 5000
/// - options.Offset: Pagination state; only valid as received on the options returned by a previous call. Never set it manually
///
/// Returns:
/// - scrobbles: The scrobbles in the requested range, ordered by submission time
/// (ties broken by scrobble ID) in the direction given by options.Descending
/// - next: The options for the following page, or nil once no scrobbles remain.
/// Pass it back to GetScrobbles unchanged and repeat until it is nil. It carries an
/// adjusted FromTimestamp/ToTimestamp, so keep a copy if you still need the original range
///
/// # Arguments
/// * `username` - String parameter.
/// * `options` - ScrobbleOptions parameter.
///
/// # Returns
/// A tuple of (scrobbles, next).
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get_scrobbles(username: &str, options: ScrobbleOptions) -> Result<(Vec<ScrobbleRef>, Option<ScrobbleOptions>), Error> {
let response = unsafe {
scrobbleretriever_getscrobbles(Json(ScrobbleRetrieverGetScrobblesRequest {
username: username.to_owned(),
options: options,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok((response.0.scrobbles, response.0.next))
}
/// GetScrobbleCount returns the number of scrobbles for a user in a given range
///
/// Parameters:
/// - username: the user to query for scrobbles
/// - options.FromTimestamp: If specified, the first UNIX timestamp to start fetching scrobbles (inclusive). Otherwise, start from the first scrobble
/// - options.ToTimestamp: If specified, the last UNIX timestamp to fetch (inclusive). Otherwise, end at the last scrobble
///
/// Returns:
/// - the number of scrobbles in the given range, or 0
///
/// # Arguments
/// * `username` - String parameter.
/// * `options` - ScrobbleCountOptions parameter.
///
/// # Returns
/// The result value.
///
/// # Errors
/// Returns an error if the host function call fails.
pub fn get_scrobble_count(username: &str, options: ScrobbleCountOptions) -> Result<i64, Error> {
let response = unsafe {
scrobbleretriever_getscrobblecount(Json(ScrobbleRetrieverGetScrobbleCountRequest {
username: username.to_owned(),
options: options,
}))?
};
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
Ok(response.0.result)
}