-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
80 lines (68 loc) · 2.11 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
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const authorizeSpotify = require('./authorizeSpotify');
const getAccessToken = require('./getAccessToken');
const refreshAccessToken = require('./refreshAccessToken');
const getRecentlyPlayed = require('./getRecentlyPlayed');
const Datastore = require('nedb');
const cron = require('node-cron');
const Pusher = require('pusher');
const clientUrl = process.env.CLIENT_URL;
const app = express();
const db = new Datastore();
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/login', authorizeSpotify);
app.get('/callback', getAccessToken, (req, res, next) => {
db.insert(req.credentials, err => {
if (err) {
next(err);
} else {
res.redirect(`${clientUrl}/?authorized=true`);
}
});
});
app.get('/history', (req, res) => {
db.find({}, (err, docs) => {
if (err) {
throw Error('Failed to retrieve documents');
}
const accessToken = docs[0].access_token;
getRecentlyPlayed(accessToken)
.then(data => {
const arr = data.map(e => ({
played_at: e.played_at,
track_name: e.track.name,
}));
res.json(arr);
})
.then(() => {
cron.schedule('*/5 * * * *', () => {
getRecentlyPlayed(accessToken).then(data => {
const arr = data.map(e => ({
played_at: e.played_at,
track_name: e.track.name,
}));
pusher.trigger('spotify', 'update-history', {
musicHistory: arr,
});
});
});
})
.catch(err => console.log(err));
});
});
app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});