-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
485 lines (399 loc) · 13.5 KB
/
index.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const logger = require("morgan");
const port = process.env.PORT ?? 3000;
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(logger("dev"));
app.set("view engine", "ejs");
mongoose.set("strictQuery", false);
// PASSPORT DEPENDENCIES
const passport = require("passport");
const expressSession = require("express-session");
const LocalStrategy = require("passport-local").Strategy;
const MongoStore = require("connect-mongo");
// DB MODELS
const User = require("./models/UserModel");
const Show = require('./models/ShowModel');
const WatchProvider = ('./models/WatchProviderModel');
const {TMDBConfiguration} = require("./models/TMDBConfiguration");
const updateTMDBConfiguration = require("./models/updateTMDBConfiguration");
const refreshShowModel = require("./models/refreshShowModel");
const {
addShowToDatabase,
addShowToUserList,
retrieveShow,
userFullShows,
deleteUserShow,
setHasWatched,
setIsFavorite
} = require("./models/updateShowModel");
const {updateUserProfile} = require("./models/updateUserModel");
// API DEPENDENCY
const TMDB = require("./api").TMDB;
// DB CONNECTION
// Get connection variables from .env file
const {URI, DB, DB_USER, DB_PASS, EXPRESS_SESSION_SECRET} = process.env;
// URL to connect to database
const connectionURL = `${URI}/${DB}`;
// Connection options
// See https://mongoosejs.com/docs/connections.html#options, https://mongodb.github.io/node-mongodb-native/4.2/interfaces/MongoClientOptions.html)
let connectionObject = {
authSource: "admin",
user: DB_USER,
pass: DB_PASS
};
// Build the connection
mongoose.connect(connectionURL, connectionObject)
.then(() => {
console.log(`Connected to ${DB} database`)
})
.catch(error => console.log(`Error connecting to ${DB} database: ${error}`))
// USER AUTHENTICATION
// Create a session
const mongoStoreURL = `mongodb+srv://${DB_USER}:${DB_PASS}@bootcamp.doe2g0y.mongodb.net`;
app.use(expressSession({
secret: EXPRESS_SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: mongoStoreURL})
}));
// Authentication strategy using local authentication
const strategy = new LocalStrategy(User.authenticate());
passport.use(strategy);
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(passport.initialize());
app.use(passport.session());
// Authentication verification middleware - passed in to routes to verify the user is logged in. If not logged in, the user is redirected to the login page.
function verifyLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/login");
}
// API CONNECTION
const apiKey = process.env.TMDB_API_KEY_V4;
const tmdb = new TMDB(apiKey);
function performMaintenance() {
updateTMDBConfiguration();
refreshShowModel();
}
// always set to "true" for `npm run watch`
if (process.env.DISABLE_INITIAL_MAINTENANCE !== "true") {
performMaintenance();
}
setInterval(performMaintenance, 86_400_000); // 24 hours
// Add a new instance method to `Date` that returns a formatted date string,
// e.g., "March 17, 2023"
Date.prototype.formatted = function() {
return this.toLocaleString("default", {
month: "long",
day: "numeric",
year: "numeric"
});
};
// ROUTE HANDLERS
// PUBLIC PAGES
// Landing Page
app.get("/", (req, res)=>{
res.render("landing.ejs",);
})
// About Page
app.get("/about", (req, res) => {
const username = req.user?.username;
res.render("about.ejs", {username});
})
// USER CONTENT PAGES (SEARCH, SHOWS, SHOW DETAIL)
// User Home (Show list)
app.get("/home", (req, res) => {
// `username` will be undefined if the user is not logged in
Promise.all([
TMDBConfiguration.findOne({}),
userFullShows(req.user._id)
])
.then(([configuration, shows]) => {
const imagePosterBasePath = configuration.imagePosterBasePath("w92");
const username = req.user?.username;
res.render('home.ejs', {username, shows, imagePosterBasePath});
})
.catch((error) => {
console.error(error);
res.sendStatus(500);
});
});
// Search - initiate a search and view results
app.get("/search", verifyLoggedIn, (req, res) => {
const username = req.user?.username;
res.render("search.ejs", {username, shows: [], existingShows: []});
});
// Send a search query to the TMDB API and return results to the user
app.get("/searchShows", verifyLoggedIn, (req, res)=>{
// let route = "search/tv"
const {query} = req.query;
const username = req.user.username;
const existingShows = req.user.userShows.map( show => show.showId);
// Execute the functions in parallel using "Promise.all" instead of chaining them
Promise.all([
TMDBConfiguration.findOne({}),
tmdb.searchTVShows({query})
])
.then(([configuration, searchResults]) => {
const imagePosterBasePath = configuration.imagePosterBasePath("w92");
res.render("search.ejs", {
imagePosterBasePath,
shows: searchResults.results,
username,
existingShows
});
})
.catch((error) => {
console.error("/searchShows: error:", error);
res.redirect("/error");
})
});
// Add a selected show from search results to the userShows object in the userModel
app.post("/addShow", verifyLoggedIn, (req, res)=>{
const username = req.user.username;
const showId = req.body.showId;
addShowToUserList(req.user._id, showId)
.then((result) => {
console.log(result);
res.redirect("/home");
})
.catch((error) => {
console.error(error);
res.redirect("/error");
});
});
// Shows Page
app.get("/shows", verifyLoggedIn, (req, res) => {
Promise.all([
TMDBConfiguration.findOne({}),
userFullShows(req.user._id)
])
.then(([configuration, shows]) => {
const imagePosterBasePath = configuration.imagePosterBasePath("w92");
const username = req.user.username;
res.render('shows.ejs', {username, shows, imagePosterBasePath});
})
.catch((error) => {
console.error(error);
res.redirect("/error");
});
});
// Show Details Page
app.get("/show", verifyLoggedIn, (req, res) => {
const {showId} = req.query;
const {username} = req.user;
if (!showId) {
res.status(400).send("missing 'showId' query parameter");
return;
}
Promise.all([
TMDBConfiguration.findOne({}),
// retrieves a full show object with the user show object inside it
retrieveShow(req.user._id, showId)
])
.then(([configuration, show]) => {
const imagePosterBasePath = configuration.imagePosterBasePath("w92");
console.log(`imagePosterBasePath: ${imagePosterBasePath}`);
const fullPosterPath = show.posterPath ? `${imagePosterBasePath}${show.posterPath}` : "movie_poster_placeholder.svg";
console.log(show);
const imageShowDetailsPath = configuration.imageBackdropBasePath("w185");
console.log(`imageShowDetailsPath: ${imageShowDetailsPath}`);
const fullimageShowDetailsPath = show.posterPath ? `${imageShowDetailsPath}${show.posterPath}` : "movie_poster_placeholder.svg";
const imageBackdropBasePath = configuration.imageBackdropBasePath("w780");
const fullBackdropPath = show.backdropPath ? `${imageBackdropBasePath}${show.backdropPath}`: null;
console.log(`This is the backdrop path ${fullBackdropPath}`);
if (!show) {
// gets caught by the catch block directly below
throw new Error("could not find show in database or in TMDB api");
}
res.render("showDetail.ejs", {fullPosterPath, fullBackdropPath, fullimageShowDetailsPath, show, username});
})
.catch((error) => {
console.error(error);
res.redirect("/error");
});
});
// Toggle hasWatched in userShows object
app.put("/has-watched", (req, res) => {
const { showId, hasWatched } = req.body;
setHasWatched(req.user._id, showId, hasWatched)
.then((result) => {
console.log(result);
res.sendStatus(200);
})
.catch((error) => {
console.error(error);
res.sendStatus(400);
});
});
// Toggle isFavorite in userShows object
app.put("/is-favorite", (req, res) => {
const { showId, isFavorite } = req.body;
setIsFavorite(req.user._id, showId, isFavorite)
.then((result) => {
console.log(result);
res.sendStatus(200);
})
.catch((error) => {
console.error(error);
res.sendStatus(400);
});
});
// Delete show from userShow object
app.post("/deleteUserShow", verifyLoggedIn, (req, res) => {
const showId = req.body.showId;
if (!showId) {
res.redirect("/error");
return;
}
console.log(`delete showId: ${showId} for user ${req.user.username}`);
deleteUserShow(req.user._id, showId)
.then((result) => {
console.log("result from deleteUserShow:", result);
res.redirect('/home')
})
.catch((error) => {
console.error("error deleteUserShow:", error);
res.redirect("/error");
});
});
// USER ACCOUNT MANAGEMENT (LOGIN, LOGOUT, SIGNUP, PROFILE, CHANGE PASSWORD)
// User Login Page
app.get("/login", (req, res) => {
const failedAttempt = req.query.failedAttempt ?? false;
const username = req.user?.username;
res.render("login.ejs", {username, failedAttempt});
});
// Login using passport authentication
app.post("/login", passport.authenticate("local", {
failureRedirect: "/login?failedAttempt=true",
successRedirect: "/home",
failureMessage: "the failure message"
}), (error, req, res, next) => {
if (error) {
next(error);
}
});
// Logout (ends session)
// https://www.passportjs.org/concepts/authentication/logout/
app.get("/logout", (req, res, next) => {
req.logout((error) => {
if (error) {
return next(error);
}
res.redirect("/");
});
});
// Signup Page
app.get("/signup", (req, res) => {
const username = req.user?.username;
res.render("signup.ejs", {username});
});
// Create a user account using passport
app.post("/signup", (req, res) => {
User.register(
new User({
username: req.body.username
}),
req.body.password,
(error, response) => {
if (error) {
res.send(error);
}
else {
console.log(`response from signup: ${response}`);
passport.authenticate("local") (req, res, () => {
res.redirect("/home");
});
}
}
)
});
// Profile page
app.get("/profile", verifyLoggedIn, (req, res) => {
const user = req.user;
const { updated } = req.query ?? false;
// for display purposes, we want to display an empty string for missing
// properties, not "undefined"
const keys = ["firstName", "lastName", "email"];
for (const key of keys) {
if (!user[key]) {
user[key] = "";
}
}
res.render("profile.ejs", {user, updated});
});
// Update user info in the db
app.post("/update-profile", (req, res) => {
const userId = req.user._id;
const { firstName, lastName, email } = req.body;
const options = {
firstName: firstName === "" ? null : firstName,
lastName: lastName === "" ? null : lastName,
email: email === "" ? null : email
}
updateUserProfile(userId, options)
.then(() => {
res.redirect("/profile?updated=true");
})
.catch(error => {
console.log(`Error updating user profile: ${error}`);
res.redirect("/error");
});
});
// Change Password Page
app.get("/change-password", verifyLoggedIn, (req, res) => {
const user = req.user;
const failedAttempt = req.query.failedAttempt ?? false;
res.render("change_password.ejs", {user, failedAttempt});
});
app.post("/change-password", (req, res) => {
req.user.changePassword(req.body.oldPassword, req.body.newPassword, (error) => {
if (error) {
console.log(`Error changing password: ${error}`);
res.redirect("/change-password?failedAttempt=true");
}
else {
console.log("Password changed successfully");
res.redirect("/home");
}
});
});
app.put("/has-watched", (req, res) => {
const { showId, hasWatched } = req.body;
setHasWatched(req.user._id, showId, hasWatched)
.then((result) => {
console.log(result);
res.sendStatus(200);
})
.catch((error) => {
console.error(error);
res.redirect("/error");
});
});
app.put("/is-favorite", (req, res) => {
const { showId, isFavorite } = req.body;
setIsFavorite(req.user._id, showId, isFavorite)
.then((result) => {
console.log(result);
res.sendStatus(200);
})
.catch((error) => {
console.error(error);
res.redirect("/error");
});
});
// ERROR PAGE
app.get("/error", (req, res) => {
res.render("error.ejs");
});
app.listen(port, () => {
console.log(`Showrunner Server is running on http://localhost:${port}`)
});