Debian Codegraph @

mpd/client.go

raw symbols SCIP
1 // Copyright 2009 The GoMPD Authors. All rights reserved.
2 // Use of this source code is governed by the MIT
3 // license that can be found in the LICENSE file.
4
5 // Package mpd provides the client side interface to MPD (Music Player Daemon).
6 // The protocol reference can be found at http://www.musicpd.org/doc/protocol/index.html
7 package mpd
8
9 import (
10 "errors"
11 "fmt"
12 "io"
13 "net/textproto"
14 "strconv"
15 "strings"
16 "time"
17 )
18
19 // Quote quotes string VALUES in the format understood by MPD.
20 // See: https://github.com/MusicPlayerDaemon/MPD/blob/master/src/util/Tokenizer.cxx
21 // NB: this function shouldn't be used on the PROTOCOL LEVEL because it considers single quotes special chars and
22 // escapes them.
23 func quote(s string) string {
24 // TODO: We are using strings.Builder even tough it's not ideal.
25 // When unsafe.{String,Slice}{,Data} is available, we should use buffer+unsafe.
26 // q := make([]byte, 2+2*len(s))
27 // return unsafe.String(unsafe.SliceData(q), len(q))
28 // [issue53003]: https://github.com/golang/go/issues/53003
29 var q strings.Builder
30 q.Grow(2 + 2*len(s))
31 q.WriteByte('"')
32 for _, c := range []byte(s) {
33 // We need to escape single/double quotes and a backslash by prepending them with a '\'
34 switch c {
35 case '"', '\\', '\'':
36 q.WriteByte('\\')
37 }
38 q.WriteByte(c)
39 }
40 q.WriteByte('"')
41 return q.String()
42 }
43
44 // Quote quotes each string of args in the format understood by MPD.
45 // See: https://github.com/MusicPlayerDaemon/MPD/blob/master/src/util/Tokenizer.cxx
46 func quoteArgs(args []string) string {
47 quoted := make([]string, len(args))
48 for index, arg := range args {
49 quoted[index] = quote(arg)
50 }
51 return strings.Join(quoted, " ")
52 }
53
54 // Client represents a client connection to a MPD server.
55 type Client struct {
56 text *textproto.Conn
57 version string
58 }
59
60 // Error represents an error returned by the MPD server.
61 // It contains the error number, the index of the causing command in the command list,
62 // the name of the command in the command list and the error message.
63 type Error struct {
64 Code ErrorCode
65 CommandListIndex int
66 CommandName string
67 Message string
68 }
69
70 // ErrorCode is the error code of a Error.
71 type ErrorCode int
72
73 // ErrorCodes as defined in MPD source (https://www.musicpd.org/doc/api/html/Ack_8hxx_source.html)
74 // version 0.21.
75 const (
76 ErrorNotList ErrorCode = 1
77 ErrorArg ErrorCode = 2
78 ErrorPassword ErrorCode = 3
79 ErrorPermission ErrorCode = 4
80 ErrorUnknown ErrorCode = 5
81 ErrorNoExist ErrorCode = 50
82 ErrorPlaylistMax ErrorCode = 51
83 ErrorSystem ErrorCode = 52
84 ErrorPlaylistLoad ErrorCode = 53
85 ErrorUpdateAlready ErrorCode = 54
86 ErrorPlayerSync ErrorCode = 55
87 ErrorExist ErrorCode = 56
88 )
89
90 func (e Error) Error() string {
91 if e.CommandName != "" {
92 return fmt.Sprintf("command '%s' failed: %s", e.CommandName, e.Message)
93 }
94 return e.Message
95 }
96
97 // Attrs is a set of attributes returned by MPD.
98 type Attrs map[string]string
99
100 // Dial connects to MPD listening on address addr (e.g. "127.0.0.1:6600")
101 // on network network (e.g. "tcp").
102 func Dial(network, addr string) (c *Client, err error) {
103 text, err := textproto.Dial(network, addr)
104 if err != nil {
105 return nil, err
106 }
107 line, err := text.ReadLine()
108 if err != nil {
109 return nil, err
110 }
111 if line[0:6] != "OK MPD" {
112 return nil, textproto.ProtocolError("no greeting")
113 }
114 return &Client{text: text, version: line[7:]}, nil
115 }
116
117 // DialAuthenticated connects to MPD listening on address addr (e.g. "127.0.0.1:6600")
118 // on network network (e.g. "tcp"). It then authenticates with MPD
119 // using the plaintext password password if it's not empty.
120 func DialAuthenticated(network, addr, password string) (c *Client, err error) {
121 c, err = Dial(network, addr)
122 if err == nil && len(password) > 0 {
123 err = c.Command("password %s", password).OK()
124 }
125 return c, err
126 }
127
128 // Version returns the protocol version used as provided during the handshake.
129 func (c *Client) Version() string {
130 return c.version
131 }
132
133 // We are reimplemeting Cmd() and PrintfLine() from textproto here, because
134 // the original functions append CR-LF to the end of commands. This behavior
135 // violates the MPD protocol: Commands must be terminated by '\n'.
136 func (c *Client) cmd(format string, args ...interface{}) (uint, error) {
137 id := c.text.Next()
138 c.text.StartRequest(id)
139 defer c.text.EndRequest(id)
140 if err := c.printfLine(format, args...); err != nil {
141 return 0, err
142 }
143 return id, nil
144 }
145
146 func (c *Client) printfLine(format string, args ...interface{}) error {
147 fmt.Fprintf(c.text.W, format, args...)
148 c.text.W.WriteByte('\n')
149 return c.text.W.Flush()
150 }
151
152 // Close terminates the connection with MPD.
153 func (c *Client) Close() (err error) {
154 if c.text != nil {
155 c.printfLine("close")
156 err = c.text.Close()
157 c.text = nil
158 }
159 return
160 }
161
162 // Ping sends a no-op message to MPD. It's useful for keeping the connection alive.
163 func (c *Client) Ping() error {
164 return c.Command("ping").OK()
165 }
166
167 func (c *Client) readList(key string) (list []string, err error) {
168 list = []string{}
169 key += ": "
170 for {
171 line, err := c.readLine()
172 if err != nil {
173 return nil, err
174 }
175 if line == "OK" {
176 break
177 }
178 if !strings.HasPrefix(line, key) {
179 return nil, textproto.ProtocolError("unexpected: " + line)
180 }
181 list = append(list, line[len(key):])
182 }
183 return
184 }
185
186 func (c *Client) readLine() (string, error) {
187 line, err := c.text.ReadLine()
188 if err != nil {
189 return "", err
190 }
191 if strings.HasPrefix(line, "ACK ") {
192 cur := line[4:]
193 var code, idx int
194 if strings.HasPrefix(cur, "[") {
195 sep := strings.Index(cur, "@")
196 end := strings.Index(cur, "] ")
197 if sep > 0 && end > 0 {
198 code, err = strconv.Atoi(cur[1:sep])
199 if err != nil {
200 return "", err
201 }
202 idx, err = strconv.Atoi(cur[sep+1 : end])
203 if err != nil {
204 return "", err
205 }
206 cur = cur[end+2:]
207 }
208 }
209 var cmd string
210 if strings.HasPrefix(cur, "{") {
211 if end := strings.Index(cur, "} "); end > 0 {
212 cmd = cur[1:end]
213 cur = cur[end+2:]
214 }
215 }
216 msg := strings.TrimSpace(cur)
217 return "", Error{
218 Code: ErrorCode(code),
219 CommandListIndex: idx,
220 CommandName: cmd,
221 Message: msg,
222 }
223 }
224 return line, nil
225 }
226
227 func (c *Client) readBytes(length int) ([]byte, error) {
228 // Read the entire chunk of data. ReadFull() makes sure the data length matches the expectation
229 data := make([]byte, length)
230 if _, err := io.ReadFull(c.text.R, data); err != nil {
231 return nil, err
232 }
233
234 // Verify there's a linebreak afterwards and skip it
235 termByte, err := c.text.R.ReadByte()
236 if err != nil {
237 return nil, textproto.ProtocolError("failed to read binary data terminator: " + err.Error())
238 }
239 if termByte != '\n' {
240 return nil, textproto.ProtocolError(fmt.Sprintf("wrong binary data terminator: want 0x0a, got %x", termByte))
241 }
242 return data, nil
243 }
244
245 func (c *Client) readAttrsList(startKey string) (attrs []Attrs, err error) {
246 attrs = []Attrs{}
247 startKey += ": "
248 for {
249 line, err := c.readLine()
250 if err != nil {
251 return nil, err
252 }
253 if line == "OK" {
254 break
255 }
256 if strings.HasPrefix(line, startKey) { // new entry begins
257 attrs = append(attrs, Attrs{})
258 }
259 if len(attrs) == 0 {
260 return nil, textproto.ProtocolError("unexpected: " + line)
261 }
262 i := strings.Index(line, ": ")
263 if i < 0 {
264 return nil, textproto.ProtocolError("can't parse line: " + line)
265 }
266 attrs[len(attrs)-1][line[0:i]] = line[i+2:]
267 }
268 return attrs, nil
269 }
270
271 func (c *Client) readAttrs(terminator string) (attrs Attrs, err error) {
272 attrs = make(Attrs)
273 for {
274 line, err := c.readLine()
275 if err != nil {
276 return nil, err
277 }
278 if line == terminator {
279 break
280 }
281 z := strings.Index(line, ": ")
282 if z < 0 {
283 return nil, textproto.ProtocolError("can't parse line: " + line)
284 }
285 key := line[0:z]
286 attrs[key] = line[z+2:]
287 }
288 return
289 }
290
291 func (c *Client) readBinary() ([]byte, int, error) {
292 size := -1
293 for {
294 line, err := c.readLine()
295 switch {
296 case err != nil:
297 return nil, 0, err
298
299 // Check for the size key
300 case strings.HasPrefix(line, "size: "):
301 if size, err = strconv.Atoi(line[6:]); err != nil {
302 return nil, 0, textproto.ProtocolError("failed to parse size: " + err.Error())
303 }
304
305 // Check for the binary key
306 case strings.HasPrefix(line, "binary: "):
307 length := -1
308 if length, err = strconv.Atoi(line[8:]); err != nil {
309 return nil, 0, textproto.ProtocolError("failed to parse binary: " + err.Error())
310 }
311
312 // If no size is given, assume it's equal to the provided data's length
313 if size < 0 {
314 size = length
315 }
316
317 // The binary data must follow the 'binary:' key
318 data, err := c.readBytes(length)
319 if err != nil {
320 return nil, 0, err
321 }
322
323 // The binary data must be followed by the "OK" line
324 if s, err := c.readLine(); err != nil {
325 return nil, 0, err
326 } else if s != "OK" {
327 return nil, 0, textproto.ProtocolError("expected 'OK', got " + s)
328 }
329 return data, size, nil
330
331 // No more data. Obviously, no binary data encountered
332 case line == "", line == "OK":
333 return nil, 0, textproto.ProtocolError("no binary data found in response")
334 }
335 }
336 }
337
338 // CurrentSong returns information about the current song in the playlist.
339 func (c *Client) CurrentSong() (Attrs, error) {
340 return c.Command("currentsong").Attrs()
341 }
342
343 // Status returns information about the current status of MPD.
344 func (c *Client) Status() (Attrs, error) {
345 return c.Command("status").Attrs()
346 }
347
348 // Stats displays statistics (number of artists, songs, playtime, etc)
349 func (c *Client) Stats() (Attrs, error) {
350 return c.Command("stats").Attrs()
351 }
352
353 func (c *Client) readOKLine(terminator string) (err error) {
354 line, err := c.readLine()
355 if err != nil {
356 return
357 }
358 if line == terminator {
359 return nil
360 }
361 return textproto.ProtocolError("unexpected response: " + line)
362 }
363
364 func (c *Client) idle(subsystems ...string) ([]string, error) {
365 return c.Command("idle %s", Quoted(strings.Join(subsystems, " "))).Strings("changed")
366 }
367
368 func (c *Client) noIdle() (err error) {
369 id, err := c.cmd("noidle")
370 if err == nil {
371 c.text.StartResponse(id)
372 c.text.EndResponse(id)
373 }
374 return
375 }
376
377 //
378 // Playback control
379 //
380
381 // Next plays next song in the playlist.
382 func (c *Client) Next() error {
383 return c.Command("next").OK()
384 }
385
386 // Pause pauses playback if pause is true; resumes playback otherwise.
387 func (c *Client) Pause(pause bool) error {
388 if pause {
389 return c.Command("pause 1").OK()
390 }
391 return c.Command("pause 0").OK()
392 }
393
394 // Play starts playing the song at playlist position pos. If pos is negative,
395 // start playing at the current position in the playlist.
396 func (c *Client) Play(pos int) error {
397 if pos < 0 {
398 return c.Command("play").OK()
399 }
400 return c.Command("play %d", pos).OK()
401 }
402
403 // PlayID plays the song identified by id. If id is negative, start playing
404 // at the current position in playlist.
405 func (c *Client) PlayID(id int) error {
406 if id < 0 {
407 return c.Command("playid").OK()
408 }
409 return c.Command("playid %d", id).OK()
410 }
411
412 // Previous plays previous song in the playlist.
413 func (c *Client) Previous() error {
414 return c.Command("previous").OK()
415 }
416
417 // Seek seeks to the position time (in seconds) of the song at playlist position pos.
418 // Deprecated: Use SeekPos instead.
419 func (c *Client) Seek(pos, time int) error {
420 return c.Command("seek %d %d", pos, time).OK()
421 }
422
423 // SeekID is identical to Seek except the song is identified by it's id
424 // (not position in playlist).
425 // Deprecated: Use SeekSongID instead.
426 func (c *Client) SeekID(id, time int) error {
427 return c.Command("seekid %d %d", id, time).OK()
428 }
429
430 // SeekPos seeks to the position d of the song at playlist position pos.
431 func (c *Client) SeekPos(pos int, d time.Duration) error {
432 return c.Command("seek %d %f", pos, d.Seconds()).OK()
433 }
434
435 // SeekSongID seeks to the position d of the song identified by id.
436 func (c *Client) SeekSongID(id int, d time.Duration) error {
437 return c.Command("seekid %d %f", id, d.Seconds()).OK()
438 }
439
440 // SeekCur seeks to the position d within the current song.
441 // If relative is true, then the time is relative to the current playing position.
442 func (c *Client) SeekCur(d time.Duration, relative bool) error {
443 if relative {
444 return c.Command("seekcur %+f", d.Seconds()).OK()
445 }
446 return c.Command("seekcur %f", d.Seconds()).OK()
447 }
448
449 // Stop stops playback.
450 func (c *Client) Stop() error {
451 return c.Command("stop").OK()
452 }
453
454 // SetVolume sets the volume to volume. The range of volume is 0-100.
455 func (c *Client) SetVolume(volume int) error {
456 return c.Command("setvol %d", volume).OK()
457 }
458
459 // Random enables random playback, if random is true, disables it otherwise.
460 func (c *Client) Random(random bool) error {
461 if random {
462 return c.Command("random 1").OK()
463 }
464 return c.Command("random 0").OK()
465 }
466
467 // Repeat enables repeat mode, if repeat is true, disables it otherwise.
468 func (c *Client) Repeat(repeat bool) error {
469 if repeat {
470 return c.Command("repeat 1").OK()
471 }
472 return c.Command("repeat 0").OK()
473 }
474
475 // Single enables single song mode, if single is true, disables it otherwise.
476 func (c *Client) Single(single bool) error {
477 if single {
478 return c.Command("single 1").OK()
479 }
480 return c.Command("single 0").OK()
481 }
482
483 // Consume enables consume mode, if consume is true, disables it otherwise.
484 func (c *Client) Consume(consume bool) error {
485 if consume {
486 return c.Command("consume 1").OK()
487 }
488 return c.Command("consume 0").OK()
489 }
490
491 //
492 // Playlist related functions
493 //
494
495 // PlaylistInfo returns attributes for songs in the current playlist. If
496 // both start and end are negative, it does this for all songs in
497 // playlist. If end is negative but start is positive, it does it for the
498 // song at position start. If both start and end are positive, it does it
499 // for positions in range [start, end).
500 func (c *Client) PlaylistInfo(start, end int) ([]Attrs, error) {
501 var cmd *Command
502 switch {
503 case start < 0 && end < 0:
504 // Request all playlist items.
505 cmd = c.Command("playlistinfo")
506 case start >= 0 && end >= 0:
507 // Request this range of playlist items.
508 cmd = c.Command("playlistinfo %d:%d", start, end)
509 case start >= 0 && end < 0:
510 // Request the single playlist item at this position.
511 cmd = c.Command("playlistinfo %d", start)
512 case start < 0 && end >= 0:
513 return nil, errors.New("negative start index")
514 default:
515 panic("unreachable")
516 }
517 return cmd.AttrsList("file")
518 }
519
520 // SetPriority set the priority of the specified songs. If end is negative but
521 // start is non-negative, it does it for the song at position start. If both
522 // start and end are non-negative, it does it for positions in range
523 // [start, end).
524 func (c *Client) SetPriority(priority, start, end int) error {
525 switch {
526 case start < 0 && end < 0:
527 return errors.New("negative start and end index")
528 case start >= 0 && end >= 0:
529 // Update the prio for this range of playlist items.
530 return c.Command("prio %d %d:%d", priority, start, end).OK()
531 case start >= 0 && end < 0:
532 // Update the prio for a single playlist item at this position.
533 return c.Command("prio %d %d", priority, start).OK()
534 case start < 0 && end >= 0:
535 return errors.New("negative start index")
536 default:
537 panic("unreachable")
538 }
539 }
540
541 // SetPriorityID sets the prio of the song with the given id.
542 func (c *Client) SetPriorityID(priority, id int) error {
543 return c.Command("prioid %d %d", priority, id).OK()
544 }
545
546 // Delete deletes songs from playlist. If both start and end are positive,
547 // it deletes those at positions in range [start, end). If end is negative,
548 // it deletes the song at position start.
549 func (c *Client) Delete(start, end int) error {
550 if start < 0 {
551 return errors.New("negative start index")
552 }
553 if end < 0 {
554 return c.Command("delete %d", start).OK()
555 }
556 return c.Command("delete %d:%d", start, end).OK()
557 }
558
559 // DeleteID deletes the song identified by id.
560 func (c *Client) DeleteID(id int) error {
561 return c.Command("deleteid %d", id).OK()
562 }
563
564 // Move moves the songs between the positions start and end to the new position
565 // position. If end is negative, only the song at position start is moved.
566 func (c *Client) Move(start, end, position int) error {
567 if start < 0 {
568 return errors.New("negative start index")
569 }
570 if end < 0 {
571 return c.Command("move %d %d", start, position).OK()
572 }
573 return c.Command("move %d:%d %d", start, end, position).OK()
574 }
575
576 // MoveID moves songid to position on the plyalist.
577 func (c *Client) MoveID(songid, position int) error {
578 return c.Command("moveid %d %d", songid, position).OK()
579 }
580
581 // Add adds the file/directory uri to playlist. Directories add recursively.
582 func (c *Client) Add(uri string) error {
583 return c.Command("add %s", uri).OK()
584 }
585
586 // AddID adds the file/directory uri to playlist and returns the identity
587 // id of the song added. If pos is positive, the song is added to position
588 // pos.
589 func (c *Client) AddID(uri string, pos int) (int, error) {
590 var cmd *Command
591 if pos >= 0 {
592 cmd = c.Command("addid %s %d", uri, pos)
593 } else {
594 cmd = c.Command("addid %s", uri)
595 }
596 attrs, err := cmd.Attrs()
597 if err != nil {
598 return -1, err
599 }
600 tok, ok := attrs["Id"]
601 if !ok {
602 return -1, textproto.ProtocolError("addid did not return Id")
603 }
604 return strconv.Atoi(tok)
605 }
606
607 // Clear clears the current playlist.
608 func (c *Client) Clear() error {
609 return c.Command("clear").OK()
610 }
611
612 // Shuffle shuffles the tracks from position start to position end in the
613 // current playlist. If start or end is negative, the whole playlist is
614 // shuffled.
615 func (c *Client) Shuffle(start, end int) error {
616 if start < 0 || end < 0 {
617 return c.Command("shuffle").OK()
618 }
619 return c.Command("shuffle %d:%d", start, end).OK()
620 }
621
622 // Database related commands
623
624 // GetFiles returns the entire list of files in MPD database.
625 func (c *Client) GetFiles() ([]string, error) {
626 return c.Command("list file").Strings("file")
627 }
628
629 // Update updates MPD's database: find new files, remove deleted files, update
630 // modified files. uri is a particular directory or file to update. If it is an
631 // empty string, everything is updated.
632 //
633 // The returned jobID identifies the update job, enqueued by MPD.
634 func (c *Client) Update(uri string) (jobID int, err error) {
635 id, err := c.cmd("update %s", quote(uri))
636 if err != nil {
637 return
638 }
639 c.text.StartResponse(id)
640 defer c.text.EndResponse(id)
641
642 line, err := c.readLine()
643 if err != nil {
644 return
645 }
646 if !strings.HasPrefix(line, "updating_db: ") {
647 return 0, textproto.ProtocolError("unexpected response: " + line)
648 }
649 jobID, err = strconv.Atoi(line[13:])
650 if err != nil {
651 return
652 }
653 return jobID, c.readOKLine("OK")
654 }
655
656 // Rescan updates MPD's database like Update, but it also rescans unmodified
657 // files. uri is a particular directory or file to update. If it is an empty
658 // string, everything is updated.
659 //
660 // The returned jobID identifies the update job, enqueued by MPD.
661 func (c *Client) Rescan(uri string) (jobID int, err error) {
662 id, err := c.cmd("rescan %s", quote(uri))
663 if err != nil {
664 return
665 }
666 c.text.StartResponse(id)
667 defer c.text.EndResponse(id)
668
669 line, err := c.readLine()
670 if err != nil {
671 return
672 }
673 if !strings.HasPrefix(line, "updating_db: ") {
674 return 0, textproto.ProtocolError("unexpected response: " + line)
675 }
676 jobID, err = strconv.Atoi(line[13:])
677 if err != nil {
678 return
679 }
680 return jobID, c.readOKLine("OK")
681 }
682
683 // ListAllInfo returns attributes for songs in the library. Information about
684 // any song that is either inside or matches the passed in uri is returned.
685 // To get information about every song in the library, pass in "/".
686 func (c *Client) ListAllInfo(uri string) ([]Attrs, error) {
687 id, err := c.cmd("listallinfo %s ", quote(uri))
688 if err != nil {
689 return nil, err
690 }
691 c.text.StartResponse(id)
692 defer c.text.EndResponse(id)
693
694 attrs := []Attrs{}
695 inEntry := false
696 for {
697 line, err := c.readLine()
698 if err != nil {
699 return nil, err
700 }
701 if line == "OK" {
702 break
703 } else if strings.HasPrefix(line, "file: ") { // new entry begins
704 attrs = append(attrs, Attrs{})
705 inEntry = true
706 } else if strings.HasPrefix(line, "directory: ") {
707 inEntry = false
708 }
709
710 if inEntry {
711 i := strings.Index(line, ": ")
712 if i < 0 {
713 return nil, textproto.ProtocolError("can't parse line: " + line)
714 }
715 attrs[len(attrs)-1][line[0:i]] = line[i+2:]
716 }
717 }
718 return attrs, nil
719 }
720
721 // ListInfo lists the contents of the directory URI using MPD's lsinfo command.
722 func (c *Client) ListInfo(uri string) ([]Attrs, error) {
723 id, err := c.cmd("lsinfo %s", quote(uri))
724 if err != nil {
725 return nil, err
726 }
727 c.text.StartResponse(id)
728 defer c.text.EndResponse(id)
729 attrs := []Attrs{}
730 for {
731 line, err := c.readLine()
732 if err != nil {
733 return nil, err
734 }
735 if line == "OK" {
736 break
737 }
738 if strings.HasPrefix(line, "file: ") ||
739 strings.HasPrefix(line, "directory: ") ||
740 strings.HasPrefix(line, "playlist: ") {
741 attrs = append(attrs, Attrs{})
742 }
743 i := strings.Index(line, ": ")
744 if i < 0 {
745 return nil, textproto.ProtocolError("can't parse line: " + line)
746 }
747 attrs[len(attrs)-1][strings.ToLower(line[0:i])] = line[i+2:]
748 }
749 return attrs, nil
750 }
751
752 // ReadComments reads "comments" (audio metadata) from the song URI using
753 // MPD's readcomments command.
754 func (c *Client) ReadComments(uri string) (Attrs, error) {
755 return c.Command("readcomments %s", uri).Attrs()
756 }
757
758 // Find searches the library for songs and returns attributes for each matching song.
759 // The args are the raw arguments passed to MPD. For example, to search for
760 // songs that belong to a specific artist and album:
761 //
762 // Find("artist", "Artist Name", "album", "Album Name")
763 //
764 // Searches are case sensitive. Use Search for case insensitive search.
765 func (c *Client) Find(args ...string) ([]Attrs, error) {
766 return c.Command("find " + quoteArgs(args)).AttrsList("file")
767 }
768
769 // Search behaves exactly the same as Find, but the searches are not case sensitive.
770 func (c *Client) Search(args ...string) ([]Attrs, error) {
771 return c.Command("search " + quoteArgs(args)).AttrsList("file")
772 }
773
774 // List searches the database for your query. You can use something simple like
775 // `artist` for your search, or something like `artist album <Album Name>` if
776 // you want the artist that has an album with a specified album name.
777 func (c *Client) List(args ...string) ([]string, error) {
778 id, err := c.cmd("list " + quoteArgs(args))
779 if err != nil {
780 return nil, err
781 }
782 c.text.StartResponse(id)
783 defer c.text.EndResponse(id)
784
785 var ret []string
786 for {
787 line, err := c.readLine()
788 if err != nil {
789 return nil, err
790 }
791
792 i := strings.Index(line, ": ")
793 if i > 0 {
794 ret = append(ret, line[i+2:])
795 } else if line == "OK" {
796 break
797 } else {
798 return nil, textproto.ProtocolError("can't parse line: " + line)
799 }
800 }
801 return ret, nil
802 }
803
804 // Partition commands
805
806 // Partition switches the client to a different partition.
807 func (c *Client) Partition(name string) error {
808 return c.Command("partition %s", name).OK()
809 }
810
811 // ListPartitions returns a list of partitions and their information.
812 func (c *Client) ListPartitions() ([]Attrs, error) {
813 return c.Command("listpartitions").AttrsList("partition")
814 }
815
816 // NewPartition creates a new partition with the given name.
817 func (c *Client) NewPartition(name string) error {
818 return c.Command("newpartition %s", name).OK()
819 }
820
821 // DelPartition deletes partition with the given name.
822 func (c *Client) DelPartition(name string) error {
823 return c.Command("delpartition %s", name).OK()
824 }
825
826 // MoveOutput moves an output with the given name to the current partition.
827 func (c *Client) MoveOutput(name string) error {
828 return c.Command("moveoutput %s", name).OK()
829 }
830
831 // Output related commands.
832
833 // ListOutputs lists all configured outputs with their name, id & enabled state.
834 func (c *Client) ListOutputs() ([]Attrs, error) {
835 return c.Command("outputs").AttrsList("outputid")
836 }
837
838 // EnableOutput enables the audio output with the given id.
839 func (c *Client) EnableOutput(id int) error {
840 return c.Command("enableoutput %d", id).OK()
841 }
842
843 // DisableOutput disables the audio output with the given id.
844 func (c *Client) DisableOutput(id int) error {
845 return c.Command("disableoutput %d", id).OK()
846 }
847
848 // Stored playlists related commands
849
850 // ListPlaylists lists all stored playlists.
851 func (c *Client) ListPlaylists() ([]Attrs, error) {
852 return c.Command("listplaylists").AttrsList("playlist")
853 }
854
855 // PlaylistContents returns a list of attributes for songs in the specified
856 // stored playlist.
857 func (c *Client) PlaylistContents(name string) ([]Attrs, error) {
858 return c.Command("listplaylistinfo %s", name).AttrsList("file")
859 }
860
861 // PlaylistLoad loads the specfied playlist into the current queue.
862 // If start and end are non-negative, only songs in this range are loaded.
863 func (c *Client) PlaylistLoad(name string, start, end int) error {
864 if start < 0 || end < 0 {
865 return c.Command("load %s", name).OK()
866 }
867 return c.Command("load %s %d:%d", name, start, end).OK()
868 }
869
870 // PlaylistAdd adds a song identified by uri to a stored playlist identified
871 // by name.
872 func (c *Client) PlaylistAdd(name string, uri string) error {
873 return c.Command("playlistadd %s %s", name, uri).OK()
874 }
875
876 // PlaylistClear clears the specified playlist.
877 func (c *Client) PlaylistClear(name string) error {
878 return c.Command("playlistclear %s", name).OK()
879 }
880
881 // PlaylistDelete deletes the song at position pos from the specified playlist.
882 func (c *Client) PlaylistDelete(name string, pos int) error {
883 return c.Command("playlistdelete %s %d", name, pos).OK()
884 }
885
886 // PlaylistMove moves a song identified by id in a playlist identified by name
887 // to the position pos.
888 func (c *Client) PlaylistMove(name string, id, pos int) error {
889 return c.Command("playlistmove %s %d %d", name, id, pos).OK()
890 }
891
892 // PlaylistRename renames the playlist identified by name to newName.
893 func (c *Client) PlaylistRename(name, newName string) error {
894 return c.Command("rename %s %s", name, newName).OK()
895 }
896
897 // PlaylistRemove removes the playlist identified by name from the playlist
898 // directory.
899 func (c *Client) PlaylistRemove(name string) error {
900 return c.Command("rm %s", name).OK()
901 }
902
903 // PlaylistSave saves the current playlist as name in the playlist directory.
904 func (c *Client) PlaylistSave(name string) error {
905 return c.Command("save %s", name).OK()
906 }
907
908 // A Sticker represents a name/value pair associated to a song. Stickers
909 // are managed and shared by MPD clients, and MPD server does not assume
910 // any special meaning in them.
911 type Sticker struct {
912 Name, Value string
913 }
914
915 func newSticker(name, value string) *Sticker {
916 return &Sticker{
917 Name: name,
918 Value: value,
919 }
920 }
921
922 func parseSticker(s string) (*Sticker, error) {
923 // Since '=' can appear in the sticker name and in the sticker value,
924 // it's impossible to determine where the name ends and value starts.
925 // Assume that '=' is more likely to occur in the value
926 // (e.g. base64 encoded data -- see #39).
927 i := strings.Index(s, "=")
928 if i < 0 {
929 return nil, textproto.ProtocolError("parsing sticker failed")
930 }
931 return newSticker(s[:i], s[i+1:]), nil
932 }
933
934 // StickerDelete deletes sticker for the song with given URI.
935 func (c *Client) StickerDelete(uri string, name string) error {
936 return c.Command("sticker delete song %s %s", uri, name).OK()
937 }
938
939 // StickerFind finds songs inside directory with URI which have a sticker with given name.
940 // It returns a slice of URIs of matching songs and a slice of corresponding stickers.
941 func (c *Client) StickerFind(uri string, name string) ([]string, []Sticker, error) {
942 attrs, err := c.Command("sticker find song %s %s", uri, name).AttrsList("file")
943 if err != nil {
944 return nil, nil, err
945 }
946 files := make([]string, len(attrs))
947 stks := make([]Sticker, len(attrs))
948 for i, attr := range attrs {
949 if _, ok := attr["file"]; !ok {
950 return nil, nil, textproto.ProtocolError("file attribute not found")
951 }
952 if _, ok := attr["sticker"]; !ok {
953 return nil, nil, textproto.ProtocolError("sticker attribute not found")
954 }
955 files[i] = attr["file"]
956 stk, err := parseSticker(attr["sticker"])
957 if err != nil {
958 return nil, nil, err
959 }
960 stks[i] = *stk
961 }
962 return files, stks, nil
963 }
964
965 // StickerGet gets sticker value for the song with given URI.
966 func (c *Client) StickerGet(uri string, name string) (*Sticker, error) {
967 attrs, err := c.Command("sticker get song %s %s", uri, name).Attrs()
968 if err != nil {
969 return nil, err
970 }
971 attr, ok := attrs["sticker"]
972 if !ok {
973 return nil, textproto.ProtocolError("sticker not found")
974 }
975 stk, err := parseSticker(attr)
976 if stk == nil {
977 return nil, err
978 }
979 return stk, nil
980 }
981
982 // StickerList returns a slice of stickers for the song with given URI.
983 func (c *Client) StickerList(uri string) ([]Sticker, error) {
984 attrs, err := c.Command("sticker list song %s", uri).AttrsList("sticker")
985 if err != nil {
986 return nil, err
987 }
988 stks := make([]Sticker, len(attrs))
989 for i, attr := range attrs {
990 s, ok := attr["sticker"]
991 if !ok {
992 return nil, textproto.ProtocolError("sticker attribute not found")
993 }
994 stk, err := parseSticker(s)
995 if err != nil {
996 return nil, err
997 }
998 stks[i] = *stk
999 }
1000 return stks, nil
1001 }
1002
1003 // StickerSet sets sticker value for the song with given URI.
1004 func (c *Client) StickerSet(uri string, name string, value string) error {
1005 return c.Command("sticker set song %s %s %s", uri, name, value).OK()
1006 }
1007
1008 // AlbumArt retrieves an album artwork image for a song with the given URI using MPD's albumart command.
1009 func (c *Client) AlbumArt(uri string) ([]byte, error) {
1010 offset := 0
1011 var data []byte
1012 for {
1013 // Read the data in chunks
1014 chunk, size, err := c.Command("albumart %s %d", uri, offset).Binary()
1015 if err != nil {
1016 return nil, err
1017 }
1018
1019 // Accumulate the data
1020 data = append(data, chunk...)
1021 offset = len(data)
1022 if offset >= size {
1023 break
1024 }
1025 }
1026 return data, nil
1027 }
1028
1029 // ReadPicture retrieves the embedded album artwork image for a song with the given URI using MPD's readpicture command.
1030 func (c *Client) ReadPicture(uri string) ([]byte, error) {
1031 offset := 0
1032 var data []byte
1033 for {
1034 // Read the data in chunks
1035 chunk, size, err := c.Command("readpicture %s %d", uri, offset).Binary()
1036 if err != nil {
1037 return nil, err
1038 }
1039
1040 // Accumulate the data
1041 data = append(data, chunk...)
1042 offset = len(data)
1043 if offset >= size {
1044 break
1045 }
1046 }
1047 return data, nil
1048 }