-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
84 lines (73 loc) · 2.25 KB
/
server.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
const express = require('express')
const app = express()
const http = require('http').Server(app)
const bodyParser = require('body-parser')
const request = require('request')
const refresh = require('spotify-refresh')
const Spotify = require('spotify-web-api-node')
require('dotenv').config()
const spotify = new Spotify()
spotify.setRefreshToken(process.env.REFRESH_TOKEN)
spotify.setClientId(process.env.CLIENT_ID)
spotify.setClientSecret(process.env.CLIENT_SECRET)
function getIDfromUri(uri) {
const split = uri.split(/[:\"]+/)
return split[3]
}
const post = uri =>
request.post({
url: `https://api.spotify.com/v1/playlists/5dPp7yV9i8mELe1Kk9UC6D/tracks?uris=spotify%3Atrack%3A${getIDfromUri(
uri
)}`,
headers: {
Authorization: `Bearer ${spotify.getAccessToken()}`,
Host: 'api.spotify.com',
Accept: 'application/json',
'Content-Type': 'application/json',
'Content-Length': 0
},
json: true
})
app.use('/public', express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post('/song', (req, res) => {
const track = req.body.submiturl.replace(/\'/g, '')
const artist = req.body.submitartist.replace(/\'/g, '')
spotify
.searchTracks(artist != '' ? `track:${track} artist:${artist}` : track)
.then(
data => {
const uri = JSON.stringify(data.body['tracks']['items'][0]['uri'])
const isExplicit = JSON.stringify(
data.body['tracks']['items'][0]['explicit']
)
if (isExplicit === 'true') {
console.log(`requested song ${track} not added because it's explicit`)
return res.sendFile(__dirname + '/index.html')
} else {
post(uri)
console.log(`added ${track} to the playlist!`)
return res.sendFile(__dirname + '/added.html')
}
},
err => {
console.log(err)
}
)
})
app.get('/', (err, res) => {
res.sendFile(`${__dirname}/index.html`)
spotify.refreshAccessToken().then(
data => {
spotify.setAccessToken(data.body['access_token'])
},
err => {
console.log('Could not refresh access token', err)
}
)
})
app.get('/added', (err, res) => {
res.sendFile(`${__dirname}/added.html`)
})
http.listen(3000)