-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
343 lines (289 loc) · 10.1 KB
/
app.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
* This is an example of a basic node.js script that performs
* the Authorization Code oAuth2 flow to authenticate against
* the Spotify Accounts.
*
* For more information, read
* https://developer.spotify.com/documentation/web-api/tutorials/code-flow
*/
var express = require('express');
var request = require('request');
var crypto = require('crypto');
var cors = require('cors');
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
var OpenAI = require('openai');
var SpotifyWebApi = require('spotify-web-api-node');
var HttpsProxyAgent = require('https-proxy-agent');
// const { createProxyMiddleware } = require('http-proxy-middleware');
// import { HttpProxyAgent } from 'http-proxy-agent';
// import express from 'express';
// import request from 'request';
// import crypto from 'crypto';
// import cors from 'cors';
// import querystring from 'querystring';
// import cookieParser from 'cookie-parser';
// import OpenAI from 'openai';
// import SpotifyWebApi from 'spotify-web-api-node';
// import HttpsProxyAgent from 'https-proxy-agent';
// const spotifyApi = new SpotifyWebApi();
const client_id = process.env.SPOTIFY_CLIENT_ID; // your clientId
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const BACKEND_ROUTE = "https://snobbify-backend.onrender.com";
const FRONTEND_ROUTE = "https://snobbify.onrender.com";
// const redirect_uri = 'http://localhost:8888/callback'; // Your redirect uri
const redirect_uri = BACKEND_ROUTE + '/callback'; // Your redirect uri
// const apiProxy = createProxyMiddleware({ target: 'https://api.openai.com/v1/chat/completions'});
// const openai = new OpenAI({
// apiKey: process.env.OPENAI_API_KEY,
// httpAgent: new HttpsProxyAgent.HttpsProxyAgent("https://api.openai.com/v1/chat/completions")});
const openai = new OpenAI({apiKey: process.env.OPENAI_API_KEY});
const generateRandomString = (length) => {
return crypto
.randomBytes(60)
.toString('hex')
.slice(0, length);
}
var stateKey = 'spotify_auth_state';
var app = express();
var corsOptions = function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers',
'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
}
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser())
.use(express.json());
// app.use(['/roastArtists', '/roastTracks'], cors(corsOptions));
app.get('/login', function(req, res) {
var state = generateRandomString(16);
res.cookie(stateKey, state);
// your application requests authorization
var scope = 'user-read-private user-read-email user-read-playback-state user-top-read';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
});
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
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) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect(FRONTEND_ROUTE + '/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect(FRONTEND_ROUTE + '/#' +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
});
app.get('/refresh_token', function(req, res) {
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
res.send({
'access_token': access_token,
'refresh_token': refresh_token
});
}
});
});
// ROASTING ENDPOINTS ------------------------
// used a POST request because didn't want to expose artists in URL
// and concerned about account data fiddling
app.post('/roastArtists', async function(req, res) {
// TODO: implement try/catch so server doesn't just crash lmfao
// console.log(req.body);
let topArtists = req.body.topArtists;
let topArtistsStr = "{" + topArtists.join(", ") + "}";
// console.log("generateRoast, topArtists:", topArtists);
// console.log("generateRoast:",topArtistsStr);
// console.log("sending to chatGPT...")
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: process.env.ARTISTS_PROMPT },
{ role: "user", content: topArtistsStr}
],
model: "gpt-3.5-turbo",
});
// console.log("finished!")
// console.log(completion.choices[0]);
res.send({
gpt_response: completion.choices[0]
})
// console.log("GPT response:", completion.choices[0]);
});
app.post('/sample', async function(req, res) {
try {
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: process.env.TRACKS_PROMPT },
{ role: "user", content: "{Aphex Twin}"}
],
model: "gpt-3.5-turbo",
});
console.log(completion.choices[0]);
return res.status(200);
} catch (error) {
console.log(error);
}
});
// used a POST request because didn't want to expose artists in URL
// and concerned about account data fiddling
app.post('/roastTracks', async function(req, res) {
try {
// TODO: implement try/catch so server doesn't just crash lmfao
// console.log(req.body);
let topTracks = req.body
let topTracksStr = JSON.stringify(topTracks);
console.log("topTracks:", topTracks);
console.log("topTrackStr:",topTracksStr);
console.log("sending to chatGPT...")
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: process.env.TRACKS_PROMPT },
{ role: "user", content: topTracksStr}
],
model: "gpt-3.5-turbo",
});
// let gptHeaders = new Headers({
// 'Content-Type': 'application/json',
// 'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY
// });
// // manual fetch
// const completion = await fetch("https://api.openai.com/v1/chat/completions", {
// method: "POST",
// headers: headers,
// body: JSON.stringify({
// model: "gpt-3.5-turbo",
// messages: [
// { role: "system", content: process.env.TRACKS_PROMPT },
// { role: "user", content: topTracksStr}
// ]
// })
// })
// .then((completion) => {
// res.send({
// gpt_response: completion.choices[0]
// // gpt_response: {"message" : { "content" : topTracksStr}}
// })
// }, function(err) {
// console.log('Something went wrong!', err);
// })
console.log("finished!")
console.log(completion.choices[0]);
res.send({
gpt_response: completion.choices[0]
// gpt_response: {"message" : { "content" : topTracksStr}}
})
// console.log("GPT response:", completion.choices[0]);
} catch (error) {
console.log(error);
}
});
/**
* deprecated
*/
app.get('/getPlaying', async function(req, res) {
const authHeader = req.header("Authorization");
// console.log("Request:", req);
// console.log("header:", authHeader)
let accessToken = undefined
// TODO: this is VERY insecure
if (authHeader.startsWith("Bearer ")){
accessToken = authHeader.substring(7, authHeader.length);
} else {
res.send(200);
}
console.log("Access token:", accessToken);
// Set the credentials when making the request
let spotifyApi = new SpotifyWebApi({
accessToken: accessToken
});
console.log("Reading playback...")
const spotifyRes = spotifyApi.getMyCurrentPlaybackState().then(
function(data) {
console.log("Playback data retrieved. Start of data:")
console.log(data.body);
console.log("End of data ---")
const name = data.body.item.name;
const albumArt = data.body.item.album.images[0].url;
// console.log("again:",spotifyRes);
console.log("name:", name);
console.log("albumArt:", albumArt);
// TODO: how to correctly send this data back??
res.send({
'name': name,
'album_art': albumArt
})
},
function(err) {
console.log('Something went wrong!', err);
}
);
})
console.log('Listening on 8888');
app.listen(8888);