initial commit, should work
@@ -0,0 +1,136 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# vitepress build output
|
||||
**/.vitepress/dist
|
||||
|
||||
# vitepress cache directory
|
||||
**/.vitepress/cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
@@ -0,0 +1,29 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const dotenv = require("dotenv");
|
||||
const cors = require("cors");
|
||||
|
||||
dotenv.config();
|
||||
const app = express();
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// Connect to MongoDB
|
||||
mongoose
|
||||
.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
|
||||
.then(() => console.log("MongoDB connected"))
|
||||
.catch((err) => console.error(err));
|
||||
|
||||
// Routes
|
||||
const userRoutes = require("./routes/users");
|
||||
const movieRoutes = require("./routes/movies");
|
||||
|
||||
app.use(express.static('public'));
|
||||
app.use("/api/users", userRoutes);
|
||||
app.use("/api/movies", movieRoutes);
|
||||
|
||||
// Start Server
|
||||
const PORT = process.env.PORT || 5000;
|
||||
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|
||||
@@ -0,0 +1,18 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const authenticate = (req, res, next) => {
|
||||
const token = req.headers.authorization?.split(" ")[1];
|
||||
if (!token) {
|
||||
return res.status(401).json({ message: "No token provided" });
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
req.user = decoded; // Attach user data to request
|
||||
next(); // Continue to the next middleware or route handler
|
||||
} catch (error) {
|
||||
return res.status(401).json({ message: "Invalid or expired token" });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = authenticate;
|
||||
@@ -0,0 +1,14 @@
|
||||
const mongoose = require("mongoose");
|
||||
|
||||
const movieSchema = new mongoose.Schema({
|
||||
imdb_id: { type: String, required: true },
|
||||
title: { type: String, required: false },
|
||||
description: { type: String, required: false },
|
||||
rating: { type: String, required: false },
|
||||
poster: { type: String, required: false },
|
||||
category: { type: String, required: true },
|
||||
vod_link: { type: String, required: true },
|
||||
watchedBy: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
|
||||
});
|
||||
|
||||
module.exports = mongoose.model("Movie", movieSchema);
|
||||
@@ -0,0 +1,15 @@
|
||||
const mongoose = require("mongoose");
|
||||
|
||||
const userSchema = new mongoose.Schema({
|
||||
name: { type: String, required: true },
|
||||
email: { type: String, required: true, unique: true },
|
||||
password: { type: String, required: true },
|
||||
role: { type: Number, default: 0 },
|
||||
watchedMovies: [{
|
||||
imdb_id: { type: String, required: false },
|
||||
watchedDate: { type: Date, default: Date.now } // Store the watched date
|
||||
}]
|
||||
});
|
||||
|
||||
const User = mongoose.model("User", userSchema);
|
||||
module.exports = User;
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "oscar-pool-ap",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"axios": "^1.7.9",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"body-parser": "^1.20.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.7",
|
||||
"express": "^4.21.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mongoose": "^8.9.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.9"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,212 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pool Oscar 2025 - Checklist</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<style>
|
||||
.navbar-custom {
|
||||
background-color: black;
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .navbar-brand,
|
||||
.navbar-custom .nav-link {
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .nav-link:hover {
|
||||
color: #ddd;
|
||||
}
|
||||
.movie-table {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.ratio {
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
|
||||
<!-- Black banner with buttons and user info -->
|
||||
<nav class="navbar navbar-expand-lg navbar-custom">
|
||||
<div class="container-fluid">
|
||||
<div class="d-flex align-items-center">
|
||||
<!-- Logo with max height and width control -->
|
||||
<a class="navbar-brand" href="#">
|
||||
<img src="img/logo_w.png" style="max-width: 180px; height: 70px; object-fit: contain;">
|
||||
</a>
|
||||
<a href="movies.html" class="btn btn-outline-light me-2">Films</a>
|
||||
<a href="checklist.html" class="btn btn-outline-light me-2">Checklist</a>
|
||||
<a href="user-stat.html" class="btn btn-outline-light">Statistique</a>
|
||||
</div>
|
||||
<div class="d-flex">
|
||||
<span id="user-name" class="navbar-text me-3"></span>
|
||||
<button id="log-off" class="btn btn-danger">Déconnexion</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container mt-5">
|
||||
<h2>Checklist</h2>
|
||||
<div id="watched-ratio" class="ratio"></div>
|
||||
<h3 class="fs-6">Temps avant les Oscar (2 mars 2025) - <span id="time-left"></span></h3>
|
||||
<div class="progress my-3">
|
||||
<div id="progress-bar" class="progress-bar" role="progressbar" style="width: 0%; background-color: red;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
|
||||
</div>
|
||||
<!-- Table for movies -->
|
||||
<table class="table movie-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Titre</th>
|
||||
<th scope="col">Regardé</th>
|
||||
<th scope="col">Date du visionnage</th> <!-- New column for watched date -->
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="movie-table-body">
|
||||
<!-- Movie rows will be inserted here -->
|
||||
</tbody>
|
||||
</table>
|
||||
<br><br>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
window.onload = async function () {
|
||||
const token = localStorage.getItem('auth_token');
|
||||
|
||||
const targetDate = new Date('March 2, 2025');
|
||||
const currentDate = new Date();
|
||||
const timeDifference = targetDate - currentDate;
|
||||
const daysLeft = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
|
||||
document.getElementById('time-left').textContent = `${daysLeft} jours`;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
// Decode the token (using a library like jwt-decode or manually)
|
||||
const decoded = JSON.parse(atob(token.split('.')[1])); // Manually decoding JWT
|
||||
|
||||
// Access the user's name from the decoded token
|
||||
const userName = decoded.name;
|
||||
|
||||
// Update the user name in the navbar
|
||||
document.getElementById('user-name').textContent = userName;
|
||||
|
||||
// Verify JWT Token expiration
|
||||
const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds
|
||||
if (decoded.exp && decoded.exp < currentTime) {
|
||||
console.warn("Token is expired");
|
||||
localStorage.removeItem('auth_token'); // Remove the expired token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error decoding token:", error);
|
||||
localStorage.removeItem('auth_token'); // Remove invalid token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} else {
|
||||
// Handle case if no token is available
|
||||
window.location.href = '/'; // Redirect to the login page if no token
|
||||
}
|
||||
|
||||
const res = await fetch('/api/movies', {
|
||||
method: 'GET',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
localStorage.removeItem('auth_token');
|
||||
window.location.href = '/';
|
||||
return;
|
||||
}
|
||||
|
||||
const movies = await res.json();
|
||||
const watchedRes = await fetch('/api/movies/watchedMovies', {
|
||||
method: 'GET',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
let watchedMovies = [];
|
||||
if (watchedRes.ok) {
|
||||
watchedMovies = await watchedRes.json();
|
||||
}
|
||||
|
||||
const totalMoviesCount = movies.length;
|
||||
const watchedMoviesCount = watchedMovies.length;
|
||||
document.getElementById('watched-ratio').innerText = `Regardé: ${watchedMoviesCount} / ${totalMoviesCount} (${((watchedMoviesCount / totalMoviesCount) * 100).toFixed(1)}%)`;
|
||||
|
||||
function updateProgressBar(watchedCount, totalCount) {
|
||||
const progressBar = document.getElementById('progress-bar');
|
||||
const percentage = (watchedCount / totalCount) * 100;
|
||||
progressBar.style.width = `${percentage}%`;
|
||||
|
||||
if (percentage <= 50) {
|
||||
progressBar.style.backgroundColor = `rgb(${255}, ${Math.floor((percentage / 50) * 255)}, 0)`;
|
||||
} else {
|
||||
progressBar.style.backgroundColor = `rgb(${Math.floor(255 - ((percentage - 50) / 50) * 255)}, 255, 0)`;
|
||||
}
|
||||
|
||||
progressBar.setAttribute('aria-valuenow', Math.round(percentage));
|
||||
}
|
||||
|
||||
updateProgressBar(watchedMoviesCount, totalMoviesCount);
|
||||
|
||||
const movieTableBody = document.getElementById('movie-table-body');
|
||||
movies.forEach(movie => {
|
||||
const watchedMovie = watchedMovies.find(wm => wm.imdb_id === movie.imdb_id);
|
||||
const watchedDate = watchedMovie ? new Date(watchedMovie.watchedDate).toLocaleString() : '';
|
||||
const movieRow = document.createElement('tr');
|
||||
movieRow.innerHTML = `
|
||||
<td>${movie.title}</td>
|
||||
<td>
|
||||
<input type="checkbox" class="form-check-input" id="movie-${movie.imdb_id}" ${watchedMovie ? 'checked' : ''} />
|
||||
</td>
|
||||
<td id="watched-date-${movie.imdb_id}">${watchedDate}</td>
|
||||
`;
|
||||
movieTableBody.appendChild(movieRow);
|
||||
|
||||
const checkbox = document.getElementById(`movie-${movie.imdb_id}`);
|
||||
checkbox.addEventListener('change', async (event) => {
|
||||
const isChecked = event.target.checked;
|
||||
const watchedDateCell = document.getElementById(`watched-date-${movie.imdb_id}`);
|
||||
if (isChecked) {
|
||||
watchedDateCell.textContent = new Date().toLocaleString();
|
||||
} else {
|
||||
watchedDateCell.textContent = '';
|
||||
}
|
||||
|
||||
await fetch('/api/movies/users/updateWatchedMovies', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ imdb_id: movie.imdb_id, isChecked })
|
||||
});
|
||||
|
||||
const updatedWatchedMoviesRes = await fetch('/api/movies/watchedMovies', {
|
||||
method: 'GET',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (updatedWatchedMoviesRes.ok) {
|
||||
const updatedWatchedMovies = await updatedWatchedMoviesRes.json();
|
||||
const updatedWatchedCount = updatedWatchedMovies.length;
|
||||
document.getElementById('watched-ratio').innerText = `Regardé: ${updatedWatchedCount} / ${totalMoviesCount} (${((updatedWatchedCount / totalMoviesCount) * 100).toFixed(1)}%)`;
|
||||
updateProgressBar(updatedWatchedCount, totalMoviesCount);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('log-off').addEventListener('click', () => {
|
||||
localStorage.removeItem('auth_token');
|
||||
window.location.href = '/';
|
||||
});
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 658 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 418 B |
|
After Width: | Height: | Size: 586 B |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,69 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pool Oscar 2025</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
|
||||
<div class="container d-flex justify-content-center align-items-center vh-100">
|
||||
<div class="card p-4" style="max-width: 400px;">
|
||||
<div class="text-center mb-4">
|
||||
<img src="img/logo.png" style="width: 80%";>
|
||||
</div>
|
||||
<form id="login-form">
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Courriel</label>
|
||||
<input type="email" class="form-control" id="email" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Mot de passe</label>
|
||||
<input type="password" class="form-control" id="password" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100">Connexion</button>
|
||||
</form>
|
||||
<p class="mt-3 text-center">Pas de compte? <a href="/register.html">Enregistrez-vous</a></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
// Check if the user is already logged in by looking for auth_token in localStorage
|
||||
if (localStorage.getItem('auth_token')) {
|
||||
// If the token is found, redirect to /movies.html
|
||||
window.location.href = '/movies.html';
|
||||
}
|
||||
|
||||
// Handle login form submission
|
||||
document.getElementById('login-form').addEventListener('submit', async function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = document.getElementById('email').value;
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
const res = await fetch('/api/users/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
// Save the token to localStorage
|
||||
localStorage.setItem('auth_token', data.token);
|
||||
window.location.href = '/movies.html'; // Redirect to movies page on success
|
||||
} else {
|
||||
const error = await res.json();
|
||||
alert(`Login failed: ${error.message}`);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,284 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pool Oscar 2025 - Films</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<style>
|
||||
.navbar-custom {
|
||||
background-color: black;
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .navbar-brand,
|
||||
.navbar-custom .nav-link {
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .nav-link:hover {
|
||||
color: #ddd;
|
||||
}
|
||||
|
||||
/* Style for the 'WATCHED' banner */
|
||||
.watched-banner {
|
||||
background-color: green;
|
||||
color: white;
|
||||
text-align: center;
|
||||
padding: 5px;
|
||||
font-weight: bold;
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Centering checkbox and making card look better */
|
||||
.movie-card {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.card-body {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Style for the filter button */
|
||||
#filter-button {
|
||||
margin-left: 15px;
|
||||
}
|
||||
|
||||
/* Style for the ratio display */
|
||||
.ratio {
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
|
||||
<!-- Black banner with buttons and user info -->
|
||||
<nav class="navbar navbar-expand-lg navbar-custom">
|
||||
<div class="container-fluid">
|
||||
<div class="d-flex align-items-center">
|
||||
<!-- Logo with max height and width control -->
|
||||
<a class="navbar-brand" href="#">
|
||||
<img src="img/logo_w.png" style="max-width: 180px; height: 70px; object-fit: contain;">
|
||||
</a>
|
||||
<a href="movies.html" class="btn btn-outline-light me-2">Films</a>
|
||||
<a href="checklist.html" class="btn btn-outline-light me-2">Checklist</a>
|
||||
<a href="user-stat.html" class="btn btn-outline-light">Statistique</a>
|
||||
</div>
|
||||
<div class="d-flex">
|
||||
<span id="user-name" class="navbar-text me-3"></span>
|
||||
<button id="log-off" class="btn btn-danger">Déconnexion</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container mt-5">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<h2>Films</h2>
|
||||
<h3 class="fs-6 mb-0">
|
||||
<img src="/img/filter.png" style="height: 25px;"><button id="filter-button" class="btn btn-primary btn-sm"></button>
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<!-- Displaying the ratio of watched movies -->
|
||||
<div id="watched-ratio" class="ratio">
|
||||
<!-- This will display the ratio -->
|
||||
</div>
|
||||
|
||||
<h3 class="fs-6">Temps avant les Oscar (2 mars 2025) - <span id="time-left"></span></h3>
|
||||
<div id="movies-list" class="row">
|
||||
<!-- Movies will be displayed here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
window.onload = async function () {
|
||||
// Calculate the time left until March 2, 2025
|
||||
const targetDate = new Date('March 2, 2025');
|
||||
const currentDate = new Date();
|
||||
|
||||
// Calculate the difference in milliseconds
|
||||
const timeDifference = targetDate - currentDate;
|
||||
|
||||
// Convert milliseconds to days
|
||||
const daysLeft = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
|
||||
|
||||
// Update the "Time Left" text
|
||||
document.getElementById('time-left').textContent = `${daysLeft} jours`;
|
||||
|
||||
// Get token from localStorage (assuming it's set after login)
|
||||
const token = localStorage.getItem('auth_token');
|
||||
// Check if token exists
|
||||
if (token) {
|
||||
try {
|
||||
// Decode the token (using a library like jwt-decode or manually)
|
||||
const decoded = JSON.parse(atob(token.split('.')[1])); // Manually decoding JWT
|
||||
|
||||
// Access the user's name from the decoded token
|
||||
const userName = decoded.name;
|
||||
|
||||
// Update the user name in the navbar
|
||||
document.getElementById('user-name').textContent = userName;
|
||||
|
||||
// Verify JWT Token expiration
|
||||
const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds
|
||||
if (decoded.exp && decoded.exp < currentTime) {
|
||||
console.warn("Token is expired");
|
||||
localStorage.removeItem('auth_token'); // Remove the expired token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error decoding token:", error);
|
||||
localStorage.removeItem('auth_token'); // Remove invalid token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} else {
|
||||
// Handle case if no token is available
|
||||
window.location.href = '/'; // Redirect to the login page if no token
|
||||
}
|
||||
|
||||
// Fetching the movies from your API with Authorization header
|
||||
const res = await fetch('/api/movies', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}` // Send the token in the Authorization header
|
||||
}
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
// If unauthorized or any error, log out the user
|
||||
localStorage.removeItem('auth_token'); // Clear the token
|
||||
window.location.href = '/'; // Redirect to login page
|
||||
return;
|
||||
}
|
||||
|
||||
const movies = await res.json();
|
||||
|
||||
// Fetch watched movies for the logged-in user
|
||||
const watchedRes = await fetch('/api/movies/watchedMovies', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}` // Send the token to verify the user
|
||||
}
|
||||
});
|
||||
|
||||
let watchedMovies = [];
|
||||
if (watchedRes.ok) {
|
||||
watchedMovies = await watchedRes.json(); // Get the list of watched movies from the user's profile
|
||||
}
|
||||
|
||||
const moviesList = document.getElementById('movies-list');
|
||||
|
||||
// Calculate the watched-to-total ratio
|
||||
const totalMoviesCount = movies.length;
|
||||
const watchedMoviesCount = watchedMovies.length;
|
||||
const ratioText = `Regardé: ${watchedMoviesCount} / ${totalMoviesCount} (${((watchedMoviesCount / totalMoviesCount) * 100).toFixed(1)}%)`;
|
||||
|
||||
// Display the ratio below the Movies heading
|
||||
document.getElementById('watched-ratio').innerText = ratioText;
|
||||
|
||||
// Loop through the movies and create cards for them
|
||||
movies.forEach(movie => {
|
||||
const isChecked = watchedMovies.some(watchedMovie => watchedMovie.imdb_id === movie.imdb_id); // Check if the movie is watched
|
||||
const watchedMovie = watchedMovies.find(wm => wm.imdb_id === movie.imdb_id);
|
||||
const watchedDate = watchedMovie ? new Date(watchedMovie.watchedDate).toLocaleString() : ''; // Get the watched date if available
|
||||
|
||||
const movieDiv = document.createElement('div');
|
||||
movieDiv.classList.add('col-md-4', 'mb-4', 'movie-card');
|
||||
movieDiv.setAttribute('data-imdb-id', movie.imdb_id);
|
||||
movieDiv.innerHTML = `
|
||||
<div class="card">
|
||||
${isChecked ? '<div class="watched-banner">REGARDÉ</div>' : ''}
|
||||
<img src="${movie.poster}" class="card-img-top" alt="${movie.title}" style="width: 75%; display: block; margin: 0 auto; padding: 10px;">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title d-flex justify-content-between align-items-center">
|
||||
${movie.title}
|
||||
<span>⭐ ${movie.rating} <a href="https://www.imdb.com/title/${movie.imdb_id}/"><img src="/img/imdb.png"></a></span>
|
||||
</h5>
|
||||
<p class="fw-bold fst-italic card-text" style="font-size: 0.75rem;">${movie.category}</p>
|
||||
<p class="card-text">${movie.description}</p>
|
||||
${isChecked ? `<p class="card-text"><strong>Regardé le:</strong> ${watchedDate}</p>` : ''} <!-- Display watched date and time if movie is watched -->
|
||||
<p class="card-text">🎥 ${movie.vod_link}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
moviesList.appendChild(movieDiv);
|
||||
});
|
||||
|
||||
// Log off functionality
|
||||
document.getElementById('log-off').addEventListener('click', function() {
|
||||
localStorage.removeItem('auth_token'); // Remove token from localStorage
|
||||
window.location.href = '/'; // Redirect to login page
|
||||
});
|
||||
|
||||
// Retrieve filter state from localStorage
|
||||
const savedFilterState = localStorage.getItem('filter-checkbox');
|
||||
let isFilterActive = savedFilterState === 'checked';
|
||||
|
||||
// Update button text and color based on the filter state
|
||||
const filterButton = document.getElementById('filter-button');
|
||||
filterButton.textContent = isFilterActive ? 'Tous les films' : 'Films non regardé';
|
||||
|
||||
// Change the button color to red when "Tous les films" is displayed
|
||||
if (isFilterActive) {
|
||||
filterButton.classList.remove('btn-danger');
|
||||
filterButton.classList.add('btn-primary');
|
||||
} else {
|
||||
filterButton.classList.remove('btn-primary');
|
||||
filterButton.classList.add('btn-danger');
|
||||
}
|
||||
|
||||
// Event listener for the button
|
||||
filterButton.addEventListener('click', function () {
|
||||
// Toggle the filter state
|
||||
isFilterActive = !isFilterActive;
|
||||
|
||||
// Update the button text and color based on the new state
|
||||
filterButton.textContent = isFilterActive ? 'Tous les films' : 'Films non regardé';
|
||||
if (isFilterActive) {
|
||||
filterButton.classList.remove('btn-danger');
|
||||
filterButton.classList.add('btn-primary');
|
||||
} else {
|
||||
filterButton.classList.remove('btn-primary');
|
||||
filterButton.classList.add('btn-danger');
|
||||
}
|
||||
|
||||
// Save the filter state to localStorage
|
||||
const filterState = isFilterActive ? 'checked' : 'unchecked';
|
||||
localStorage.setItem('filter-checkbox', filterState);
|
||||
|
||||
// Apply the filter to the movie cards
|
||||
filterMovies();
|
||||
});
|
||||
|
||||
// Function to filter the movies based on the button state
|
||||
function filterMovies() {
|
||||
const showUnwatchedOnly = isFilterActive;
|
||||
const movieCards = document.querySelectorAll('.movie-card');
|
||||
|
||||
movieCards.forEach(card => {
|
||||
const imdbId = card.getAttribute('data-imdb-id');
|
||||
const isWatched = watchedMovies.some(watchedMovie => watchedMovie.imdb_id === imdbId);
|
||||
|
||||
// Hide the movie card if it's watched and the filter is on
|
||||
if (showUnwatchedOnly && isWatched) {
|
||||
card.style.display = 'none';
|
||||
} else {
|
||||
card.style.display = 'block';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Initial filter application
|
||||
filterMovies();
|
||||
};
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,107 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pool Oscar 2025 - Enregistrement</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
|
||||
<div class="container d-flex justify-content-center align-items-center vh-100">
|
||||
<div class="card p-4" style="max-width: 400px;">
|
||||
<div class="text-center mb-4">
|
||||
<img src="img/logo.png" style="width: 80%";>
|
||||
</div>
|
||||
<form id="register-form">
|
||||
<div class="mb-3">
|
||||
<label for="name" class="form-label">Nom</label>
|
||||
<input type="text" class="form-control" id="name" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Courriel</label>
|
||||
<input type="email" class="form-control" id="email" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Mot de passe</label>
|
||||
<input type="password" class="form-control" id="password" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100">Enregistrer</button>
|
||||
</form>
|
||||
<p class="mt-3 text-center">Déjà un compte? <a href="/">Connectez-vous</a></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal for displaying registration response -->
|
||||
<div class="modal fade" id="responseModal" tabindex="-1" aria-labelledby="responseModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="responseModalLabel">Statut de l’enregistrement</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="response-message">
|
||||
<!-- Response message will be inserted here -->
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
|
||||
<button type="button" class="btn btn-primary" id="redirect-login">Retourner à la page d'accueil</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
// Check if the user is already logged in by looking for auth_token in localStorage
|
||||
if (localStorage.getItem('auth_token')) {
|
||||
// If the token is found, redirect to /movies.html
|
||||
window.location.href = '/movies.html';
|
||||
}
|
||||
|
||||
// Handle registration form submission
|
||||
document.getElementById('register-form').addEventListener('submit', async function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
const name = document.getElementById('name').value;
|
||||
const email = document.getElementById('email').value;
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
const res = await fetch('/api/users/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, password })
|
||||
});
|
||||
|
||||
const responseMessageElement = document.getElementById('response-message');
|
||||
const modal = new bootstrap.Modal(document.getElementById('responseModal'));
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
// Show success message in the modal
|
||||
responseMessageElement.textContent = data.message;
|
||||
|
||||
// Show the modal
|
||||
modal.show();
|
||||
|
||||
// Redirect to login after the modal is dismissed
|
||||
document.getElementById('redirect-login').addEventListener('click', function () {
|
||||
window.location.href = '/';
|
||||
});
|
||||
} else {
|
||||
const error = await res.json();
|
||||
// Show error message in the modal
|
||||
responseMessageElement.textContent = `Error: ${error.message}`;
|
||||
|
||||
// Show the modal
|
||||
modal.show();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
|
||||
@@ -0,0 +1,192 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>User Statistics</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<style>
|
||||
.navbar-custom {
|
||||
background-color: black;
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .navbar-brand,
|
||||
.navbar-custom .nav-link {
|
||||
color: white;
|
||||
}
|
||||
.navbar-custom .nav-link:hover {
|
||||
color: #ddd;
|
||||
}
|
||||
.user-table {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.ratio {
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
|
||||
<!-- Black banner with buttons and user info -->
|
||||
<nav class="navbar navbar-expand-lg navbar-custom">
|
||||
<div class="container-fluid">
|
||||
<div class="d-flex align-items-center">
|
||||
<!-- Logo with max height and width control -->
|
||||
<a class="navbar-brand" href="#">
|
||||
<img src="img/logo_w.png" style="max-width: 180px; height: 70px; object-fit: contain;">
|
||||
</a>
|
||||
<a href="movies.html" class="btn btn-outline-light me-2">Films</a>
|
||||
<a href="checklist.html" class="btn btn-outline-light me-2">Checklist</a>
|
||||
<a href="user-stat.html" class="btn btn-outline-light">Statistique</a>
|
||||
</div>
|
||||
<div class="d-flex">
|
||||
<span id="user-name" class="navbar-text me-3"></span>
|
||||
<button id="log-off" class="btn btn-danger">Déconnexion</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container mt-5">
|
||||
<h2>Statistiques des utilisateurs</h2>
|
||||
<!-- Table for users and movies watched -->
|
||||
<table class="table user-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Nom</th>
|
||||
<th scope="col">Total des films regardés</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="user-table-body">
|
||||
<!-- User rows will be inserted here -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Modal for displaying movies watched -->
|
||||
<div class="modal fade" id="moviesModal" tabindex="-1" aria-labelledby="moviesModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="moviesModalLabel">Films regardés</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<ul id="movie-list" class="list-group">
|
||||
<!-- Movie titles will be inserted here -->
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
window.onload = async function () {
|
||||
const token = localStorage.getItem('auth_token');
|
||||
// Check if token exists
|
||||
if (token) {
|
||||
try {
|
||||
// Decode the token (using a library like jwt-decode or manually)
|
||||
const decoded = JSON.parse(atob(token.split('.')[1])); // Manually decoding JWT
|
||||
|
||||
// Access the user's name from the decoded token
|
||||
const userName = decoded.name;
|
||||
|
||||
// Update the user name in the navbar
|
||||
document.getElementById('user-name').textContent = userName;
|
||||
|
||||
// Verify JWT Token expiration
|
||||
const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds
|
||||
if (decoded.exp && decoded.exp < currentTime) {
|
||||
console.warn("Token is expired");
|
||||
localStorage.removeItem('auth_token'); // Remove the expired token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error decoding token:", error);
|
||||
localStorage.removeItem('auth_token'); // Remove invalid token
|
||||
window.location.href = '/'; // Redirect to the login page
|
||||
}
|
||||
} else {
|
||||
// Handle case if no token is available
|
||||
window.location.href = '/'; // Redirect to the login page if no token
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch user stats from the new endpoint
|
||||
const statsRes = await fetch('/api/users/stats', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!statsRes.ok) {
|
||||
throw new Error('Failed to fetch user stats');
|
||||
}
|
||||
|
||||
const stats = await statsRes.json();
|
||||
const userTableBody = document.getElementById('user-table-body');
|
||||
|
||||
// Populate table rows with user stats
|
||||
stats.forEach(userStat => {
|
||||
const userRow = document.createElement('tr');
|
||||
|
||||
userRow.innerHTML = `
|
||||
<td>
|
||||
<a href="#" class="user-link" data-movies='${JSON.stringify(userStat.watchedMovies)}'>${userStat.name}</a>
|
||||
</td>
|
||||
<td>${userStat.watchedCount}</td>
|
||||
<td>${userStat.watchedRatio}</td>
|
||||
`;
|
||||
|
||||
userTableBody.appendChild(userRow);
|
||||
});
|
||||
|
||||
// Add event listener for user links
|
||||
document.querySelectorAll('.user-link').forEach(link => {
|
||||
link.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
const datasetMovies = this.dataset.movies
|
||||
console.log(datasetMovies)
|
||||
const movies = JSON.parse(datasetMovies);
|
||||
|
||||
// Clear the current movie list in the modal
|
||||
const movieList = document.getElementById('movie-list');
|
||||
movieList.innerHTML = '';
|
||||
|
||||
// Populate the modal with the movies the user has watched
|
||||
movies.forEach(movie => {
|
||||
const movieItem = document.createElement('li');
|
||||
movieItem.classList.add('list-group-item');
|
||||
movieItem.textContent = movie.movieTitle;
|
||||
movieList.appendChild(movieItem);
|
||||
});
|
||||
|
||||
// Show the modal
|
||||
const modal = new bootstrap.Modal(document.getElementById('moviesModal'));
|
||||
modal.show();
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error loading user statistics:', error);
|
||||
// localStorage.removeItem('auth_token');
|
||||
// window.location.href = '/';
|
||||
}
|
||||
|
||||
// Log-off functionality
|
||||
document.getElementById('log-off').addEventListener('click', function() {
|
||||
localStorage.removeItem('auth_token');
|
||||
window.location.href = '/';
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,135 @@
|
||||
const express = require("express");
|
||||
const Movie = require("../models/Movie");
|
||||
const User = require("../models/User");
|
||||
const axios = require("axios");
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Fetch movie details from OMDb API
|
||||
async function fetchMovieDetailsFromOmdb(imdb_id) {
|
||||
const apiKey = process.env.OMDB_API; // Replace with your actual OMDb API key
|
||||
const omdbUrl = `https://www.omdbapi.com/?i=${encodeURIComponent(imdb_id)}&apikey=${apiKey}`;
|
||||
|
||||
try {
|
||||
const response = await axios.get(omdbUrl);
|
||||
if (response.data.Response === "True") {
|
||||
return {
|
||||
title: response.data.Title,
|
||||
description: response.data.Plot,
|
||||
rating: response.data.imdbRating,
|
||||
poster: response.data.Poster
|
||||
};
|
||||
} else {
|
||||
throw new Error('Movie not found on OMDb API');
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Error fetching movie details: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Get all movies
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const movies = await Movie.find();
|
||||
res.status(200).json(movies);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get watched movies for the user
|
||||
router.get("/watchedMovies", async (req, res) => {
|
||||
const token = req.headers.authorization?.split(" ")[1]; // Get token from header
|
||||
if (!token) return res.status(401).json({ message: "Token is required" });
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET); // Verify token
|
||||
console.log("Decoded token:", decoded);
|
||||
console.log("Decoded decoded.userId:", decoded.id);
|
||||
const user = await User.findById(decoded.id); // Get user by ID
|
||||
if (!user) return res.status(404).json({ message: "User not found" });
|
||||
|
||||
res.status(200).json(user.watchedMovies); // Return the list of watched movies
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Update watched movies for the user
|
||||
router.patch("/users/updateWatchedMovies", async (req, res) => {
|
||||
const token = req.headers.authorization?.split(" ")[1]; // Get token from header
|
||||
if (!token) return res.status(401).json({ message: "Token is required" });
|
||||
|
||||
const { imdb_id, isChecked } = req.body;
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET); // Verify token
|
||||
const user = await User.findById(decoded.id); // Get user by ID
|
||||
if (!user) return res.status(404).json({ message: "User not found" });
|
||||
|
||||
if (isChecked) {
|
||||
// Add movie to watchedMovies with the watched date if not already added
|
||||
const movieIndex = user.watchedMovies.findIndex(movie => movie.imdb_id === imdb_id);
|
||||
if (movieIndex === -1) {
|
||||
user.watchedMovies.push({ imdb_id, watchedDate: new Date() });
|
||||
}
|
||||
} else {
|
||||
// Remove movie from watchedMovies array
|
||||
user.watchedMovies = user.watchedMovies.filter(movie => movie.imdb_id !== imdb_id);
|
||||
}
|
||||
|
||||
await user.save(); // Save updated user
|
||||
res.status(200).json({ message: "Watched movies updated successfully" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Add movie
|
||||
router.post("/add", async (req, res) => {
|
||||
const { imdb_id, category, vod_link } = req.body;
|
||||
|
||||
try {
|
||||
// Get the token from the Authorization header
|
||||
const token = req.headers.authorization?.split(" ")[1];
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ message: "Authentication token is required" });
|
||||
}
|
||||
|
||||
// Verify and decode the token
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// Check if the user is an admin
|
||||
if (!decoded.admin) {
|
||||
return res.status(403).json({ message: "You do not have admin privileges" });
|
||||
}
|
||||
|
||||
// Fetch movie details from OMDb API
|
||||
const movieDetails = await fetchMovieDetailsFromOmdb(imdb_id);
|
||||
|
||||
// Proceed with adding the movie
|
||||
const movie = new Movie({
|
||||
imdb_id,
|
||||
title: movieDetails.title,
|
||||
description: movieDetails.description,
|
||||
rating: movieDetails.rating,
|
||||
poster: movieDetails.poster,
|
||||
category,
|
||||
vod_link
|
||||
});
|
||||
|
||||
await movie.save();
|
||||
|
||||
res.status(201).json({ message: "Movie added successfully!" });
|
||||
} catch (err) {
|
||||
if (err instanceof jwt.JsonWebTokenError) {
|
||||
return res.status(401).json({ message: "Invalid or expired token" });
|
||||
}
|
||||
res.status(400).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,155 @@
|
||||
const express = require("express");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const jwt = require("jsonwebtoken");
|
||||
const User = require("../models/User");
|
||||
const Movie = require("../models/Movie");
|
||||
const axios = require("axios");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Fetch movie details from OMDb API
|
||||
async function fetchMovieDetailsFromOmdb(imdb_id) {
|
||||
const apiKey = process.env.OMDB_API; // Replace with your actual OMDb API key
|
||||
const omdbUrl = `https://www.omdbapi.com/?i=${encodeURIComponent(imdb_id)}&apikey=${apiKey}`;
|
||||
|
||||
try {
|
||||
const response = await axios.get(omdbUrl);
|
||||
if (response.data.Response === "True") {
|
||||
return {
|
||||
title: response.data.Title.replace(/'/g, "")
|
||||
};
|
||||
} else {
|
||||
throw new Error('Movie not found on OMDb API');
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Error fetching movie details: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware to verify token
|
||||
function verifyToken(req, res, next) {
|
||||
const token = req.headers['authorization'] && req.headers['authorization'].startsWith('Bearer ')
|
||||
? req.headers['authorization'].split(' ')[1]
|
||||
: null;
|
||||
|
||||
if (!token) {
|
||||
return res.status(403).json({ message: "No token provided, access denied." });
|
||||
}
|
||||
|
||||
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
|
||||
if (err) {
|
||||
return res.status(401).json({ message: "Invalid or expired token" });
|
||||
}
|
||||
req.user = decoded; // Store decoded user info for use in routes
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
// Get user stats with watched movie titles and details from OMDb
|
||||
router.get("/stats", verifyToken, async (req, res) => {
|
||||
try {
|
||||
// Fetch all users
|
||||
const users = await User.find();
|
||||
|
||||
// Fetch all movies
|
||||
const allMovies = await Movie.find();
|
||||
const totalMoviesCount = allMovies.length;
|
||||
|
||||
if (totalMoviesCount === 0) {
|
||||
return res.status(400).json({ message: "No movies available in the database." });
|
||||
}
|
||||
|
||||
// Build stats for each user
|
||||
const userStats = await Promise.all(users.map(async (user) => {
|
||||
// Get watched movie IMDb IDs
|
||||
const watchedMovies = user.watchedMovies
|
||||
.map((wm) => wm.imdb_id) // Extract IMDb ID
|
||||
.filter((imdb_id) => allMovies.some((m) => m.imdb_id === imdb_id)); // Ensure the movie exists in the database
|
||||
|
||||
const watchedCount = watchedMovies.length;
|
||||
const watchedRatio = ((watchedCount / totalMoviesCount) * 100).toFixed(1);
|
||||
|
||||
// Fetch movie details from OMDb for each watched movie
|
||||
const movieDetailsPromises = watchedMovies.map(async (imdb_id) => {
|
||||
try {
|
||||
const movieTitle = (await fetchMovieDetailsFromOmdb(imdb_id)).title;
|
||||
return {
|
||||
imdb_id,
|
||||
movieTitle
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(`Error fetching details for movie with IMDb ID: ${imdb_id}`);
|
||||
return { imdb_id, error: err.message };
|
||||
}
|
||||
});
|
||||
|
||||
const movieTitle = await Promise.all(movieDetailsPromises);
|
||||
|
||||
return {
|
||||
name: user.name,
|
||||
watchedCount,
|
||||
totalMoviesCount,
|
||||
watchedRatio: `${watchedRatio}%`,
|
||||
watchedMovies: movieTitle // Include movie details
|
||||
};
|
||||
}));
|
||||
|
||||
res.json(userStats);
|
||||
} catch (err) {
|
||||
console.error("Erreur dans l'extraction des statistiques sur les utilisateurs :", err);
|
||||
res.status(500).json({ error: "Internal server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Register User
|
||||
router.post("/register", async (req, res) => {
|
||||
const { name, email, password, role } = req.body;
|
||||
|
||||
try {
|
||||
if (!password) {
|
||||
throw new Error("Le mot de passe est obligatoire et ne peut être indéfini");
|
||||
}
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
const user = new User({ name, email, password: hashedPassword, role });
|
||||
await user.save();
|
||||
res.status(201).json({ message: "L'utilisateur s'est enregistré avec succès !" });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Login User
|
||||
router.post("/login", async (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
try {
|
||||
const user = await User.findOne({ email });
|
||||
if (!user) return res.status(404).json({ message: "L'utilisateur n'a pas été trouvé" });
|
||||
|
||||
const isMatch = await bcrypt.compare(password, user.password);
|
||||
if (!isMatch) return res.status(401).json({ message: "Informations d'identification non valides" });
|
||||
|
||||
// Check if the user role is 69 and set the admin flag
|
||||
const isAdmin = user.role === 69;
|
||||
|
||||
// Create a token with the user ID, name, and admin flag if the user is an admin
|
||||
const token = jwt.sign(
|
||||
{ id: user._id, name: user.name, admin: isAdmin }, // Include name in the token payload
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: "1h" }
|
||||
);
|
||||
|
||||
res.status(200).json({ token });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Protected route to get movies (example)
|
||||
router.get("/movies", verifyToken, async (req, res) => {
|
||||
// Only authorized users will reach this point
|
||||
const movies = await Movie.find(); // Assuming Movie model exists
|
||||
res.json(movies);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||