forked from Thyraz/Sonos-Kids-Controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (71 loc) · 2.32 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
85
86
87
// Setup
const express = require('express');
const cors = require('cors');
const app = express();
const path = require('path');
const jsonfile = require('jsonfile');
var SpotifyWebApi = require('spotify-web-api-node');
const config = require('./server/config/config.json');
app.use(cors());
var spotifyApi = new SpotifyWebApi({
clientId: config.spotify.clientId,
clientSecret: config.spotify.clientSecret
});
// Configuration
const dataFile = './server/config/data.json'
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'www'))); // Static path to compiled Ionic app
// Routes
app.get('/api/data', (req, res) => {
jsonfile.readFile(dataFile, (error, data) => {
if (error) data = [];
res.json(data);
});
});
app.post('/api/add', (req, res) => {
jsonfile.readFile(dataFile, (error, data) => {
if (error) data = [];
data.push(req.body);
jsonfile.writeFile(dataFile, data, { spaces: 4 }, (error) => {
if (error) throw err;
res.status(200).send();
});
});
});
app.post('/api/delete', (req, res) => {
jsonfile.readFile(dataFile, (error, data) => {
if (error) data = [];
data.splice(req.body.index, 1);
jsonfile.writeFile(dataFile, data, { spaces: 4 }, (error) => {
if (error) throw err;
res.status(200).send();
});
});
});
app.get('/api/token', (req, res) => {
// Retrieve an access token from Spotify
spotifyApi.clientCredentialsGrant().then(
function(data) {
res.status(200).send(data.body['access_token']);
},
function(err) {
console.log(
'Something went wrong when retrieving a new Spotify access token',
err.message
);
res.status(500).send(err.message);
}
);
});
app.get('/api/sonos', (req, res) => {
// Send server address and port of the node-sonos-http-api instance to the client
res.status(200).send(config['node-sonos-http-api']);
});
// Catch all other routes and return the index file from Ionic app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'www/index.html'));
});
// listen (start app with 'node server.js')
app.listen(8200);
console.log("App listening on port 8200");