From a6d53b28ae89141c827bccefbf872b91ccdcda5e Mon Sep 17 00:00:00 2001 From: jjohnstondev Date: Sat, 7 Jan 2023 20:28:01 -0800 Subject: [PATCH] idr --- commands/commands.go | 57 ++++++++++++++++++++++++++++++++++++++++++-- runner/runner.go | 2 ++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/commands/commands.go b/commands/commands.go index a30f35d..d98b888 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "io/ioutil" + "net/url" "os" "path/filepath" "strings" @@ -14,8 +15,7 @@ import ( ) func Play(ctx *ctx.Context, client *spotify.Client) error { - var err error - err = client.Play(ctx) + err := client.Play(ctx) if err != nil { if isNoActiveError(err) { return playWithTransfer(ctx, client) @@ -26,6 +26,27 @@ func Play(ctx *ctx.Context, client *spotify.Client) error { return nil } +func PlayUrl(ctx *ctx.Context, client *spotify.Client, args []string) error { + if len(args) < 2 { + return fmt.Errorf("Please provide a url") + } + url, err := url.Parse(args[1]) + if err != nil { + return err + } + track_id := strings.Split(url.Path, "/")[2] + err = client.QueueSong(ctx, spotify.ID(track_id)) + if err != nil { + if isNoActiveError(err) { + return queueWithTransfer(ctx, client, spotify.ID(track_id)) + } + return err + } + err = client.Next(ctx) + ctx.Println("Playing!") + return nil +} + func Devices(ctx *ctx.Context, client *spotify.Client) error { devices, err := client.PlayerDevices(ctx) if err != nil { @@ -152,3 +173,35 @@ func playWithTransfer(ctx *ctx.Context, client *spotify.Client) error { ctx.Println("Playing!") return nil } + +func queueWithTransfer(ctx *ctx.Context, client *spotify.Client, track_id spotify.ID) error { + configDir, _ := os.UserConfigDir() + deviceFile, err := os.Open(filepath.Join(configDir, "gospt/device.json")) + if err != nil { + return err + } + defer deviceFile.Close() + deviceValue, err := ioutil.ReadAll(deviceFile) + if err != nil { + return err + } + var device *spotify.PlayerDevice + err = json.Unmarshal(deviceValue, &device) + if err != nil { + return err + } + err = client.TransferPlayback(ctx, device.ID, true) + if err != nil { + return err + } + err = client.QueueSong(ctx, track_id) + if err != nil { + return err + } + err = client.Next(ctx) + if err != nil { + return err + } + ctx.Println("Playing!") + return nil +} diff --git a/runner/runner.go b/runner/runner.go index 605e002..394dd38 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -22,6 +22,8 @@ func Run(ctx *ctx.Context, client *spotify.Client, args []string) error { switch args[0] { case "play": return commands.Play(ctx, client) + case "playurl": + return commands.PlayUrl(ctx, client, args) case "pause": return commands.Pause(ctx, client) case "next":