forked from badfortrains/spotcontrol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery.go
308 lines (266 loc) · 7.18 KB
/
discovery.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package spotcontrol
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/badfortrains/mdns"
"log"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"net"
)
type connectInfo struct {
DeviceID string `json:"deviceID"`
PublicKey string `json:"publicKey"`
}
type connectDeviceMdns struct {
path string
name string
}
type getInfo struct {
Status int `json:"status"`
StatusError string `json:"statusError"`
SpotifyError int `json:"spotifyError"`
Version string `json:"version"`
DeviceID string `json:"deviceID"`
RemoteName string `json:"remoteName"`
ActiveUser string `json:"activeUser"`
PublicKey string `json:"publicKey"`
DeviceType string `json:"deviceType"`
LibraryVersion string `json:"libraryVersion"`
AccountReq string `json:"accountReq"`
BrandDisplayName string `json:"brandDisplayName"`
ModelDisplayName string `json:"modelDisplayName"`
}
type discovery struct {
keys privateKeys
cachePath string
loginBlob BlobInfo
deviceId string
deviceName string
mdnsServer *mdns.Server
httpServer *http.Server
devices []connectDeviceMdns
devicesLock sync.RWMutex
}
func makeGetInfo(deviceId, deviceName, publicKey string) getInfo {
return getInfo{
Status: 101,
StatusError: "ERROR-OK",
SpotifyError: 0,
Version: "1.3.0",
DeviceID: deviceId,
RemoteName: deviceName,
ActiveUser: "",
PublicKey: publicKey,
DeviceType: "UNKNOWN",
LibraryVersion: "0.1.0",
AccountReq: "PREMIUM",
BrandDisplayName: "librespot",
ModelDisplayName: "librespot",
}
}
// Advertise spotify service via mdns. Waits for user
// to connect to 'spotcontrol' device. Extracts login data
// and returns login BlobInfo.
func BlobFromDiscovery(deviceName string) *BlobInfo {
deviceId := generateDeviceId(deviceName)
d := loginFromConnect("", deviceId, deviceName)
return &d.loginBlob
}
func loginFromConnect(cachePath, deviceId string, deviceName string) *discovery {
d := discovery{
keys: generateKeys(),
cachePath: cachePath,
deviceId: deviceId,
deviceName: deviceName,
}
done := make(chan int)
l, err := net.Listen("tcp", ":8000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
go d.startHttp(done, l)
d.startDiscoverable()
<-done
return &d
}
func discoveryFromBlob(blob BlobInfo, cachePath, deviceId string, deviceName string) *discovery {
d := discovery{
keys: generateKeys(),
cachePath: cachePath,
deviceId: deviceId,
loginBlob: blob,
deviceName: deviceName,
}
d.FindDevices()
return &d
}
func loginFromFile(cachePath, deviceId string, deviceName string) *discovery {
blob, err := blobFromFile(cachePath)
if err != nil {
log.Fatal("failed to get blob from file")
}
return discoveryFromBlob(blob, cachePath, deviceId, deviceName)
}
func makeAddUserRequest(username string, blob string, key string, deviceId string, deviceName string) url.Values {
v := url.Values{}
v.Set("action", "addUser")
v.Add("userName", username)
v.Add("blob", blob)
v.Add("clientKey", key)
v.Add("deviceId", deviceId)
v.Add("deviceName", deviceName)
return v
}
func findCpath(info []string) string {
for _, i := range info {
if strings.Contains(i, "CPath") {
return strings.Split(i, "=")[1]
}
}
return ""
}
func (d *discovery) FindDevices() {
ch := make(chan *mdns.ServiceEntry, 10)
d.devices = make([]connectDeviceMdns, 0)
go func() {
for entry := range ch {
cPath := findCpath(entry.InfoFields)
url := fmt.Sprintf("http://%v:%v%v", entry.AddrV4, entry.Port, cPath)
fmt.Println("Found a device", entry)
d.devicesLock.Lock()
d.devices = append(d.devices, connectDeviceMdns{
path: url,
name: strings.Replace(entry.Name, "._spotify-connect._tcp.local.", "", 1),
})
fmt.Println("devices", d.devices)
d.devicesLock.Unlock()
}
fmt.Println("closed")
}()
err := mdns.Lookup("_spotify-connect._tcp.", ch)
if err != nil {
log.Fatal("lookup error", err)
}
}
func (d *discovery) ConnectToDevice(address string) {
resp, err := http.Get(address + "?action=getInfo")
resp, err = http.Get(address + "?action=resetUsers")
resp, err = http.Get(address + "?action=getInfo")
fmt.Println("start get")
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
info := connectInfo{}
err = decoder.Decode(&info)
if err != nil {
panic("bad json")
}
fmt.Println("resposne", resp)
client64 := base64.StdEncoding.EncodeToString(d.keys.pubKey())
blob, err := d.loginBlob.makeAuthBlob(info.DeviceID,
info.PublicKey, d.keys)
if err != nil {
panic("bad blob")
}
body := makeAddUserRequest(d.loginBlob.Username, blob, client64, d.deviceId, d.deviceName)
resp, err = http.PostForm(address, body)
defer resp.Body.Close()
decoder = json.NewDecoder(resp.Body)
var f interface{}
err = decoder.Decode(&f)
fmt.Println("got", f, resp, err)
}
func (d *discovery) handleAddUser(r *http.Request) error {
//already have login info, ignore
if d.loginBlob.Username != "" {
return nil
}
username := r.FormValue("userName")
client64 := r.FormValue("clientKey")
blob64 := r.FormValue("blob")
if username == "" || client64 == "" || blob64 == "" {
log.Println("Bad request, addUser")
return errors.New("Bad username request")
}
blob, err := newBlobInfo(blob64, client64, d.keys,
d.deviceId, username)
if err != nil {
return errors.New("failed to decode blob")
}
err = blob.saveToFile(d.cachePath)
if err != nil {
log.Println("failed to cache login info")
}
d.loginBlob = blob
d.mdnsServer.Shutdown()
return nil
}
func (d *discovery) startHttp(done chan int, l net.Listener) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
action := r.FormValue("action")
fmt.Println("got request: ", action)
switch {
case "getInfo" == action || "resetUsers" == action:
client64 := base64.StdEncoding.EncodeToString(d.keys.pubKey())
info := makeGetInfo(d.deviceId, d.deviceName, client64)
js, err := json.Marshal(info)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
case "addUser" == action:
err := d.handleAddUser(r)
if err == nil {
done <- 1
}
}
})
d.httpServer = &http.Server{}
err := d.httpServer.Serve(l)
if err != nil {
fmt.Println("got an error", err)
}
}
func (d *discovery) startDiscoverable() {
fmt.Println("start discoverable")
info := []string{"VERSION=1.0", "CPath=/"}
ifaces, err := net.Interfaces()
// handle err
ips := make([]net.IP, 0)
for _, i := range ifaces {
addrs, _ := i.Addrs()
// handle err
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ips = append(ips, v.IP)
case *net.IPAddr:
ips = append(ips, v.IP)
}
fmt.Println("found ip ", ips)
// process IP address
}
}
service, err := mdns.NewMDNSService("spotcontrol"+strconv.Itoa(rand.Intn(200)),
"_spotify-connect._tcp", "", "", 8000, ips, info)
if err != nil {
fmt.Println(err)
log.Fatal("error starting discovery")
}
server, err := mdns.NewServer(&mdns.Config{
Zone: service,
})
if err != nil {
log.Fatal("error starting discovery")
}
d.mdnsServer = server
}