package host
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
"github.com/navidrome/navidrome/plugins/types"
)
type MatcherMatchSongsRequest struct {
Songs []types.SongRef `json:"songs"`
Opts MatchOptions `json:"opts"`
}
type MatcherMatchSongsResponse struct {
Results []*types.Track `json:"results,omitempty"`
Error string `json:"error,omitempty"`
}
func RegisterMatcherHostFunctions(service MatcherService) []extism.HostFunction {
return []extism.HostFunction{
newMatcherMatchSongsHostFunction(service),
}
}
func newMatcherMatchSongsHostFunction(service MatcherService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"matcher_matchsongs",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
matcherWriteError(p, stack, err)
return
}
var req MatcherMatchSongsRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
matcherWriteError(p, stack, err)
return
}
results, svcErr := service.MatchSongs(ctx, req.Songs, req.Opts)
if svcErr != nil {
matcherWriteError(p, stack, svcErr)
return
}
resp := MatcherMatchSongsResponse{
Results: results,
}
matcherWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
func matcherWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
matcherWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
func matcherWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}