Auto commit: 2025-11-13T12:17:45.030Z

This commit is contained in:
Flatlogic Bot 2025-11-13 12:17:45 +00:00
parent b219b2f787
commit 9a0ee35f75
10 changed files with 394 additions and 8 deletions

34
api/favorites.php Normal file
View File

@ -0,0 +1,34 @@
<?php
session_start();
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'error' => 'User not logged in.']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
$video_id = $data['video_id'] ?? null;
$title = $data['title'] ?? null;
$thumbnail = $data['thumbnail'] ?? null;
if (!$video_id || !$title || !$thumbnail) {
echo json_encode(['success' => false, 'error' => 'Invalid data.']);
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO favorites (user_id, video_id, title, thumbnail) VALUES (:user_id, :video_id, :title, :thumbnail)");
$stmt->execute(['user_id' => $_SESSION['user_id'], 'video_id' => $video_id, 'title' => $title, 'thumbnail' => $thumbnail]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) { // Duplicate entry
echo json_encode(['success' => false, 'error' => 'Already in favorites.']);
} else {
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}

View File

@ -3,14 +3,15 @@ document.addEventListener('DOMContentLoaded', function () {
const resultsSection = document.getElementById('results'); const resultsSection = document.getElementById('results');
const resultsTitle = document.getElementById('results-title'); const resultsTitle = document.getElementById('results-title');
const videoGrid = document.getElementById('video-grid'); const videoGrid = document.getElementById('video-grid');
const isLoggedIn = document.body.dataset.loggedIn === 'true';
// Hardcoded YouTube video IDs for different moods // Hardcoded YouTube video IDs for different moods
const musicDatabase = { const musicDatabase = {
happy: ['3_w0dsiud4E', 'ZbZSe6N_BXs', 'r5Mozr0B-4o'], happy: [{id: 'y6Sxv-sUYtM', title: 'Pharrell Williams - Happy'}, {id: 'HgzGwKwLmgM', title: 'Queen - Don\'t Stop Me Now'}, {id: 'iPUmE-tne5s', title: 'Katrina & The Waves - Walking On Sunshine'}],
sad: ['h1YVae0pKnA', 'RB-RcX5DS5A', 'co512-p_gA8'], sad: [{id: 'hLQl3WQQoQ0', title: 'Adele - Someone Like You'}, {id: '8AHCfZTRGiI', title: 'Johnny Cash - Hurt'}, {id: 'XFkzRNyygfk', title: 'Radiohead - Creep'}],
energetic: ['_tV5LEBDs7w', 'l-sZyfFX4F0', 'q9d57g_m_dw'], energetic: [{id: 'v2AC41dglnM', title: 'AC/DC - Thunderstruck'}, {id: 'o1tj2zJ2Wvg', title: 'Guns N\' Roses - Welcome to the Jungle'}, {id: 'CD-E-LDc384', title: 'Metallica - Enter Sandman'}],
calm: ['5qap5aO4i9A', 'lFcLg2hQjdc', 'DWcJFNfaw9c'], calm: [{id: 'vNwYtllyt3Q', title: 'Brian Eno - Music for Airports 1/1'}, {id: 'S-Xm7s9eGxU', title: 'Erik Satie - Gymnopédie No. 1'}, {id: 'U3u4pQ44e14', title: 'Claude Debussy - Clair de Lune'}],
upbeat: ['9d8SzG4FPyM', 'fK_zwl-lnmc', '0-7IHOXkiV8'] upbeat: [{id: 'FGBhQbmPwH8', title: 'Daft Punk - One More Time'}, {id: 'sy1dYFGkPUE', title: 'Justice - D.A.N.C.E.'}, {id: 'Cj8JrQ9w5jY', title: 'LCD Soundsystem - Daft Punk Is Playing at My House'}]
}; };
moodButtons.forEach(button => { moodButtons.forEach(button => {
@ -33,7 +34,7 @@ document.addEventListener('DOMContentLoaded', function () {
resultsTitle.textContent = `Here's your ${mood} playlist`; resultsTitle.textContent = `Here's your ${mood} playlist`;
resultsSection.style.display = 'block'; resultsSection.style.display = 'block';
videos.forEach(videoId => { videos.forEach(video => {
const col = document.createElement('div'); const col = document.createElement('div');
col.className = 'col-lg-4 col-md-6'; col.className = 'col-lg-4 col-md-6';
@ -41,13 +42,22 @@ document.addEventListener('DOMContentLoaded', function () {
videoContainer.className = 'video-container'; videoContainer.className = 'video-container';
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube.com/embed/${videoId}`; iframe.src = `https://www.youtube.com/embed/${video.id}`;
iframe.title = 'YouTube video player'; iframe.title = 'YouTube video player';
iframe.frameBorder = '0'; iframe.frameBorder = '0';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'; iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true; iframe.allowFullscreen = true;
videoContainer.appendChild(iframe); videoContainer.appendChild(iframe);
if (isLoggedIn) {
const saveButton = document.createElement('button');
saveButton.className = 'btn btn-sm btn-outline-light mt-2';
saveButton.textContent = 'Save to favorites';
saveButton.addEventListener('click', () => saveToFavorites(video.id, video.title));
videoContainer.appendChild(saveButton);
}
col.appendChild(videoContainer); col.appendChild(videoContainer);
videoGrid.appendChild(col); videoGrid.appendChild(col);
}); });
@ -59,4 +69,22 @@ document.addEventListener('DOMContentLoaded', function () {
resultsSection.style.display = 'none'; resultsSection.style.display = 'none';
} }
} }
function saveToFavorites(videoId, title) {
fetch('/api/favorites.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ video_id: videoId, title: title, thumbnail: `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg` })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Saved to favorites!');
} else {
alert('Error: ' + data.error);
}
});
}
}); });

24
db/migrate.php Normal file
View File

@ -0,0 +1,24 @@
<?php
require_once __DIR__ . '/config.php';
function run_migrations() {
$pdo = db();
$migrations_dir = __DIR__ . '/migrations';
$files = glob($migrations_dir . '/*.sql');
sort($files);
foreach ($files as $file) {
$sql = file_get_contents($file);
if ($sql) {
try {
$pdo->exec($sql);
echo "Migration from $file ran successfully.\n";
} catch (PDOException $e) {
echo "Error running migration from $file: " . $e->getMessage() . "\n";
}
}
}
}
run_migrations();

View File

@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS `favorites` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`video_id` VARCHAR(255) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`thumbnail` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `user_video` (`user_id`, `video_id`),
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

66
favorites.php Normal file
View File

@ -0,0 +1,66 @@
<?php
session_start();
require_once __DIR__ . '/db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
$favorites = [];
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT video_id, title, thumbnail FROM favorites WHERE user_id = :user_id ORDER BY created_at DESC");
$stmt->execute(['user_id' => $_SESSION['user_id']]);
$favorites = $stmt->fetchAll();
} catch (PDOException $e) {
// Handle error
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Favorites - MusicBox</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<header class="app-header">
<div class="logo">
<h1><a href="index.php">MusicBox</a></h1>
</div>
<nav>
<a href="favorites.php" class="btn">My Favorites</a>
<a href="logout.php" class="btn">Logout</a>
</nav>
</header>
<main class="container">
<section class="favorites-list">
<h2>My Favorites</h2>
<?php if (empty($favorites)): ?>
<p>You haven't saved any favorites yet.</p>
<?php else: ?>
<div class="video-grid">
<?php foreach ($favorites as $fav): ?>
<div class="video-container">
<a href="https://www.youtube.com/watch?v=<?php echo htmlspecialchars($fav['video_id']); ?>" target="_blank">
<img src="<?php echo htmlspecialchars($fav['thumbnail']); ?>" alt="<?php echo htmlspecialchars($fav['title']); ?>">
<h3><?php echo htmlspecialchars($fav['title']); ?></h3>
</a>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</section>
</main>
<footer class="app-footer">
<p>&copy; <?php echo date('Y'); ?> MusicBox. All rights reserved.</p>
</footer>
</body>
</html>

View File

@ -1,3 +1,4 @@
<?php session_start(); ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
@ -21,11 +22,20 @@
<!-- Custom CSS --> <!-- Custom CSS -->
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>"> <link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head> </head>
<body> <body data-logged-in="<?php echo isset($_SESSION['user_id']) ? 'true' : 'false'; ?>">
<nav class="navbar navbar-expand-lg navbar-dark"> <nav class="navbar navbar-expand-lg navbar-dark">
<div class="container"> <div class="container">
<a class="navbar-brand" href="#">musicbox</a> <a class="navbar-brand" href="#">musicbox</a>
<div>
<?php if (isset($_SESSION['user_id'])): ?>
<a href="favorites.php" class="btn btn-outline-light me-2">My Favorites</a>
<a href="logout.php" class="btn btn-outline-light">Logout</a>
<?php else: ?>
<a href="login.php" class="btn btn-outline-light me-2">Login</a>
<a href="register.php" class="btn btn-light">Register</a>
<?php endif; ?>
</div>
</div> </div>
</nav> </nav>

93
login.php Normal file
View File

@ -0,0 +1,93 @@
<?php
session_start();
require_once __DIR__ . '/db/config.php';
$errors = [];
if (isset($_SESSION['user_id'])) {
header('Location: index.php');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'A valid email is required.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, password FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
header('Location: index.php');
exit;
} else {
$errors[] = 'Invalid email or password.';
}
} catch (PDOException $e) {
$errors[] = 'Database error: ' . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - MusicBox</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<header class="app-header">
<div class="logo">
<h1><a href="index.php">MusicBox</a></h1>
</div>
<nav>
<a href="register.php" class="btn">Register</a>
</nav>
</header>
<main class="container">
<section class="auth-form">
<h2>Login</h2>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="login.php" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</section>
</main>
<footer class="app-footer">
<p>&copy; <?php echo date('Y'); ?> MusicBox. All rights reserved.</p>
</footer>
</body>
</html>

6
logout.php Normal file
View File

@ -0,0 +1,6 @@
<?php
session_start();
session_unset();
session_destroy();
header('Location: login.php');
exit;

102
register.php Normal file
View File

@ -0,0 +1,102 @@
<?php
require_once __DIR__ . '/db/config.php';
$errors = [];
$success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($username)) {
$errors[] = 'Username is required.';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'A valid email is required.';
}
if (empty($password) || strlen($password) < 8) {
$errors[] = 'Password must be at least 8 characters long.';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username OR email = :email");
$stmt->execute(['username' => $username, 'email' => $email]);
if ($stmt->fetch()) {
$errors[] = 'Username or email already exists.';
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
$stmt->execute(['username' => $username, 'email' => $email, 'password' => $hashed_password]);
$success = true;
}
} catch (PDOException $e) {
$errors[] = 'Database error: ' . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register - MusicBox</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<header class="app-header">
<div class="logo">
<h1><a href="index.php">MusicBox</a></h1>
</div>
<nav>
<a href="login.php" class="btn">Login</a>
</nav>
</header>
<main class="container">
<section class="auth-form">
<h2>Create an Account</h2>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success">
<p>Registration successful! You can now <a href="login.php">login</a>.</p>
</div>
<?php else: ?>
<form action="register.php" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" minlength="8" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
<?php endif; ?>
</section>
</main>
<footer class="app-footer">
<p>&copy; <?php echo date('Y'); ?> MusicBox. All rights reserved.</p>
</footer>
</body>
</html>