-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
311 lines (267 loc) · 12.6 KB
/
api.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
var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var pool = require('./lib/utils').pool;
var utils = require('./lib/utils');
var app = express();
// use some express packages
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static(`${__dirname}/views`));
const listener = app.listen(process.env.PORT, function() {
console.log(`The server is listening on port: ${listener.address().port}`);
});
/***********************************/
/* CLIENT ENDPOINTS */
/***********************************/
// ROOT PAGE
app.get('/', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/index.html`);
});
app.get('/addSong', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/addSong.html`);
});
app.get('/searchSongsByTitle', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/listSongsByTitles.html`);
});
app.get('/searchSongsByArtist', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/listSongsByArtists.html`);
});
app.get('/showSong', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/showSong.html`);
});
app.get('/editSong', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/editSong.html`);
});
app.get('/register', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/register.html`);
});
app.get('/deleteAccount', function(request, response) {
response.status(200).sendFile(`${__dirname}/views/deleteAccount.html`);
});
/********************************/
/* API ENDPOINTS */
/********************************/
// Register in the API.
app.post('/api/join', async function(request, response) {
var username = request.headers.username.split("'").join("`");
var password = request.headers.password.split("'").join("`");
if (!await utils.validateUsername(username))
response.status(422).send(`Username not available.`);
else if (!utils.validatePassword(password))
response.status(422).send(`Wrong password format.`);
else {
var queryString = `INSERT INTO public."Users" (username, password) ` +
`VALUES ('${username}', '${password}')`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else {
console.log(`New account created: ` + username);
response.status(200).send(`${username}, registration successful.`);
}
});
}
});
// Delete account in the API.
app.delete('/api/deleteAccount', function (request, response) {
var username = request.headers.username.split("'").join("`");
var password = request.headers.password.split("'").join("`");
var queryString = `DELETE FROM public."Users" WHERE username='${username}' AND password='${password}'`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else
if (result.rowCount > 0) {
console.log(`${username} deleted.`);
response.status(200).send(`${username} deleted.`);
}
else {
console.log(`${request.ip} tried to delete the account: ${username}`);
response.status(401).send(`Authentication Failed: invalid username and/or password.`);
}
});
})
// Add a new song in the API.
app.post('/api/addSong', async function(request, response) {
var title = request.body.title.split("'").join("`");
var artist = request.body.artist.split("'").join("`");
var tuning = request.body.tuning.split("'").join("`");
var capo = request.body.capo.split("'").join("`");
var note = request.body.note.split("'").join("`");
var content = request.body.content.split("'").join("`");
var username = request.headers.username;
var password = request.headers.password;
if (!await utils.validateAuth(username, password))
response.status(401).send(`Authentication Failed: invalid username and/or password.`);
else if (!await utils.validateSong(title, artist))
response.status(403).send(`The song already exists.`);
else {
var queryString = `INSERT INTO public."Songs" (title, username_fk, artist, tuning, capo, note, content) ` +
`VALUES ('${[title, username, artist, tuning, capo, note, content].join('\',\'')}')`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else {
console.log(`${username} added: ${title} by ${artist}`);
response.status(200).send(`Song successfully added.`);
}
});
}
});
// Edit a song in the API.
app.put('/api/song/:artist/:title', async function(request, response) {
var title = request.params.title.split("`").join("'");
var artist = request.params.artist.split("`").join("'");
var tuning = request.body.tuning.split("'").join("`");
var capo = request.body.capo.split("'").join("`");
var note = request.body.note.split("'").join("`");
var content = request.body.content.split("'").join("`");
var username = request.headers.username.split("'").join("`");
var password = request.headers.password.split("'").join("`");
if (await utils.validateSong(title, artist))
response.status(404).send(`Song not found.`);
else if (await utils.getUserFromTitle(title) != username)
response.status(403).send(`The user: ${username}, does not have permission to edit the song.`);
else if (!await utils.validateAuth(username, password))
response.status(401).send(`Authentication Failed: invalid username and/or password.`);
else {
var queryString = `UPDATE public."Songs" ` +
`SET artist='${artist}', tuning='${tuning}', capo='${capo}', note='${note}', content='${content}' ` +
`WHERE title='${title}'`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else {
console.log(`${username} edited: ${title} by ${artist}`);
response.status(200).send(`Song successfully edited.`);
}
});
}
});
// Delete a song in the API.
app.delete('/api/song/:artist/:title', async function(request, response) {
var title = request.params.title.split("`").join("'");
var artist = request.params.artist.split("`").join("'");
var username = request.headers.username.split("'").join("`");
var password = request.headers.password.split("'").join("`");
if (await utils.validateSong(title, artist))
response.status(404).send('Song not found.');
else if (await utils.getUserFromTitle(title) != username)
response.status(403).send(`The user: ${username}, does not have permission to delete the song.`);
else if (!await utils.validateAuth(username, password))
response.status(401).send(`Authentication Failed: invalid username and/or password.`);
else {
var queryString = `DELETE FROM public."Songs" WHERE title='${title}' AND username_fk='${username}'`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else {
console.log(`${username} deleted: ${title} by ${artist}`);
response.status(200).send(`Song successfully deleted.`);
}
});
}
});
// Get a song from the API
app.get('/api/song/:artist/:title', async function(request, response) {
var title = request.params.title.split("`").join("'");
var artist = request.params.artist.split("`").join("'");
var queryString = `SELECT * FROM public."Songs" WHERE title='${title.split("'").join("`")}' AND artist='${artist.split("'").join("`")}'`;
var path = `/api/v1/json/${process.env.APIKEY}/searchtrack.php?s=${artist.split("`").join("`")}&t=${title.split("`").join("'")}`;
var options = {
host: 'theaudiodb.com',
path: path.split(" ").join("%20")
}
try {
var result_query = await pool.query(queryString);
if (result_query.rowCount > 0) {
// Request for extra data from the API theaudiodb.com
var request = https.get(options, function (result) {
result.on('data', function(data) {
// processing data from external API.
data = JSON.parse(data);
var song_obj = {
title: result_query.rows[0].title,
artist: result_query.rows[0].artist,
tuning: result_query.rows[0].tuning,
capo: result_query.rows[0].capo,
note: result_query.rows[0].note,
content: result_query.rows[0].content,
owner: result_query.rows[0].username_fk,
album: null,
trackNo: null,
genre: null,
musicVid: null
}
if (data.track) {
song_obj.album = data.track[0].strAlbum;
song_obj.trackNo = data.track[0].intTrackNumber;
song_obj.genre = data.track[0].strGenre;
song_obj.musicVid = data.track[0].strMusicVid;
}
response.status(200).send(song_obj);
});
});
request.on('error', function(error) {
console.error(e);
});
request.end();
} else response.status(404).send('Song not found.');
} catch (error) {
console.log(error);
response.status(400).send(error);
}
});
// Get a list of songs available in the API.
app.get('/api/songs', function(request, response) {
var queryString = `SELECT title, artist FROM public."Songs" ` +
`ORDER BY title ASC, artist ASC`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else if (result.rowCount > 0) {
response.status(200).send(result.rows);
} else response.status(404).send('Songs not found.');
});
});
// Get a filtered list of songs by artist or title.
app.post('/api/songs/search', function(request, response) {
var artist = request.query.artist;
var title = request.query.title;
if (artist != undefined & title == undefined) {
var queryString = `SELECT title, artist FROM public."Songs" ` +
`WHERE artist ILIKE '${artist.split("'").join("`")}'` +
`ORDER BY title ASC, artist ASC`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else if (result.rowCount > 0) {
response.status(200).send(result.rows);
} else response.status(404).send('Songs not found.');
});
} else if (artist == undefined & title != undefined){
var queryString = `SELECT title, artist FROM public."Songs" ` +
`WHERE title ILIKE '${title.split("'").join("`")}' ` +
`ORDER BY title ASC, artist ASC`;
pool.query(queryString, function(error, result) {
if (error) {
console.log(error);
response.status(400).send(error);
} else if (result.rowCount > 0) {
response.status(200).send(result.rows);
} else response.status(404).send('Songs not found.');
});
} else if (artist == undefined & title == undefined) {
response.status(400).send('Too few arguments.');
} else {
response.status(400).send('Too many arguments.');
}
});