-
Notifications
You must be signed in to change notification settings - Fork 22
/
client.go
277 lines (224 loc) · 5.78 KB
/
client.go
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package airplay
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/DHowett/go-plist"
)
// A PlaybackInfo is a playback information of playing content.
type PlaybackInfo struct {
// IsReadyToPlay, if true, content is currently playing or ready to play.
IsReadyToPlay bool `plist:"readyToPlay"`
// ReadyToPlayValue represents the information on whether content is currently playing, ready to play or not.
ReadyToPlayValue interface{} `plist:"readyToPlay"`
// Duration represents playback duration in seconds.
Duration float64 `plist:"duration"`
// Position represents playback position in seconds.
Position float64 `plist:"position"`
}
type Client struct {
connection *connection
}
// SlideTransition represents transition that used when show the picture.
type SlideTransition string
const (
SlideNone SlideTransition = "None"
SlideDissolve SlideTransition = "Dissolve"
SlideLeft SlideTransition = "SlideLeft"
SlideRight SlideTransition = "SlideRight"
)
var (
requestInverval = time.Second
)
type ClientParam struct {
Addr string
Port int
Password string
}
// FirstClient return the AirPlay Client that has the first found AirPlay device in LAN
func FirstClient() (*Client, error) {
device := FirstDevice()
if device.Name == "" {
return nil, errors.New("AirPlay devices not found")
}
return &Client{connection: newConnection(device)}, nil
}
func NewClient(params *ClientParam) (*Client, error) {
if params.Addr == "" {
return nil, errors.New("airplay: [ERR] Address is required to NewClient()")
}
if params.Port <= 0 {
params.Port = 7000
}
client := &Client{}
device := Device{Addr: params.Addr, Port: params.Port}
client.connection = newConnection(device)
if params.Password != "" {
client.SetPassword(params.Password)
}
return client, nil
}
func (c Client) SetPassword(password string) {
c.connection.setPassword(password)
}
// Play start content playback.
//
// When playback is finished, sends termination status on the returned channel.
// If non-nil, not a successful termination.
func (c *Client) Play(url string) <-chan error {
return c.PlayAt(url, 0.0)
}
// PlayAt start content playback by specifying the start position.
//
// Returned channel is the same as Play().
func (c *Client) PlayAt(url string, position float64) <-chan error {
ch := make(chan error, 1)
body := fmt.Sprintf("Content-Location: %s\nStart-Position: %f\n", url, position)
go func() {
if _, err := c.connection.post("play", strings.NewReader(body)); err != nil {
ch <- err
return
}
if err := c.waitForReadyToPlay(); err != nil {
ch <- err
return
}
interval := time.Tick(requestInverval)
for {
info, err := c.GetPlaybackInfo()
if err != nil {
ch <- err
return
}
if !info.IsReadyToPlay {
break
}
<-interval
}
ch <- nil
}()
return ch
}
// Stop exits content playback.
func (c *Client) Stop() {
c.connection.post("stop", nil)
}
// Scrub seeks at position seconds in playing content.
func (c *Client) Scrub(position float64) {
query := fmt.Sprintf("?position=%f", position)
c.connection.post("scrub"+query, nil)
}
// Rate change the playback rate in playing content.
//
// If rate is 0, content is paused.
// if rate is 1, content playing at the normal speed.
func (c *Client) Rate(rate float64) {
query := fmt.Sprintf("?value=%f", rate)
c.connection.post("rate"+query, nil)
}
// Photo show a JPEG picture. It can specify both remote or local file.
//
// A trivial example:
//
// // local file
// client.Photo("/path/to/gopher.jpg")
//
// // remote file
// client.Photo("http://blog.golang.org/gopher/plush.jpg")
//
func (c *Client) Photo(path string) {
c.PhotoWithSlide(path, SlideNone)
}
// PhotoWithSlide show a JPEG picture in the transition specified.
func (c *Client) PhotoWithSlide(path string, transition SlideTransition) {
url, err := url.Parse(path)
if err != nil {
log.Fatal(err)
}
var image *bytes.Reader
if url.Scheme == "http" || url.Scheme == "https" {
image, err = remoteImageReader(path)
} else {
image, err = localImageReader(path)
}
if err != nil {
log.Fatal(err)
}
header := http.Header{
"X-Apple-Transition": {string(transition)},
}
c.connection.postWithHeader("photo", image, header)
}
// GetPlaybackInfo retrieves playback informations.
func (c *Client) GetPlaybackInfo() (*PlaybackInfo, error) {
response, err := c.connection.get("playback-info")
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := convertBytesReader(response.Body)
if err != nil {
return nil, err
}
decoder := plist.NewDecoder(body)
info := &PlaybackInfo{}
if err := decoder.Decode(info); err != nil {
return nil, err
}
switch t := info.ReadyToPlayValue.(type) {
case uint64: // AppleTV 4G
info.IsReadyToPlay = (t == 1)
case bool: // AppleTV 2G, 3G
info.IsReadyToPlay = t
}
return info, nil
}
func (c *Client) waitForReadyToPlay() error {
interval := time.Tick(requestInverval)
timeout := time.After(10 * time.Second)
for {
select {
case <-timeout:
return errors.New("timeout while waiting for ready to play")
case <-interval:
info, err := c.GetPlaybackInfo()
if err != nil {
return err
}
if info.IsReadyToPlay {
return nil
}
}
}
}
func localImageReader(path string) (*bytes.Reader, error) {
fn, err := os.Open(path)
if err != nil {
return nil, err
}
defer fn.Close()
return convertBytesReader(fn)
}
func remoteImageReader(url string) (*bytes.Reader, error) {
response, err := http.Get(url)
if err != nil {
return nil, err
}
defer response.Body.Close()
return convertBytesReader(response.Body)
}
func convertBytesReader(r io.Reader) (*bytes.Reader, error) {
body, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return bytes.NewReader(body), nil
}