-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
294 lines (233 loc) · 7.93 KB
/
index.js
File metadata and controls
294 lines (233 loc) · 7.93 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
import 'dotenv/config';
import express from "express";
import axios from "axios";
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import session from "express-session";
import passport from 'passport';
import passportLocalMongoose from 'passport-local-mongoose';
import FacebookStrategy from 'passport-facebook'
import { Strategy as LocalStrategy } from 'passport-local';
import findOrCreate from 'mongoose-findorcreate';
import flash from 'connect-flash'
import * as auth from './authentication.js'
import User from './databse.js'
const app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
const url = "https://api.themoviedb.org/3/";
const BearerToken = process.env.API_BEARER_TOKEN;
const config = {
headers: { Authorization: 'Bearer ' + BearerToken },
timeout:5000
}
app.use(session({
secret:process.env.MONGOOSE_SECRET,
resave:false,
saveUninitialized:false,
cookie: {
maxAge: 24 * 60 * 60 * 1000, // 1 day (in milliseconds)
// Other cookie options if needed...
},
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(process.env.MONGODB_URL);
passport.use(User.createStrategy());
passport.serializeUser((User, done)=> {done(null, User); });
passport.deserializeUser((User, done)=>{done(null, User);});
app.set('view engine', 'ejs');
app.use(express.static("public"));
const retryAxios = async (error, maxRetries = 3) => {
for (let retryCount = 0; retryCount < maxRetries; retryCount++) {
console.log(`Request failed, retrying (${retryCount + 1}/${maxRetries})`);
try {
return await axios(error.config);
} catch (e) {
if (retryCount === maxRetries - 1) {
throw e; // Throw the error if max retries reached
}
}
}
};
// Add an Axios interceptor to handle request errors
axios.interceptors.response.use(null, async (error) => {
// Retry the request if it fails
if (error.config && error.response && error.response.status >= 500) {
return retryAxios(error);
}
throw error;
});
var isAuth = false;
var username = "";
app.get('/', async (req, res) => {
isAuth = req.isAuthenticated();
username = "";
if(isAuth){
username = req.user.username;
}
try {
let trendingMovieListDay = await axios.get(url + "trending/movie/day", config);
let trendingMovieListWeek = await axios.get(url + "trending/movie/week", config);
let popularMovieList = await axios.get(url + "movie/popular", config);
let resplonse = await axios.get('https://api.themoviedb.org/3/discover/movie?release_date.desc', config);
let latestMovieList =[];
for(let i = 0;i<20;i++){
let movie = resplonse.data.results[i];
movie = await axios.get(`https://api.themoviedb.org/3/movie/${movie.id}/videos?language=en-US`,config);
movie = movie.data.results;
if(movie.length > 0){
for(let j = 0;j < movie.length;j++) {
if(movie[j].type === 'Trailer'){
latestMovieList.push(movie[j]); break
}
};
}
}
res.render('index', {
trendingMovieListDay: trendingMovieListDay.data,
trendingMovieListWeek: trendingMovieListWeek.data,
popularMovieList: popularMovieList.data,
isAuthenticated:isAuth,
username:username,
latestMovieList:latestMovieList
});
} catch (error) {
console.log(error);
res.status(404).send(error.message + " please try again");
}
});
app.get('/movie', async (req, res) => {
try {
let popularMovieList = await axios.get(url + "movie/popular?page=1", config);
res.render("movieList", {
movieList: popularMovieList.data,
btn: true,
isAuthenticated:isAuth,
username:username
})
} catch (error) {
console.log(error.message);
res.status(404).send(error.message);
}
});
app.get('/search', async (req, res) => {
try {
const query = req.query.query;
if (!query) {
res.send(404);
}
const newQuery = query.replace(/ /g, '%20');
let movies = await axios.get(url + `/search/movie?query=${newQuery}&include_adult=false`, config);
res.render("movieList", {
movieList: movies.data,
btn: false,
isAuthenticated:isAuth,
username:username
})
} catch (error) {
console.log(error.message);
res.redirect('/');
}
})
app.get('/movie/:id', async (req, res) => {
try {
let movieDetails = await axios.get(`${url}movie/${req.params.id}`, config);
let castDetails = await axios.get(`${url}movie/${req.params.id}/credits?language=en-US`, config);
res.render("movie", {
movie: movieDetails.data,
casts: castDetails.data,
isAuthenticated:isAuth,
username:username,
id:req.params.id
})
} catch (error) {
res.status(404).send(error.message);
}
});
app.post('/movie/add', async (req, res) => {
const id = req.body.id;
// Check if the user is authenticated
if (req.isAuthenticated()) {
const userID = req.user._id;
try {
const user = await User.findOne({ _id: userID });
if (user.watchList.includes(id)) {
res.status(200).json({ message: 'Movie is already in watchList' });
} else {
const result = await User.updateOne(
{ _id: userID },
{ $push: { watchList: id } }
);
res.status(201).json({ message: 'Movie added to watchList successfully' });
}
} catch (error) {
console.error('Error updating watchList:', error);
res.status(500).json({ error: 'Internal Server Error Please refresh the site' });
}
} else {
res.status(401).json({ error: 'Unauthorized' });
}
});
app.get('/watchlist', async (req, res) => {
try {
if (isAuth) {
const userID = req.user._id;
const user = await User.findById(userID);
let movieList = {
results: []
};
if (user.watchList.length > 0) {
// Map movie IDs to an array of axios promises
const axiosPromises = user.watchList.map(async (id) => {
const movieDetails = await axios.get(`${url}movie/${id}`, config);
return movieDetails.data;
});
// Wait for all axios promises to resolve
const movieDetailsArray = await Promise.all(axiosPromises);
// Populate movieList with resolved movieDetails
movieList.results = movieDetailsArray;
res.render('movieList', {
movieList: movieList,
btn: false,
isAuthenticated: isAuth,
username: username
});
} else {
res.render('movieList',{
message:"Please add Movie in movieList",
btn: false,
isAuthenticated: isAuth,
username: username
});
}
} else {
res.send('<script>alert("Unauthorized. Please log in."); window.location.href="/login";</script>');
}
} catch (error) {
console.error('Error fetching watchlist:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/signup', (req, res) => {
res.render("signup");
});
app.post('/signup', auth.signup);
app.get('/auth/facebook',
passport.authenticate('facebook')
);
app.get('/auth/facebook/user',auth.facebookAuth);
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] })
);
app.get('/auth/google/user', auth.googleAuth);
app.get('/login', (req, res) => {
res.render('login');
});
app.get('/logout', auth.logout)
app.post('/login',auth.login );
app.listen(port, (req, res) => {
console.log('listening on port ' + port);
});