-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmopidy.go
More file actions
108 lines (91 loc) · 1.98 KB
/
Copy pathmopidy.go
File metadata and controls
108 lines (91 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package mopidy
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"sptlrx/player"
)
func New(address string) *Client {
return &Client{address: address}
}
// Client implements player.Player
type Client struct {
address string
}
func (c *Client) get(method string, out interface{}) error {
body := requestBody{
JsonRPC: "2.0",
ID: 1,
Method: method,
}
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
url := fmt.Sprintf("http://%s/mopidy/rpc", c.address)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(out)
}
func (c *Client) State() (*player.State, error) {
var state stateResponse
err := c.get("core.playback.get_state", &state)
if err != nil {
return nil, err
}
var current currentResponse
err = c.get("core.playback.get_current_track", ¤t)
if err != nil {
return nil, err
}
var position positionResponse
err = c.get("core.playback.get_time_position", &position)
if err != nil {
return nil, err
}
var artist string
for i, a := range current.Result.Artists {
if i != 0 {
artist += " "
}
artist += a.Name
}
query := artist + " " + current.Result.Name
return &player.State{
Track: player.TrackMetadata{
ID: current.Result.URI,
Query: query,
},
Position: position.Result,
Playing: state.Result == "playing",
}, err
}
type requestBody struct {
JsonRPC string `json:"jsonrpc"`
ID int `json:"id"`
Method string `json:"method"`
}
type currentResponse struct {
Result struct {
URI string `json:"uri"`
Name string `json:"name"`
Artists []struct {
Name string `json:"name"`
} `json:"artists"`
} `json:"result"`
}
type stateResponse struct {
Result string `json:"result"`
}
type positionResponse struct {
Result int `json:"result"`
}