Improve LoadableSource implementation

This commit is contained in:
nemunaire 2024-10-09 09:02:32 +02:00
parent eb2eeee3c7
commit 207a4562e6
4 changed files with 31 additions and 25 deletions

2
app.go
View File

@ -73,7 +73,7 @@ func (app *App) loadCustomSources() error {
if newss, ok := sources.LoadableSources[csrc.Source]; !ok { if newss, ok := sources.LoadableSources[csrc.Source]; !ok {
return fmt.Errorf("Unable to load source #%d: %q: no such source registered", id, csrc.Source) return fmt.Errorf("Unable to load source #%d: %q: no such source registered", id, csrc.Source)
} else { } else {
src, err := newss(csrc.KV) src, err := newss.LoadSource(csrc.KV)
if err != nil { if err != nil {
return fmt.Errorf("Unable to load source #%d (%s): %w", id, csrc.Source, err) return fmt.Errorf("Unable to load source #%d (%s): %w", id, csrc.Source, err)
} }

View File

@ -9,8 +9,8 @@ import (
) )
type CustomSource struct { type CustomSource struct {
Source string `json:"src"` Source string `json:"src"`
KV map[string]string `json:"kv"` KV map[string]interface{} `json:"kv"`
} }
type Settings struct { type Settings struct {

View File

@ -1,6 +1,8 @@
package sources package sources
import () import (
"encoding/json"
)
var ( var (
LoadableSources = map[string]LoadaleSource{} LoadableSources = map[string]LoadaleSource{}
@ -19,4 +21,17 @@ type PlayingSource interface {
CurrentlyPlaying() string CurrentlyPlaying() string
} }
type LoadaleSource func(map[string]string) (SoundSource, error) type LoadaleSource struct {
LoadSource func(map[string]interface{}) (SoundSource, error)
Description string
SourceDefinition interface{}
}
func Unmarshal(in map[string]interface{}, out interface{}) error {
jin, err := json.Marshal(in)
if err != nil {
return err
}
return json.Unmarshal(jin, out)
}

View File

@ -7,7 +7,6 @@ import (
"os" "os"
"os/exec" "os/exec"
"path" "path"
"strings"
"time" "time"
"github.com/DexterLB/mpvipc" "github.com/DexterLB/mpvipc"
@ -18,31 +17,23 @@ import (
type MPVSource struct { type MPVSource struct {
process *exec.Cmd process *exec.Cmd
ipcSocketDir string ipcSocketDir string
Name string Name string `json:"name"`
Options []string Options []string `json:"opts"`
File string File string `json:"file"`
} }
func init() { func init() {
sources.LoadableSources["mpv"] = NewMPVSource sources.LoadableSources["mpv"] = sources.LoadaleSource{
LoadSource: NewMPVSource,
Description: "Play any file, stream or URL through mpv",
SourceDefinition: &MPVSource{},
}
} }
func NewMPVSource(kv map[string]string) (sources.SoundSource, error) { func NewMPVSource(kv map[string]interface{}) (sources.SoundSource, error) {
var s MPVSource var s MPVSource
err := sources.Unmarshal(kv, &s)
if name, ok := kv["name"]; ok { return &s, err
s.Name = name
}
if opts, ok := kv["opts"]; ok {
s.Options = strings.Split(opts, " ")
}
if file, ok := kv["file"]; ok {
s.File = file
}
return &s, nil
} }
func (s *MPVSource) GetName() string { func (s *MPVSource) GetName() string {