@@ -7,15 +7,15 @@ const calcNextSong = (queue) => {
7
7
return { newQueue : queue , newNextSong : max_votes }
8
8
}
9
9
10
- const addNextSongToSpotify = ( uri , spotify_auth_token , wss , WebSocket ) => {
10
+ const addNextSongToSpotify = ( uri , spotify_auth_token , wss , WebSocket , device_id = false ) => {
11
11
12
12
const config = {
13
13
headers : { Authorization : `Bearer ${ spotify_auth_token } ` }
14
14
} ;
15
15
16
- const body = {
17
- uri
18
- }
16
+
17
+ let body
18
+ device_id ? body = { uri , device_id } : body = { uri }
19
19
20
20
axios . post ( "https://api.spotify.com/v1/me/player/queue?" + new URLSearchParams ( body ) , { } , config ) . then ( res => {
21
21
console . log ( "Added song to queue" )
@@ -27,20 +27,78 @@ const addNextSongToSpotify = (uri, spotify_auth_token, wss, WebSocket) => {
27
27
return true
28
28
} ) . catch ( err => {
29
29
console . log ( "added song error:" )
30
- console . log ( err )
31
- return false
30
+ if ( err . response . data . error . reason === "NO_ACTIVE_DEVICE" ) {
31
+ getSpotifyDevices ( spotify_auth_token , ( device_error , device_result ) => {
32
+ if ( device_error ) {
33
+ return false
34
+ } else {
35
+ const { devices} = device_result
36
+ if ( devices . length < 1 ) return false
37
+ let id
38
+ let found = false
39
+ for ( let i = 0 ; i < devices . length ; i ++ ) {
40
+ if ( devices [ i ] . type === "Smartphone" ) {
41
+ id = devices [ i ] . id
42
+ found = true
43
+ break
44
+ }
45
+ }
46
+ if ( found ) return addNextSongToSpotify ( uri , spotify_auth_token , wss , WebSocket , id )
47
+
48
+ for ( let i = 0 ; i < devices . length ; i ++ ) {
49
+ if ( devices [ i ] . type === "Computer" ) {
50
+ id = devices [ i ] . id
51
+ found = true
52
+ break
53
+ }
54
+ }
55
+ if ( found ) return addNextSongToSpotify ( uri , spotify_auth_token , wss , WebSocket , id )
56
+ return addNextSongToSpotify ( uri , spotify_auth_token , wss , WebSocket , devices [ 0 ] . id )
57
+
58
+ }
59
+ } )
60
+ } else {
61
+ return false
62
+ }
63
+
32
64
} )
65
+
66
+
33
67
68
+
34
69
35
70
}
36
71
37
72
38
- const newAuthToken = ( ) => {
73
+
74
+ const getSpotifyDevices = ( spotify_auth_token , _callback ) => {
75
+
76
+ const config = {
77
+ headers : { Authorization : `Bearer ${ spotify_auth_token } ` }
78
+ } ;
79
+
80
+ axios . get ( "https://api.spotify.com/v1/me/player/devices" , config ) . then ( res => {
81
+
82
+ console . log ( res . data )
83
+ _callback ( false , res . data )
84
+
85
+ } ) . catch ( err => {
86
+ console . log ( "ERR1" )
87
+ console . log ( err )
88
+ if ( err . response ) {
89
+ _callback ( err . response . status , undefined )
90
+ } else {
91
+ _callback ( true , undefined )
92
+ }
93
+ } )
94
+
95
+
39
96
40
97
}
41
98
42
99
43
100
module . exports = {
44
101
calcNextSong,
45
- addNextSongToSpotify
102
+ addNextSongToSpotify,
103
+ getSpotifyDevices
46
104
}
0 commit comments