-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
667 lines (606 loc) · 18.1 KB
/
index.js
File metadata and controls
667 lines (606 loc) · 18.1 KB
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
import express from "express";
import axios from "axios";
import env from "dotenv";
import bodyParser from "body-parser";
import pg from "pg";
import bcrypt from "bcrypt";
import session from "express-session"; // cookie
import passport from "passport";
import { Strategy } from "passport-local";
import GoogleStrategy from "passport-google-oauth2";
import flash from "connect-flash";
const app = express();
const port = 3000;
const saltRounds = 10; //hashing
const API_URL = "https://api.themoviedb.org/3"; // API for AMTsDB
const IMG_URL = "https://image.tmdb.org/t/p/original"; // Poster URL
env.config();
// Middleware
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000 * 86400,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// Env
const db = new pg.Client({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
});
db.connect();
// Check if user is connected and open main page or login/register
app.get("/", async (req, res) => {
if (req.isAuthenticated()) {
const user_id = req.user.id;
try {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'no' ORDER BY added_date DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", { data: data, header: "AMTss", err: null });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
} else {
res.render("login-register", { err: null });
}
});
// Show only added movies
app.get("/movies", async (req, res) => {
if (req.isAuthenticated()) {
const user_id = req.user.id;
try {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND type = 'movie' AND watchlist = 'no' ORDER BY likes DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", { data: data, header: "Your movies", err: null });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
} else {
res.render("login-register", { err: null });
}
});
// Show only added TV shows
app.get("/tv-shows", async (req, res) => {
if (req.isAuthenticated()) {
const user_id = req.user.id;
try {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND type = 'tv' AND watchlist = 'no' ORDER BY likes DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", { data: data, header: "Your TV Shows", err: null });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
} else {
res.render("login-register", { err: null });
}
});
// Sort by selected action
app.post("/order", async (req, res) => {
const user_id = req.user.id;
const { likes, rating, order } = req.body;
try {
if (likes === "on") {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'no' ORDER BY likes DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", {
data: data,
header: "Ordering by likes",
err: null,
});
} else if (rating === "on") {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'no' ORDER BY rating DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", {
data: data,
header: "Ordering by your ratings",
err: null,
});
} else {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'no' ORDER BY title ASC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", {
data: data,
header: "Alphabetical order",
err: null,
});
}
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
});
// Show other user profiles
app.get("/users", async (req, res) => {
const user_id = req.user.id;
try {
const result = await db.query(
`SELECT email FROM users WHERE id != $1 ORDER BY email ASC`,
[user_id]
);
const users = result.rows.map((obj) => ({
user: obj.email,
userName:
obj.email.split("@")[0].charAt(0).toUpperCase() +
obj.email.split("@")[0].slice(1),
}));
res.render("users", { users: users });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
});
app.get("/watchlist", async (req, res) => {
const user_id = req.user.id;
try {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'yes'`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
}));
res.render("watchlist", { data: data, err: null });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
});
app.get("/login-register", (req, res) => {
res.render("login-register", { err: req.flash("error")[0] });
});
// Login via Google
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
app.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "/",
failureRedirect: "login-register",
failureFlash: true,
})
);
app.get("/auth/google/login-register", (req, res) => {
res.redirect("/");
});
// Logout
app.get("/logout", (req, res) => {
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect("/login-register");
});
});
// Handle login input
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "login-register",
failureFlash: true,
})
);
// Handle register input and login
app.post("/register", async (req, res) => {
const { email, password } = req.body;
try {
const checkResult = await db.query("SELECT * FROM users WHERE email = $1", [
email,
]);
if (checkResult.rows.length > 0) {
res.render("login-register", {
err: "Email already exists. Try logging in.",
});
} else {
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.error("Error hashing password:", err);
} else {
const result = await db.query(
`INSERT INTO users (email, password) VALUES ($1, $2) RETURNING *`,
[email, hash]
);
const user = result.rows[0];
req.login(user, (err) => {
console.log(err);
res.redirect("/");
});
}
});
}
} catch (err) {
console.log(err.detail);
}
});
// Handle searchbar input
app.get("/search", async (req, res) => {
const searchInput = req.query.search;
try {
const response = await axios.get(API_URL + "/search/multi", {
headers: {
accept: "application/json",
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
params: {
query: searchInput,
include_adult: false,
language: "en-US",
page: 1,
},
});
const results = response.data.results
.filter((obj) => obj.media_type === "movie" || obj.media_type === "tv")
.filter((obj) => obj.poster_path !== null)
.map((obj) => ({
title: obj.title || obj.name,
overview: obj.overview,
media_type: obj.media_type,
release_date: obj.release_date || obj.first_air_date,
poster_path: IMG_URL + obj.poster_path,
type: obj.media_type,
}));
res.render("index", {
results: results,
err: null,
});
} catch (err) {
res.status(500).send(err.message);
}
});
// Go to an user database
app.get("/:email", async (req, res) => {
const { email } = req.params;
const userName =
email.split("@")[0].charAt(0).toUpperCase() + email.split("@")[0].slice(1);
try {
const result = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = (SELECT id FROM users WHERE email = $1) AND watchlist = 'no' ORDER BY rating DESC`,
[email]
);
const data = result.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
user_id: obj.user_id,
likes: obj.likes,
}));
res.render("userAMTs", { data: data, user: userName });
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
});
// Add and rate selected AMTs to the database
app.post("/add", async (req, res) => {
const { title, poster, description, release_date, rate, comment, type } =
req.body;
const user_id = req.user.id;
try {
await db.query(
`INSERT INTO AMTsDb (user_id, title, url, description, release_date, rating, comment, type, watchlist) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'no')`,
[user_id, title, poster, description, release_date, rate, comment, type]
);
res.redirect("/");
} catch (err) {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND description =$2`,
[user_id, description]
);
const inWatchlist = database.rows[0].watchlist;
const id = database.rows[0].id;
if (inWatchlist === "yes") {
await db.query(
`UPDATE AMTsDb SET rating = $1, comment = $2, watchlist = 'no' WHERE user_id = $3 AND id = $4`,
[rate, comment, user_id, id]
);
res.redirect("/");
} else {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'no' ORDER BY likes DESC`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
added_date: obj.added_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
rate: obj.rating,
comment: obj.comment,
likes: obj.likes,
}));
res.render("index", {
data: data,
header: "AMTss",
err: "You have added this AMTs before.",
});
console.error(err);
}
}
});
// Delete selected AMTs from the database
app.post("/delete", async (req, res) => {
const id = req.body.del;
try {
await db.query("BEGIN");
await db.query(`DELETE FROM user_likes WHERE item_id = $1`, [id]);
await db.query(`DELETE FROM AMTsDb WHERE id = $1`, [id]);
await db.query("COMMIT");
res.redirect("/");
} catch (err) {
console.log(err);
}
});
// Update page (AMTss)
app.post("/to-update", async (req, res) => {
const user_id = req.user.id;
try {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND id = $2`,
[user_id, req.body.del]
);
const data = database.rows[0];
res.render("update", {
title: data.title,
overview: data.description,
release_date: data.release_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: data.url,
id: data.id,
comment: data.comment,
err: null,
});
} catch (err) {
console.error(err);
res.status(500).send("Error fetching data");
}
});
// Update selected AMTs
app.post("/update", async (req, res) => {
const { id, rate, comment } = req.body;
const user_id = req.user.id;
try {
await db.query(
`UPDATE AMTsDb SET rating = $1, comment = $2, watchlist = 'no' WHERE user_id = $3 AND id = $4`,
[rate, comment, user_id, id]
);
res.redirect("/");
} catch (err) {
console.error(err);
res.status(500).send("Error saving data");
}
});
//Add to watchlist
app.post("/watchlist", async (req, res) => {
const { title, poster, description, release_date, type } = req.body;
const user_id = req.user.id;
try {
await db.query(
`INSERT INTO AMTsDb (user_id, title, url, description, release_date, type, watchlist) VALUES ($1, $2, $3, $4, $5, $6, 'yes')`,
[user_id, title, poster, description, release_date, type]
);
res.redirect("/watchlist");
} catch (err) {
const database = await db.query(
`SELECT * FROM AMTsDb WHERE user_id = $1 AND watchlist = 'yes'`,
[user_id]
);
const data = database.rows.map((obj) => ({
title: obj.title,
overview: obj.description,
release_date: obj.release_date.toLocaleDateString("tr-TR").slice(0, 10),
poster_path: obj.url,
id: obj.id,
}));
res.render("watchlist", {
data: data,
err: "You have already added this AMTs to your watchlist.",
});
console.error(err);
}
});
// Like any users AMTs
app.post("/like", async (req, res) => {
const itemId = req.body["item-id"];
const likerUserId = req.user.id;
try {
const checkLiked = await db.query(
`SELECT id FROM user_likes WHERE liker_id = $1 AND item_id = $2`,
[likerUserId, itemId]
);
if (checkLiked.rows.length > 0) {
return res.status(400).render("index", {
err: "You have already liked this AMTs.",
});
}
await db.query(`UPDATE AMTsDb SET likes = likes + 1 WHERE id = $1`, [
itemId,
]);
await db.query(
`INSERT INTO user_likes (liker_id, item_id) VALUES ($1, $2)`,
[likerUserId, itemId]
);
res.redirect("back");
} catch (err) {
console.error(err);
res.status(500).send("Error processing like operation");
}
});
passport.use(
"local",
new Strategy(
{ usernameField: "email", passwordField: "password" },
async function verify(username, password, cb) {
try {
const result = await db.query("SELECT * FROM users WHERE email = $1", [
username,
]);
if (result.rows.length > 0) {
const user = result.rows[0];
const storedPassword = user.password;
bcrypt.compare(password, storedPassword, (err, valid) => {
if (err) {
return cb(err);
} else {
if (valid) {
return cb(null, user);
} else {
return cb(null, false, {
message: "Incorrect password.",
});
}
}
});
} else {
return cb(null, false, { message: "User not found" });
}
} catch (err) {
console.log(err);
}
}
)
);
passport.use(
"google",
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "https://amtssdb.onrender.com/auth/google/callback",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, cb) => {
try {
const result = await db.query("SELECT * FROM users WHERE email = $1", [
profile.email,
]);
if (result.rows.length === 0) {
const newUser = await db.query(
"INSERT INTO users (email, password, name, picture) VALUES ($1, $2, $3, $4)",
[profile.email, "google", profile.displayName, profile.picture]
);
return cb(null, newUser.rows[0]);
} else {
return cb(null, result.rows[0]);
}
} catch (err) {
return cb(err);
}
}
)
);
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((user, cb) => {
cb(null, user);
});
app.listen(port, () => {
console.log(`API is running at http://localhost:${port}`);
});