-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackend.js
236 lines (197 loc) · 6.17 KB
/
backend.js
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
const express = require("express");
const app = express();
const port = 3000;
const dotenv = require("dotenv");
dotenv.config({ path: '.env' });
const querystring = require('querystring');
const request = require('request');
const pg = require('pg');
const cors = require("cors");
const CONSTRING = process.env.CONSTRING;
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const PLAYLIST_ID = process.env.PLAYLIST_ID;
const redirect_uri = process.env.REDIRECT_URI;
const ReadWrite = require("./utils/data");
console.log(CLIENT_ID, CLIENT_SECRET, PLAYLIST_ID, CONSTRING);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const client = new pg.Client(CONSTRING);
let access_token;
let refresh_token;
let expires_in;
let delay = 5;
// Utility:
function generateRandomString(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
function convertToSpotifyURI(url) {
const trackID = url.split('/').pop().split('?')[0];
return `spotify:track:${trackID}`;
};
async function connectCLient(){
try{
await client.connect();
console.log("connected")
}
catch(err){
console.log("Could not connect:", err)
}
}
// Routes:
app.get("/", (req, res)=>{
res.send("Hi")
});
app.get('/login', function(req, res) {
let state = generateRandomString(16);
let scope = 'user-read-private user-read-email playlist-modify-public playlist-modify-private playlist-read-private playlist-read-collaborative';
console.log("login")
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: `${CLIENT_ID}`,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
});
const getRefreshToken = () => {
let refreshTokenRequest = {
url: 'https://accounts.spotify.com/api/token',
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token,
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + (new Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'))
},
json: true
};
return(refreshTokenRequest)
};
const accessTokenRefresher = ()=>{
a = setInterval(()=>{
expires_in -= 1;
// console.log(expires_in);
if (expires_in<=0){
// console.log("Timer Reached 0");
// console.log("Sending post request");
request.post(getRefreshToken(), function(error, response, body) {
if (!error && response.statusCode === 200) {
access_token = body.access_token
expires_in = body.expires_in
if(body.refresh_token){
refresh_token = body.refresh_token;
}
console.log(access_token, refresh_token);
}
});
}
}, 1000)
};
app.get('/callback', async function (req, res) {
let code = req.query.code || null;
let state = req.query.state || null;
if (state === null) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
await connectCLient();
let authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'content-type': ' ',
'Authorization': 'Basic ' + (new Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'))
},
json: true
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
access_token = body.access_token;
refresh_token = body.refresh_token;
expires_in = body.expires_in;
res.send('Authentication successful! Access token: PRIVATE' +"<br>"+ expires_in +"<br>");
console.log("Access Token:\n", access_token)
startAddingSpotifySongs(access_token);
accessTokenRefresher();
} else {
res.status(response.statusCode).send('Error: ' + error);
}
});
}
});
// Adding songs to playlist
app.post("/add", async (req, res)=>{
console.log(req.body)
let {url, email} = req.body;
console.log(email);
let uri = convertToSpotifyURI(url);
// checkInfo :
// 0 if correct
// 1 if duplicate uri
// 2 if user rate limited
let temp = await ReadWrite.checkInfo(client, uri, email);
console.log(temp)
if( temp === 1){
console.log("already exits");
res.status(409).send({ message: "The song is already in the playlist." });
}
else if(temp === 2){
console.log("Slow down send request after some time (not been 5 mins since last request)")
res.status(429).send({ message: "You are being rate limited. Please try again later." });
}
else{
res.status(200).send({ message: "Song added to the playlist." });
ReadWrite.Write(client, `${uri}`, email);
}
})
const startAddingSpotifySongs = (access_token)=>{
addSpotifySongs = setInterval(async ()=>{
songList = await ReadWrite.Read(client);
// console.log(songList)
// if (songList.length === 0) {
// console.log("is 0\n",songList, songList.length);
// }
if(1===0){}
else{
let authOptions = {
url: `https://api.spotify.com/v1/playlists/${PLAYLIST_ID}/tracks`,
body: {
uris: songList
},
headers: {
Authorization: 'Bearer ' + access_token
},
json: true
};
// console.log(authOptions.headers, authOptions.body.uris)
// console.log(songList)
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
let snapshot_id = body.snapshot_id;
console.log("Added!!\n", snapshot_id)
} else {
console.error('Error: ' + error);
}
});
}
}, 1000*delay)
}
app.listen(port, '0.0.0.0', () => {
console.log(`Example app listening on port: ${port}`);
});