aboutsummaryrefslogtreecommitdiff
path: root/music/patch.go
blob: aba20ec9644445e3298623adbbeb3c55658dcab0 (plain)
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
package music

import (
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"strings"

	"github.com/delucks/go-subsonic"
	"github.com/jfbus/httprs"
)

// Stream2 patches subsonic.Client.Stream to return a ReadCloser for use with "beep"
func Stream2(s *subsonic.Client, id string, parameters map[string]string) (io.ReadCloser, error) {
	params := url.Values{}
	params.Add("id", id)
	for k, v := range parameters {
		params.Add(k, v)
	}
	response, err := s.Request("GET", "stream", params)
	if err != nil {
		return nil, err
	}
	contentType := response.Header.Get("Content-Type")
	if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
		// An error was returned
		responseBody, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return nil, err
		}
		resp := subsonic.Response{}
		err = xml.Unmarshal(responseBody, &resp)
		if err != nil {
			return nil, err
		}
		if resp.Error != nil {
			err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
		} else {
			err = fmt.Errorf("An error occurred: %#v\n", resp)
		}
		return nil, err
	}

	return httprs.NewHttpReadSeeker(response), nil
}

func Download2(s *subsonic.Client, id string) (io.ReadCloser, error) {
	params := url.Values{}
	params.Add("id", id)
	response, err := s.Request("GET", "download", params)
	if err != nil {
		return nil, err
	}
	contentType := response.Header.Get("Content-Type")
	if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
		// An error was returned
		responseBody, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return nil, err
		}
		resp := subsonic.Response{}
		err = xml.Unmarshal(responseBody, &resp)
		if err != nil {
			return nil, err
		}
		if resp.Error != nil {
			err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
		} else {
			err = fmt.Errorf("An error occurred: %#v\n", resp)
		}
		return nil, err
	}
	return httprs.NewHttpReadSeeker(response), nil
}