-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
346 lines (287 loc) · 10.7 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
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
344
345
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const path = require('path');
const mongoose = require('mongoose');
const port = process.env.port || 8080;
const flash = require('connect-flash');
const { ensureAuthenticated } = require("./middleware/check_auth");
require("dotenv").config()
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const Purchase = require("./models/purchaseModel").Purchase;
let user_music_items = []
// let test_music_items = new Map(user_music_items)
let test_music_items = null
const app = express();
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
//possible need to reconfigure session details
app.use(
session({
secret: "secret", // rename secret to secure password
reverse: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false,
maxAge: 24 * 60 * 60 * 1000,
},
})
);
const authRoute = require("./routes/authRoute");
const indexRoute = require("./routes/indexRoute");
const checkoutRoute = require("./routes/checkoutRoute");
const profileRoute = require("./routes/profileRoute");
const adminRoute = require("./routes/adminRoute");
const helpRoute = require("./routes/helpRoute");
const { SecretsManager } = require('aws-sdk');
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next) => {
console.log(req.session.passport);
next();
});
app.use(flash());
app.use("/", indexRoute);
app.use("/auth", authRoute);
app.use("/edit-profile", profileRoute);
app.use("/admin", adminRoute);
app.use("/help", helpRoute);
app.get("/checkout", (req, res) => {
res.render("checkout", { data: {music_info: user_music_items}})
user_music_items = []
});
app.get("/payment_success", (req, res) => res.render('payment_success'));
app.get("/payment_cancel", (req, res) => res.render('payment_cancel'));
app.get('/checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.retrieve(req.query.id, {expand:['line_items']});
res.json({session});
});
// Stripe checkout session
app.post('/create-checkout-session', async (req, res) => {
try {
const taxRates = await stripe.taxRates.create({
display_name: 'Sales Tax',
inclusive: false,
percentage: 23,
country: 'PL',
});
// console.log(taxRates)
// console.log(req.body.items2)
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
line_items: req.body.items.map(item => {
const music_item = test_music_items.get(item.id)
addtoPlaylist('5ip8XW3DeB2ozaKDVxEmGN', music_item.track_uri)
return {
price_data: {
currency: 'cad',
product_data: {
name: `${music_item.artist_name}: ${music_item.song_name}`
},
unit_amount: process.env.PRICE
},
quantity: 1,
tax_rates: [taxRates.id]
}
}),
success_url: `${process.env.SERVER_URL}/payment_success?id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.SERVER_URL}/payment_cancel?id={CHECKOUT_SESSION_ID}`
})
res.json({ url: session.url,
id : session.id })
} catch (e) {
res.status(500).json({ error: e.message })
}
});
// Save purchase data into MonogDB
// INSTRUCTION:
// - type "stripe listen --forward-to localhost:8000/webhook" IN DIFFERENT TERMINAL
app.post('/webhook', express.json({type: 'application/json'}), (request, response) => {
const event = request.body;
let time = Date.now()
let _id = null
let _name = null
let _email = null
let _amount_received = null
let _receipt_url = null
let _currency = null
// Handle the event
switch (event.type) {
case 'charge.succeeded':
let charge = event.data.object;
const purchase = new Purchase({
id: charge.id,
email: charge.billing_details.email,
name: charge.billing_details.name,
amount_received: charge.amount,
currency: charge.currency,
receipt_url: charge.receipt_url
});
purchase.save()
break;
default:
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
});
// connect to mongodb
// Load the AWS SDK
// var AWS = require('aws-sdk'),
// region = "us-east-1",
// secretName = "arn:aws:secretsmanager:us-east-1:905552511425:secret:DB2-f6fAr0",
// secret,
// decodedBinarySecret;
// // Create a Secrets Manager client
// var client = new AWS.SecretsManager({
// region: region
// });
// // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
// // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
// // We rethrow the exception by default.
// client.getSecretValue({SecretId: secretName}, function(err, data) {
// if (err) {
// if (err.code === 'DecryptionFailureException')
// // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
// // Deal with the exception here, and/or rethrow at your discretion.
// throw err;
// else if (err.code === 'InternalServiceErrorException')
// // An error occurred on the server side.
// // Deal with the exception here, and/or rethrow at your discretion.
// throw err;
// else if (err.code === 'InvalidParameterException')
// // You provided an invalid value for a parameter.
// // Deal with the exception here, and/or rethrow at your discretion.
// throw err;
// else if (err.code === 'InvalidRequestException')
// // You provided a parameter value that is not valid for the current state of the resource.
// // Deal with the exception here, and/or rethrow at your discretion.
// throw err;
// else if (err.code === 'ResourceNotFoundException')
// // We can't find the resource that you asked for.
// // Deal with the exception here, and/or rethrow at your discretion.
// throw err;
// }
// else {
// // Decrypts secret using the associated KMS CMK.
// // Depending on whether the secret is a string or binary, one of these fields will be populated.
// if ('SecretString' in data) {
// secret = data.SecretString;
// } else {
// let buff = new Buffer(data.SecretBinary, 'base64');
// decodedBinarySecret = buff.toString('ascii');
// }
// }
// let db = (JSON.parse(secret));
// // connect to mongodb
// mongoose.connect(db.secret, { useNewURLParser: true, useUnifiedTopology: true})
// .then((result) => console.log('connected to db'))
// .then(app.listen(port, () => {
// console.log(`Server started on port ${port}`);
// }))
// .catch((err) => console.log(err));
// });
const databaseURL = 'mongodb+srv://Admin:111122!Aadmin@musicart.uumip.mongodb.net/MusicartDB?retryWrites=true&w=majority';
mongoose.connect(databaseURL, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log('connected to db'))
.then(app.listen(port, () => {
console.log(`Server started on port ${port}`);
}))
.catch((err) => console.log(err));
// Search
const fs = require('fs')
const SpotifyWebApi = require('spotify-web-api-node');
var token = require("fs").readFileSync("token.txt", "utf8");
const bodyParser = require('body-parser')
const spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(token);
//GET MY PROFILE DATA
// function getMyData() {
// (async () => {
// const me = await spotifyApi.getMe();
// console.log(me.body);
// getUserPlaylists(me.body.id);
// })().catch(e => {
// console.error(e);
// });
// }
//GET MY PLAYLISTS
// async function getUserPlaylists(userName) {
// const data = await spotifyApi.getUserPlaylists(userName)
// console.log("---------------+++++++++++++++++++++++++")
// let playlists = []
// for (let playlist of data.body.items) {
// console.log(playlist.name + " " + playlist.id)
// let tracks = await getPlaylistTracks(playlist.id, playlist.name);
// console.log(tracks);
// const tracksJSON = { tracks }
// let data = JSON.stringify(tracksJSON);
// fs.writeFileSync(playlist.name+'.json', data);
// }
// }
async function getPlaylistTracks(playlistId, playlistName) {
const data = await spotifyApi.getPlaylistTracks(playlistId, {
offset: 1,
limit: 100,
fields: 'items'
})
let tracks = [];
for (let track_obj of data.body.items) {
const track = track_obj.track
tracks.push(track);
console.log(track.name + " : " + track.artists[0].name)
}
console.log("---------------+++++++++++++++++++++++++")
return tracks;
}
async function searchTracks(trackName, res){
const data = await spotifyApi.searchTracks(trackName, {
offset: 1,
limit: 10,
fields: 'items'
})
let results = data.body.tracks.items
results.forEach(result => {
if(result.name.toUpperCase().includes(trackName.toUpperCase())){
let music = [result.id, {song_image: result.album.images[1].url,artist_name: result.artists[0].name,
song_name: result.name,song_type: result.album.album_type, release_date: result.album.release_date,
song_url: result.external_urls.spotify, track_uri: result.uri}]
user_music_items.push(music)
}
});
test_music_items = new Map(user_music_items)
res.redirect('checkout')
}
function addtoPlaylist(playlistId, trackId){
spotifyApi.addTracksToPlaylist(
playlistId,
[
trackId
])
}
app.get('/search', function(req, res) {
res.render('search');
// let track_name = req.query.search_track;
// // console.log('text is ' + track_name);
// searchTracks(track_name)
// res.json(process.env.SERVER_URL)
});
// app.get('/search_result', (req, res) => {
// let track_name = req.query.search_track;
// console.log(track_name)
// searchTracks(track_name)
// })
app.get('/search_result', (req, res) => {
let track_name = req.query.search_track
searchTracks(track_name, res)
// .then(res.redirect('checkout'))
// console.log(user_music_items)
// if (user_music_items.length != 0) {
// res.redirect('checkout')
// }
// res.redirect('checkout')
})