diff --git a/config/config.php b/config/config.php deleted file mode 100644 index c53a8f7..0000000 --- a/config/config.php +++ /dev/null @@ -1,10 +0,0 @@ -load(); if ($_ENV['TEST'] === false) { throw new Exception("Environment variables not loaded"); +} else if ($_ENV['APP_ENV'] === 'local') { + error_reporting(E_ALL); + ini_set('display_errors', 1); +} else { + error_reporting(0); + ini_set('display_errors', 0); + ini_set('log_errors', 1); } session_start(); define('DOC_ROOT', dirname(__DIR__)); -require DOC_ROOT . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'; - spl_autoload_register(function ($class) { $file = str_replace("\\", DIRECTORY_SEPARATOR, $class); $path = DOC_ROOT . DIRECTORY_SEPARATOR . "src" . DIRECTORY_SEPARATOR . "php" . DIRECTORY_SEPARATOR . $file . ".php"; diff --git a/db/create_db.sql b/db/create_db.sql index 6f6988f..20988e5 100644 --- a/db/create_db.sql +++ b/db/create_db.sql @@ -1,3 +1,4 @@ +DROP TABLE IF EXISTS api_tokens; DROP TABLE IF EXISTS rating; DROP TABLE IF EXISTS tokens; DROP TABLE IF EXISTS playlist; diff --git a/public/acceptFriend.php b/public/acceptFriend.php index 616595e..07b2ba4 100644 --- a/public/acceptFriend.php +++ b/public/acceptFriend.php @@ -1,79 +1,61 @@ getConnection(); - echo 'empezamos conexion'; $stmt = $db->prepare("INSERT INTO friends (USER_NAME, FRIEND_NAME) VALUES (:username, :friend)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':friend', $friend); $result1 = $stmt->execute(); - echo 'paso 1'; - $stmt = $db->prepare("INSERT INTO friends (USER_NAME, FRIEND_NAME) VALUES (:friend, :username)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':friend', $friend); $result2 = $stmt->execute(); - echo 'paso 2'; - $stmt = $db->prepare("DELETE FROM requests WHERE REQUEST_USER = :friend AND REQUESTED_USER = :username"); $stmt->bindParam(':username', $username); $stmt->bindParam(':friend', $friend); $result3 = $stmt->execute(); - echo 'paso 3'; - $result = $result1 && $result2 && $result3; // Ambas consultas deben ser exitosas header("Location: ./usuario.php?mensaje=Ahora sois amigos :)"); exit(); - } elseif($rechazar != null) { - echo 'empezamos conexion rechazar'; - // Código para rechazar la solicitud de amistad + } elseif ($rechazar != null) { $db = DbConnection::getInstance()->getConnection(); - - echo "DELETE FROM requests WHERE REQUEST_USER = " . $username . " AND REQUESTED_USER = " . $friend . ""; - + $stmt = $db->prepare("DELETE FROM requests WHERE REQUEST_USER = :friend AND REQUESTED_USER = :username"); $stmt->bindParam(':username', $username); $stmt->bindParam(':friend', $friend); $result4 = $stmt->execute(); - //header("Location: ./usuario.php?mensaje=Solicitud rechazada"); - header("Location: ./usuario.php?mensaje=DELETE FROM requests WHERE REQUEST_USER = " . $username . " AND REQUESTED_USER = " . $friend); + header("Location: ./usuario.php?mensaje=Solicitud rechazada"); exit(); - + } - - echo 'El usuario introducido no existe o ya ha sido añadido'; - + + if ($result) { - header("Location: ./usuario.php?mensaje=Ahora sois amigos :)"); exit(); } else { - - echo "Error: " . $stmt->errorInfo()[2]; + header("Location: ./usuario.php?mensaje=Hubo un problema, vuelve a intentarlo :("); + exit(); } } \ No newline at end of file diff --git a/public/anadirPlaylist.php b/public/anadirPlaylist.php index c09edf3..4465f6b 100644 --- a/public/anadirPlaylist.php +++ b/public/anadirPlaylist.php @@ -5,28 +5,23 @@ $url = $_POST['urlPlaylist']; $username = $_POST['username']; - // Extract the URL between src=" and " - //preg_match('/src="([^"]*)"/', $url, $matches); - //$url = $matches[1] ?? ''; - - echo 'Esta playlist ya ha sido añadida por otro usuario.'; - - try{ + try { $db = DbConnection::getInstance()->getConnection(); $stmt = $db->prepare("INSERT INTO playlist VALUES (?, ?)"); $result = $stmt->execute([$url, $username]); - + if ($result) { // Redirect to index.php on success - header("Location: ./index.php?playlist=".$url."&mensaje=Playlist añadida correctamente"); + header("Location: ./index.php?mensaje=Playlist añadida correctamente"); exit(); } else { // Echo error message on failure - header("Location: ./index.php?playlist=".$url."&error=Esta playlist ya ha sido añadida por otro usuario"); - echo "Error: " . $stmt->errorInfo()[2]; + header("Location: ./index.php?playlist=" . $url . "&mensaje=Esta playlist ya ha sido añadida por otro usuario :("); + exit(); } - }catch(error){ - echo "Error: " . $error; + } catch (Exception $error) { + header("Location: ./index.php?playlist=" . $url . "&mensaje=Esta playlist ya ha sido añadida por otro usuario :("); + exit(); } header("Location: ./index.php?playlist=".$url."&error=Esta playlist ya ha sido añadida por otro usuario"); diff --git a/public/cambiarPsswd.php b/public/cambiarPsswd.php index 4575e58..f9d86a9 100644 --- a/public/cambiarPsswd.php +++ b/public/cambiarPsswd.php @@ -37,149 +37,152 @@ - - - - Cambiar Contraseña - - -
- Music-Life -
- - - - - -
-
- -
-

Nueva contraseña

-
-

Para usuario:

-
-

-
- - -
+ + +
+ Music-Life +
+ + + + + +
+
+ +
+

Nueva contraseña

+
+

Para usuario:

+
+

+
+ + +
+
-
- + diff --git a/public/contacto.php b/public/contacto.php index c24e4fc..b75e85d 100644 --- a/public/contacto.php +++ b/public/contacto.php @@ -11,113 +11,76 @@ ?> - - - - -
-
-

Formulario de Contacto


- -
- - -
- - - - -
- - - - - - - - -
- - - - - - - - -

- - -
- - - -
+ +

+ + + + + +
- - - - - +
+ + + + + \ No newline at end of file diff --git a/public/css/navbar.css b/public/css/navbar.css index 4343377..f165fac 100644 --- a/public/css/navbar.css +++ b/public/css/navbar.css @@ -149,6 +149,7 @@ video { /* Ajusta el padding aquí */ padding: 0px; box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1); + height: 50px; } #navbarNav ul { @@ -160,6 +161,7 @@ video { .navbar a { font-size: 20px; text-decoration: none; + padding: 0; } .nav-item { @@ -191,6 +193,8 @@ video { #mensaje { display: none; text-align: center; + font-weight: bold; + background-color: grey; z-index: 100; position: absolute; top: 5%; diff --git a/public/css/nuevocss.css b/public/css/nuevocss.css index e9d6b43..231f687 100644 --- a/public/css/nuevocss.css +++ b/public/css/nuevocss.css @@ -1,7 +1,9 @@ body { background-color: rgb(126, 177, 174); } - +.ocultar{ + display: none; +} /* CUERPO */ #apartado { @@ -626,7 +628,7 @@ iframe { margin: 0 10px; } -.btnEditarValoracion, .btnFavValoracion { +.btnEditarValoracion, .btnFavValoracion, .btnAnadirValoracion { border-radius: 100px; padding: 10px 20px; margin: 1%; @@ -638,7 +640,7 @@ iframe { transition: opacity 0.5s, transform 0.5s; /* Añadir transición aquí */ } -.btnEditarValoracion:hover, .btnFavValoracion:hover { +.btnEditarValoracion:hover, .btnFavValoracion:hover, .btnAnadirValoracion:hover { cursor: pointer; opacity: 1; transform: scale(1.1); diff --git a/public/css/spotify-lab.css b/public/css/spotify-lab.css index 911d6fb..7c6a224 100644 --- a/public/css/spotify-lab.css +++ b/public/css/spotify-lab.css @@ -7,8 +7,9 @@ --title-text: #f9fbfad5; --background-user: #d4d5d6; } -/* clase para ocualtar elementos con JS */ -.ocultar{ + +/* clase para ocultar elementos con JS */ +.ocultar { display: none; } @@ -28,6 +29,7 @@ body { height: 75vh; width: 90%; z-index: 1; + margin-bottom: 60px; } .lab-panel { @@ -44,7 +46,7 @@ body { padding: 20px; } -.genero-item{ +.genero-item { padding: 10px 20px; border: none; border-radius: 30px; @@ -59,7 +61,7 @@ body { margin-bottom: 20px; } -#cont-generos{ +#cont-generos { display: flex; flex-direction: column; justify-content: center; @@ -68,13 +70,13 @@ body { margin-bottom: 6%; } -.cont-btn-generos{ +.cont-btn-generos { display: grid; grid-template-columns: 50% 50%; width: 100%; } -.lab-form{ +.lab-form { width: 80%; display: flex; flex-direction: column; @@ -84,13 +86,13 @@ body { font-weight: 500; } -.lab-form input{ - width: 100%; +.lab-form input { + width: 90%; border-radius: 4px; border-style: none; } -.lab-form input[type="range"]{ +.lab-form input[type="range"] { height: 15px; background: white; outline: none; @@ -98,7 +100,7 @@ body { transition: opacity 0.2s; } -.lab-form input[type="range"]::-webkit-slider-thumb{ +.lab-form input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 25px; @@ -108,7 +110,7 @@ body { border-radius: 50%; } -.lab-form input[type="range"]::-moz-range-thumb{ +.lab-form input[type="range"]::-moz-range-thumb { width: 25px; height: 25px; background: blue; @@ -117,36 +119,27 @@ body { } -#valorTempo{ +#valorTempo { margin-bottom: 5%; } -.lab-form button{ +.lab-form button { font-size: 15px; padding: 10px; border-radius: 30px; width: 30%; - background-color: rgb(76, 253, 94); + background-color: rgb(87, 238, 102); margin: auto; border-style: none; } -.lab-form button:hover{ +.lab-form button:hover { border-right: 5px solid; border-left: 5px solid; border-color: rgba(67, 155, 222, 0.5); transition: ease-in-out 0.2s; } -/* No funciona TODO: */ -/* .user-pic-lg { - width: 670px; - height: 670px; - border-radius: 100%; - transform: scale(1.1); - box-shadow: 0 0 10px 10px rgba(73, 223, 215, 0.762); -} */ - .lab-resultado-container { display: flex; flex-direction: column; @@ -159,12 +152,13 @@ body { padding: 40px; } -.lab-intro{ +.lab-intro { display: flex; flex-direction: row-reverse; align-self: flex-end; } -.lab-intro #getInfo{ + +.lab-intro #getInfo { background-color: #f3f3f3; height: 30px; width: 30px; @@ -175,7 +169,7 @@ body { cursor: pointer; } -#info{ +#info { background-color: rgb(200, 246, 241); border-radius: 20px; text-align: center; @@ -185,7 +179,7 @@ body { margin: 0 1%; } -.lab-intro{ +.lab-intro { position: absolute; top: 5%; right: 2%; @@ -212,8 +206,8 @@ body { .valoracion { width: 100%; */ - /* Hacer que la valoración ocupe todo el ancho disponible en su área */ - /* margin: 10px; +/* Hacer que la valoración ocupe todo el ancho disponible en su área */ +/* margin: 10px; border-radius: 20px; background-color: rgba(255, 255, 255, 0.211); padding: 10px; @@ -223,12 +217,43 @@ body { grid-area: musica; } +/* #btnEnviar{ + background-color: #f3f3f3; + border-radius: 30px; + padding: 10px; + border-style: none; + cursor: pointer; +} */ + +.spotify-playlists { + display: flex; + flex: wrap; + justify-items: center; +} + +.spotify-playlist { + width: 40%; +} + +#btnEnviar { + font-size: 17px; + padding: 10px; + border-radius: 30px; + width: 30%; + background-color: rgb(180, 87, 238); + margin: auto; + border-style: none; + :hover { + cursor: pointer; + } +} + @media screen and (max-width: 1200px) { /* Modal Info */ - .lab-intro{ + .lab-intro { position: absolute; top: 0; right: 0; @@ -298,5 +323,4 @@ body { .musica { grid-area: musica; } - } \ No newline at end of file diff --git a/public/css/usuario.css b/public/css/usuario.css index a26c1cf..bbd7dcb 100644 --- a/public/css/usuario.css +++ b/public/css/usuario.css @@ -26,6 +26,7 @@ body { height: 75vh; width: 90%; z-index: 1; + margin-bottom: 60px; } .usuario { @@ -188,6 +189,17 @@ body { width: 30%; } +.bloquePV2{ + margin: 25px; + width: 100%; +} + +.playlistPerfil{ +margin: 25px; +} + + + @media screen and (max-width: 1200px) { @@ -234,7 +246,7 @@ body { /* background-color: rgba(255, 255, 255, 0.239); border-radius: 50px 50px 5px 5px; */ padding: 10px; - margin-bottom: 30px; + margin-bottom: 120px; } .valoraciones { @@ -268,6 +280,11 @@ body { align-items: center; justify-content: center; flex-direction: column; + margin-bottom: 50px; + } + + .playlistPerfil{ + width: 100%; } .verPlaylists{ @@ -277,10 +294,15 @@ body { width: 100%; } - .bloquePV{ + .bloquePV, + .bloquePV2{ margin: 0; margin-bottom: 10px; width: 100%; } + .playlistPerfil{ + margin: 0; + } + } \ No newline at end of file diff --git a/public/google-login-api.php b/public/google-login-api.php index 2b9deea..b43327c 100644 --- a/public/google-login-api.php +++ b/public/google-login-api.php @@ -11,38 +11,40 @@ // $client_id, $redirect_uri & $client_secret come from the settings // $code is the code passed to the redirect url -function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) { - $url = 'https://www.googleapis.com/oauth2/v4/token'; - - - $curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code'; - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); - $data = json_decode(curl_exec($ch), true); - $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE); - if($http_code != 200) - throw new Exception('Error : Failed to receieve access token'); - - return $data; +function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) +{ + $url = 'https://www.googleapis.com/oauth2/v4/token'; + + + $curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code=' . $code . '&grant_type=authorization_code'; + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); + $data = json_decode(curl_exec($ch), true); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($http_code != 200) + throw new Exception('Error : Failed to receieve access token'); + + return $data; } // $access_token is the access token you got earlier -function GetUserProfileInfo($access_token) { - $url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email'; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token)); - $data = json_decode(curl_exec($ch), true); - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if($http_code != 200) - throw new Exception('Error : Failed to get user information'); - - return $data; +function GetUserProfileInfo($access_token) +{ + $url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email'; + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token)); + $data = json_decode(curl_exec($ch), true); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($http_code != 200) + throw new Exception('Error : Failed to get user information'); + + return $data; } diff --git a/public/index.php b/public/index.php index ef6751b..d0de522 100644 --- a/public/index.php +++ b/public/index.php @@ -36,13 +36,22 @@ } ?>
+ + '; + echo $_GET['mensaje']; + echo '
'; + } + ?> +
@@ -51,7 +60,7 @@ $pdo = DbConnection::getInstance(); // $urls = $pdo->showAllPlaylists(); - $urls = $pdo->showAllPlaylistsRandom(4); + $urls = $pdo->showAllPlaylistsRandom(3); // Generar los iframes con las URLs seleccionadas foreach ($urls as $url) { echo ' - - - - -
+
-
- +
+ +
Debes entrar a tu cuenta para poder valorar

'; + echo '

Debes estar logueado para poder valorar

'; } ?>
@@ -234,23 +252,23 @@ class="btn btn-primary-subtle rounded-pill btnBuscar">Buscar $groupedRatings[$link][] = $rating; } foreach ($groupedRatings as $link => $ratingsForLink) { - // echo ''; - // echo ''; - // $active = ''; + echo ''; + echo ''; + $active = ''; ?> - -
@@ -425,8 +442,11 @@ class="btn btn-primary-subtle rounded-pill btnBuscar">Buscar
cookie2
+ + + diff --git a/public/js/BusquedaSpotify.js b/public/js/BusquedaSpotify.js deleted file mode 100644 index 9897727..0000000 --- a/public/js/BusquedaSpotify.js +++ /dev/null @@ -1,19 +0,0 @@ -// Este código cambia el src de la url del iframe en la página de búsqueda de Spotify. Solo eso. -let consulta = document.getElementById('nombrePlaylist'); -let iframeBuscador = document.getElementById('iframeBusqueda'); -let botonBuscar = document.getElementById('botonBusca'); - -botonBuscar.addEventListener('click', buscarLista); - -function buscarLista() { - console.log('a'); - let contenidoIframe = consulta.value; - let match = contenidoIframe.match(/src="(.*?)"/); - - if (match && match[1]) { - let url = match[1]; - iframeBuscador.src = url; - } else { - console.error("No se pudo encontrar la URL en el atributo src del iframe."); - } -} \ No newline at end of file diff --git a/public/js/app.html b/public/js/app.html deleted file mode 100644 index 59209af..0000000 --- a/public/js/app.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - Spotify Search - - - -
-
- - -
- -
- -
-
-
- - - - diff --git a/public/js/app.js b/public/js/app.js deleted file mode 100644 index 8608117..0000000 --- a/public/js/app.js +++ /dev/null @@ -1,104 +0,0 @@ -const searchButton = document.getElementById('botonBuscar') - -async function getAccessToken() { - const authParams = new URLSearchParams({ - grant_type: 'client_credentials', - client_id: 'sustituye por tu client_id', - client_secret: 'sustituye_por_tu_client_secret', - }); - - const response = await fetch('https://accounts.spotify.com/api/token', { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - body: authParams, - }); - console.log(response); - const data = await response.json(); - accessToken = data.access_token; - console.log(accessToken); -} - -// Función para buscar artista y obtener sus álbumes -async function search() { - alert('Buscando...'); - const searchInput = document.getElementById('urlPlaylist').value; - const artistParams = { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - }, - }; - - // Obtener el ID del artista - const artistResponse = await fetch( - `https://api.spotify.com/v1/search?q=${searchInput}&type=playlist&limit=3`, - artistParams - ); - const artistData = await artistResponse.json(); - const artistID = artistData.artists.items[0].id; - - // Obtener los álbumes del artista - const albumsResponse = await fetch( - `https://api.spotify.com/v1/artists/${artistID}/albums?include_groups=album&market=US&limit=5`, - artistParams - ); - const albumsData = await albumsResponse.json(); - - displayAlbums(albumsData.items); -} - -// Función para mostrar los álbumes en el DOM -function displayAlbums(albums) { - const albumContainer = document.getElementById('album-container'); - albumContainer.innerHTML = ''; // Limpiar contenido previo - - albums.forEach((album) => { - const albumCard = document.createElement('div'); - albumCard.className = 'card'; - - const albumImg = document.createElement('img'); - albumImg.className = 'card-img'; - albumImg.src = album.images[0].url; - - const cardBody = document.createElement('div'); - cardBody.className = 'card-body'; - - const cardTitle = document.createElement('h5'); - cardTitle.className = 'card-title'; - cardTitle.textContent = album.name; - - const cardText = document.createElement('p'); - cardText.className = 'card-text'; - cardText.innerHTML = `Release Date:
${album.release_date}`; - - const cardButton = document.createElement('a'); - cardButton.className = 'card-button'; - cardButton.href = album.external_urls.spotify; - cardButton.textContent = 'Album Link'; - - cardBody.appendChild(cardTitle); - cardBody.appendChild(cardText); - cardBody.appendChild(cardButton); - - albumCard.appendChild(albumImg); - albumCard.appendChild(cardBody); - - albumContainer.appendChild(albumCard); - }); -} - -// Obtener el token de acceso al cargar la página -getAccessToken(); - -// Añadir evento de búsqueda al botón -searchButton.addEventListener('click', search); - -// Añadir evento de búsqueda al presionar Enter -searchButton.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { - search(); - } -}); \ No newline at end of file diff --git a/public/js/cargaCss.js b/public/js/cargaCss.js index 20c9ced..4d29d1c 100644 --- a/public/js/cargaCss.js +++ b/public/js/cargaCss.js @@ -10,12 +10,15 @@ if(window.location.href.includes('spotifyLab')){ `; -}else if(window.location.href.includes('index') || window.location.href === 'music-lifes.es'){ +} +/*else if(window.location.href.includes('index') || window.location.href === 'http://www.music-life.es' +|| window.location.href === 'http://localhost/ML5/public/'){ head.innerHTML += ` `; -}else if(window.location.href.includes('login')){ +}*/ +else if(window.location.href.includes('login')){ head.innerHTML += ` `; diff --git a/public/js/editarValoraciones.js b/public/js/editarValoraciones.js index 32f4dd4..3c70397 100644 --- a/public/js/editarValoraciones.js +++ b/public/js/editarValoraciones.js @@ -1,6 +1,13 @@ let btnsEditarValoracion = document.getElementsByClassName('btnEditarValoracion'); let btnEliminarValoracion = document.getElementsByClassName('btnEliminarValoracion'); let valoracionPreview = document.getElementsByClassName('verValoracion'); +let formLike = document.getElementById('buscador3'); +let formValorarBuscador = document.getElementById('valoracionBuscador'); +let btnNewValoracion = document.querySelector('.btnAnadirValoracion'); +// formValorarBuscador.addEventListener('submit', (e)=>{ +// e.preventDefault(); +// console.log(formValorarBuscador); +// }); document.addEventListener('DOMContentLoaded', ()=>{ @@ -83,7 +90,38 @@ document.addEventListener('DOMContentLoaded', ()=>{ }); } + //esto habra que cambiarlo en caso de añadir el fav en mas sitios + // formLike.addEventListener('submit', (e)=>{ + // e.preventDefault(); + // console.log(formLike); + // }); + btnNewValoracion.addEventListener('click', (e)=>{ + const urlPlaylistCont = document.getElementById('iframeBusqueda'); + + if(e.target.matches('button')){ + let urlPlaylist2 = document.getElementById('urlPlaylist2'); + urlPlaylist2.value = urlPlaylistCont.src; + formValorarBuscador.parentNode.classList.toggle('ocultar'); + }else if(e.target.matches('i')){ + let urlPlaylist2 = document.getElementById('urlPlaylist2'); + urlPlaylist2.value = urlPlaylistCont.src; + formValorarBuscador.parentNode.classList.toggle('ocultar'); + } + }); + const favValoracion = document.querySelector('.btnFavValoracion'); + const urlPlaylist = formLike.querySelector('#urlPlaylist'); + favValoracion.addEventListener('click', (e)=>{ + const urlPlaylistCont = document.getElementById('iframeBusqueda'); + urlPlaylist.value = urlPlaylistCont.src; + if(e.target.matches('button')){ + const btnGuardar = document.getElementById('btnGuardar'); + btnGuardar.click(); + }else if(e.target.matches('i')){ + const btnGuardar = document.getElementById('btnGuardar'); + btnGuardar.click(); + } + }); }); diff --git a/public/js/lab.js b/public/js/lab.js index 51c8836..433a014 100644 --- a/public/js/lab.js +++ b/public/js/lab.js @@ -8,11 +8,10 @@ for(let genero of arrGeneros){ let currentValues = inpGenero.value ? inpGenero.value.split(',') : []; let value = e.target.textContent.toLowerCase(); - if(currentValues.length < 5 && !currentValues.includes(value)){ + if(currentValues.length < 2 && !currentValues.includes(value)){ currentValues.push(value); inpGenero.value = currentValues.join(','); } - }); } @@ -28,142 +27,37 @@ function limpiarCadenaGenero(){ /**-----------> Colores aleatorios boton */ document.addEventListener('DOMContentLoaded', ()=>{ - // const buttons = document.querySelectorAll('.genero-item') for(let btn of arrGeneros){ const greenShade = getRandomGreenShade(); btn.style.backgroundColor = greenShade; } }); - function getRandomGreenShade(){ const r = 200 + Math.floor(Math.random()*55); const g = 200 + Math.floor(Math.random()*55); const b = 200 + Math.floor(Math.random()*55); const color = `rgb(${r}, ${g}, ${b})` - return color; } /**-----------> Slider tempo */ - let inpTempo = document.getElementById('tempo'); inpTempo.addEventListener('click', ()=>{ let tempoValue = inpTempo.value; let tempoSpan = document.getElementById('valorTempo'); tempoSpan.textContent = tempoValue; - // tempoSpan.innerHTML = tempoValue; + console.log(tempoValue); }); /**-----------> Boton info */ - const btnInfo = document.getElementById('getInfo'); const infoModal = document.getElementById('info'); btnInfo.addEventListener('click', ()=>{ infoModal.classList.toggle('ocultar'); }); -// let codeFlowToken; -// async function getAccessToken() { -// codeFlowToken = document.cookie.split('; ').find(row => row.startsWith('labsToken')).split('=')[1]; -// console.log(codeFlowToken); -// } - -// getAccessToken(); -// console.log(codeFlowToken); - -// async function fetchWebApi(endpoint, method, body = null) { -// console.log(`Fetching data from API: ${endpoint}`); -// try { -// const res = await fetch(`https://api.spotify.com/${endpoint}`, { -// headers: { -// Authorization: `Bearer ${codeFlowToken}`, -// }, -// method, -// body: body ? JSON.stringify(body) : null, -// }); - -// if (!res.ok) { -// // Lanza un error si la respuesta no es exitosa -// throw new Error(`API call failed with status: ${res.statusText}`); -// } - -// return await res.json(); -// } catch (error) { -// // Manejo de errores de la red o al llamar a la API -// console.error("Error fetching data from API:", error); -// return null; -// } -// } - -// async function getTopTracks() { -// // Endpoint reference : https://developer.spotify.com/documentation/web-api/reference/get-users-top-artists-and-tracks -// const response = await fetchWebApi('v1/me/top/tracks?time_range=long_term&limit=6', 'GET'); -// console.log(response.items); -// return response.items; -// } - -// async function getRecommendations(seedTracksIds) { -// // Endpoint reference : https://developer.spotify.com/documentation/web-api/reference/get-recommendations -// const response = await fetchWebApi( -// `v1/recommendations?limit=9&seed_tracks=${seedTracksIds.join(',')}`, 'GET' -// ); -// console.log(response.tracks); -// return response.tracks; -// } - -// async function createPlaylist(tracksUri) { -// const { id: user_id } = await fetchWebApi('v1/me', 'GET') - -// const playlist = await fetchWebApi( -// `v1/users/${user_id}/playlists`, 'POST', { -// "name": "Music-Life Lab recommendations", -// "description": "Playlist created in the Music-Life Lab", -// "public": false -// }); - -// await fetchWebApi( -// `v1/playlists/${playlist.id}/tracks`, 'POST', { -// uris: tracksUri -// }); - -// return playlist; -// } - -// async function generatePlaylist() { -// const topTracks = await getTopTracks(); -// console.log( -// topTracks?.map( -// ({ name, artists }) => -// `${name} by ${artists.map(artist => artist.name).join(', ')}` -// ) -// ); - -// const topTracksIds = topTracks.map(track => track.id); -// const recommendedTracks = await getRecommendations(topTracksIds); -// console.log( -// recommendedTracks.map( -// ({ name, artists }) => -// `${name} by ${artists.map(artist => artist.name).join(', ')}` -// ) -// ); - -// const tracksUri = recommendedTracks.map(track => track.uri); -// const createdPlaylist = await createPlaylist(tracksUri); -// console.log(createdPlaylist.name, createdPlaylist.id); - -// document.getElementById('playlistContainer').innerHTML = ` -// `; -// } - +/**-----------> API */ let codeFlowToken; async function getAccessToken() { @@ -204,7 +98,7 @@ async function fetchWebApi(endpoint, method, body = null) { } async function getTopTracks() { - const response = await fetchWebApi('v1/me/top/tracks?time_range=long_term&limit=6', 'GET'); + const response = await fetchWebApi('v1/me/top/tracks?time_range=long_term&limit=3', 'GET'); if (response && response.items) { console.log(response.items); return response.items; @@ -214,10 +108,23 @@ async function getTopTracks() { } } -async function getRecommendations(seedTracksIds) { - const response = await fetchWebApi( - `v1/recommendations?limit=9&seed_tracks=${seedTracksIds.join(',')}`, 'GET' - ); +async function getRecommendations(seedTracksIds, seedGenres, targetEnergy) { + + let endpoint = `v1/recommendations?limit=15`; + + if (seedGenres && seedGenres.length > 0) { + endpoint += `&seed_genres=${encodeURIComponent(seedGenres.join(','))}`; + } + + if (Array.isArray(seedTracksIds) && seedTracksIds.length != 0) { + endpoint += `&seed_tracks=${encodeURIComponent(seedTracksIds.join(','))}`; + } + + if (targetEnergy) { + endpoint += `&target_energy=${targetEnergy}`; + } + + const response = await fetchWebApi(endpoint, 'GET'); if (response && response.tracks) { console.log(response.tracks); return response.tracks; @@ -233,11 +140,12 @@ async function createPlaylist(tracksUri) { console.error('Failed to fetch user info'); return null; } - + let playlistName = document.getElementById('playlistName').value; + console.log('playlistName:', playlistName); const userId = userResponse.id; const playlistResponse = await fetchWebApi( `v1/users/${userId}/playlists`, 'POST', { - "name": "Music-Life Lab recommendations", + "name": playlistName || "Music-Life Lab", "description": "Playlist created in the Music-Life Lab", "public": false } @@ -258,24 +166,37 @@ async function createPlaylist(tracksUri) { } async function generatePlaylist() { + console.log('generando playlist'); await getAccessToken(); // Ensure token is obtained if (!codeFlowToken) { console.error('No valid token found'); return; } - + console.log('token bien'); + const topTracks = await getTopTracks(); if (topTracks.length === 0) { console.error('No top tracks available'); return; } + console.log('topTracks bien'); const topTracksIds = topTracks.map(track => track.id); - const recommendedTracks = await getRecommendations(topTracksIds); + if (!Array.isArray(topTracksIds) || topTracksIds.length === 0) { + console.error('No valid top tracks IDs'); + return; + } + console.log('topTracksIds:', topTracksIds); + + let seedGenres = inpGenero.value ? inpGenero.value.split(',') : null; + let targetEnergy = inpTempo.value ? parseFloat(inpTempo.value) : null; + + const recommendedTracks = await getRecommendations(topTracksIds, seedGenres, targetEnergy); if (recommendedTracks.length === 0) { console.error('No recommendations available'); return; } + console.log('recomendaciones bien'); const tracksUri = recommendedTracks.map(track => track.uri); const createdPlaylist = await createPlaylist(tracksUri); @@ -283,12 +204,13 @@ async function generatePlaylist() { console.error('Playlist creation failed'); return; } - + console.log('playlist creada bien'); console.log(createdPlaylist.name, createdPlaylist.id); + document.getElementById('playlistContainer').innerHTML = ` `; } +btnEnviar.addEventListener('click', generatePlaylist); + +// https://api.spotify.com/v1/recommendations?seed_artists=4NHQUGzhtTLFvgF5SZesLK&seed_genres=classical%2Ccountry&seed_tracks=0c6xIDDpzE81m2q797ordA + +// https://api.spotify.com/v1/recommendations?seed_genres=classical%2Ctechno&seed_tracks=0c6xIDDpzE81m2q797ordA%2CC0nLMjIuOsMjEq4IKuJ2twa%2C57dlsdCfq4XUf2AvIMk1jS&target_tempo=0.85 + +// https://api.spotify.com/v1/recommendations?limit=15&seed_genres=jazz%2Cindie%2Crock&seed_tracks=5lxZ3KmRdRn6iW5tE1Fwjp%2C5tMLIgw6yxobsAyIVvfHo5%2C0GdiWLQt5VYtMEcero6AOW%2C0nLMjIuOsMjEq4IKuJ2twa%2C57dlsdCfq4XUf2AvIMk1jS&target_energy=0.75 + + +// https://api.spotify.com/v1/recommendations?seed_genres=classical%2Ctechno&seed_tracks=%275lxZ3KmRdRn6iW5tE1Fwjp%27%2C+%275tMLIgw6yxobsAyIVvfHo5%27%2C+%270GdiWLQt5VYtMEcero6AOW%27%2C+%270nLMjIuOsMjEq4IKuJ2twa%27%2C+%2757dlsdCfq4XUf2AvIMk1jS%27&target_tempo=0.85 + +// https://api.spotify.com/v1/recommendations?seed_genres=classical%2Cindie&seed_tracks=5lxZ3KmRdRn6iW5tE1Fwjp%2C5tMLIgw6yxobsAyIVvfHo5%2C0GdiWLQt5VYtMEcero6AOW%2C0nLMjIuOsMjEq4IKuJ2twa%2C57dlsdCfq4XUf2AvIMk1jS - btnEnviar.addEventListener('click', generatePlaylist); \ No newline at end of file diff --git a/public/js/playlists.js b/public/js/playlists.js deleted file mode 100644 index 023f637..0000000 --- a/public/js/playlists.js +++ /dev/null @@ -1,64 +0,0 @@ -const searchButton = document.getElementById('botonBuscar') -const inputBusqueda = document.getElementById('inputBusqueda'); -const iframeBuscador = document.getElementById('iframeBusqueda'); - -async function getAccessToken() { - const authParams = new URLSearchParams({ - grant_type: 'client_credentials', - client_id: 'sustituye por tu client_id', - client_secret: 'sustituye_por_tu_client_secret', - }); - - const response = await fetch('https://accounts.spotify.com/api/token', { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - body: authParams, - }); - const data = await response.json(); - accessToken = data.access_token; -} - -// Función para buscar artista y obtener sus álbumes -async function search() { - alert('Buscando...'); - const searchInput = inputBusqueda.value; - const artistParams = { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - }, - }; - - // Obtener listado de playlists - const artistResponse = await fetch( - `https://api.spotify.com/v1/search?q=${searchInput}&type=playlist&limit=3`, - artistParams - ); - const playlistsArray = await artistResponse.json(); - console.log(playlistsArray); - const playlistID = playlistsArray.playlists.items[0].id; - console.log(playlistID); - - swapIframe(playlistID); -} - -function swapIframe(playlistID) { - iframeBuscador.src = `https://open.spotify.com/embed/playlist/${playlistID}`; -} - -// Obtener el token de acceso al cargar la página -getAccessToken(); - -// Añadir evento de búsqueda al botón -searchButton.addEventListener('click', search); - -// Añadir evento de búsqueda al presionar Enter -inputBusqueda.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { - alert('Bu.'); - search(); - } -}); \ No newline at end of file diff --git a/public/js/playlistsAPI.js b/public/js/playlistsAPI.js index 0753754..32c9290 100644 --- a/public/js/playlistsAPI.js +++ b/public/js/playlistsAPI.js @@ -67,7 +67,9 @@ document.addEventListener('DOMContentLoaded', (event) => { var urlPlaylist = document.getElementById('urlPlaylist'); + var urlPlaylist2 = document.getElementById('urlPlaylist2'); urlPlaylist.value = `https://open.spotify.com/embed/playlist/${playlistID}`; + urlPlaylist2.value = `https://open.spotify.com/embed/playlist/${playlistID}`; userCookie = document.cookie.split('; ').find(row => row.startsWith('USER')); if (userCookie) { diff --git a/public/js/script.js b/public/js/script.js index 1832230..e545dde 100644 --- a/public/js/script.js +++ b/public/js/script.js @@ -41,13 +41,16 @@ function toggleModoOscuro() { //var login var body = document.querySelector('body'); // var modo oscuro: -var videoFondo = document.getElementById('videoFondo'); -var elementosNavbar = document.getElementsByClassName('textoCabecera'); -var logoCargar = document.getElementById('logo'); -var formaSpotify = document.getElementsByClassName('formaSpotify'); +const videoFondo = document.getElementById('videoFondo'); +const elementosNavbar = document.getElementsByClassName('textoCabecera'); +//const logoCargar = document.getElementById('logo'); +const formaSpotify = document.getElementsByClassName('formaSpotify'); var textoContacto = document.getElementsByClassName('textoContacto'); var inputBusqueda = document.getElementById('inputBusqueda'); var navBar = document.getElementsByClassName('navBar'); +var mensaje = document.getElementById('mensaje'); +var buscadorUsuarios = document.getElementById('buscadorUsuarios'); +var btnEditarIcono = document.getElementById('btnEditarIcono'); var textoSpotify = document.getElementsByClassName('textoSpotify'); var apartado = document.querySelectorAll('#apartado'); @@ -113,11 +116,22 @@ function setModoOnLoad() { inputBusqueda.style.backgroundColor = 'rgb(50,50,50)'; } - for (var i = 0; i < textElements.length; i++) { textElements[i].style.color = 'white'; } + if(mensaje){ + mensaje.style.backgroundColor = 'rgb(50,50,50)'; + } + + if(buscadorUsuarios){ + buscadorUsuarios.style.backgroundColor = 'rgb(50,50,50)'; + } + + if(btnEditarIcono){ + btnEditarIcono.style.backgroundColor = 'rgb(50,50,50)'; + } + } else { if (pagina === 'spotify.html') { videoFondo.src = './img/FondoSpotifyClaro.mp4'; @@ -164,7 +178,16 @@ function setModoOnLoad() { textElements[i].style.color = 'black'; } if(inputBusqueda){ - inputBusqueda.style.backgroundColor = 'white'; + inputBusqueda.style.backgroundColor = 'white'; + } + if(mensaje){ + mensaje.style.backgroundColor = 'rgb(255,255,255)'; + } + if(buscadorUsuarios){ + buscadorUsuarios.style.backgroundColor = 'rgb(255,255,255)'; + } + if(btnEditarIcono){ + btnEditarIcono.style.backgroundColor = 'rgb(255,255,255)'; } //textoCabecera.style.color = 'black'; diff --git a/public/js/star-rating.js b/public/js/star-rating.js index 70c72ef..4621646 100644 --- a/public/js/star-rating.js +++ b/public/js/star-rating.js @@ -7,7 +7,6 @@ valoraciones.forEach(valoracion => { const commentInput = valoracion.querySelector('.comment'); const submitButton = valoracion.querySelector('.submit-button'); const ratingValue = valoracion.querySelector('.rating-value'); - // const botonDesplegable = valoracion.querySelector('.botonDesplegable'); const sectorComentarios = valoracion.querySelector('.listaComentarios'); var selectedRating = null; @@ -24,15 +23,17 @@ valoraciones.forEach(valoracion => { if(valoracion.querySelector('.btnsValoracion') || valoracion.querySelector('.editarValoracionCont')){ let btnEdit = valoracion.parentNode.parentNode.querySelector('.btnEditarValoracion'); - btnEdit.addEventListener('click', (e)=>{ - if(e.target.matches('button') || e.target.matches('i')){ - let ratingActual = valoracion.querySelector('.valoracionExistente').firstElementChild.textContent; - let indice = ratingActual.substring(0, 1); - console.log(indice); - selectedRating = indice; - updateRating(); - } - }); + if(btnEdit){ + btnEdit.addEventListener('click', (e)=>{ + if(e.target.matches('button') || e.target.matches('i')){ + let ratingActual = valoracion.querySelector('.valoracionExistente').firstElementChild.textContent; + let indice = ratingActual.substring(0, 1); + console.log(indice); + selectedRating = indice; + updateRating(); + } + }); + } } diff --git a/public/json/playlistPorDefecto.json b/public/json/playlistPorDefecto.json index f520b80..9035ef9 100644 --- a/public/json/playlistPorDefecto.json +++ b/public/json/playlistPorDefecto.json @@ -19,12 +19,6 @@ "https://open.spotify.com/embed/playlist/37i9dQZF1DX4WYpdgoIcn6", "https://open.spotify.com/embed/playlist/37i9dQZF1DXcRXFNfZr7Tp", "https://open.spotify.com/embed/playlist/37i9dQZF1DX4dyzvuaRJ0n", - "https://open.spotify.com/embed/playlist/37i9dQZF1DXcF6B6QPhFDv", - "https://open.spotify.com/embed/playlist/37i9dQZF1DX0XUsuxWHRQd", - "https://open.spotify.com/embed/playlist/37i9dQZF1DX1lVhptIYRda", - "https://open.spotify.com/embed/playlist/37i9dQZF1DX10zKzsJ2jva", - "https://open.spotify.com/embed/playlist/37i9dQZF1DX4JAvHpjipBk", - "https://open.spotify.com/embed/playlist/37i9dQZF1DX4E3UdUs7fUx", "https://open.spotify.com/embed/playlist/37i9dQZF1DX4SBhb3fqCJd", "https://open.spotify.com/embed/playlist/37i9dQZF1DXcZDD7cfEKhW", "https://open.spotify.com/embed/playlist/37i9dQZF1DX4WYpdgoIcn6", diff --git a/public/login.php b/public/login.php index 2a21a6c..3bd6d7c 100644 --- a/public/login.php +++ b/public/login.php @@ -1,138 +1,104 @@ errors))){ -// $mailer = Mailer::obtenerInstancia(); -// $mailer->enviarCorreo($userMail, $motivo, $nombre, $mensajeExtra); -// } - ?> - -
- -
- - -
-
- -
-

Iniciar sesión

-
- -
-
- -
-
-

¿Primera vez aquí?

Crear cuenta -
-
-

¿Olvidaste la contraseña?

-
- - -
- +
+
+ + +

Iniciar sesión

+
+ +
+
+ +
+
+

¿Primera vez aquí?

Crear cuenta +
+ + + + +
+ +
+ + + +
+

Registro

+
+ +
+
+ +
+
+ +
+
+ +
+ +
+ +
+
+

¿Ya tiene una cuenta?

Conectarse +
+ +
+ + +
+

Recupera tu contraseña

+
+

Email

+

+ +
+
+
+ +
- +
+ - -
-

Registro

-
- -
-
- -
-
- -
-
- -
- -
- -
-
-

¿Ya tiene una cuenta?

Conectarse -
- -
- - -
-

Recupera tu contraseña

-
-

Email

- -
-
-
- - -
-
-
- -
- 0) : ?> -
- -
  • - -
  • - -
    - - - - 0) { ?> -
    - -
  • - -
  • - -
    - +
    + 0): ?> +
    + +
  • + +
  • + +
    + + + + 0) { ?> +
    + +
  • + +
  • +
    - + +
    + \ No newline at end of file diff --git a/public/mailer/cambiarPsswd.php b/public/mailer/cambiarPsswd.php deleted file mode 100644 index e71b180..0000000 --- a/public/mailer/cambiarPsswd.php +++ /dev/null @@ -1,225 +0,0 @@ -getConnection(); - - $sql = 'SELECT USERID FROM TOKENS WHERE TIPO = "RECOVERY" AND EXPIRES > NOW() AND TOKEN = :TOKEN'; - $stmt = $conn->prepare($sql); - - $stmt->bindParam(':TOKEN', $token, PDO::PARAM_STR); - - $stmt->execute(); - - // comprobar si funciono (mediante ver el mensaje que nos sale siempre en tyerminal etc) - $rowCount = $stmt->rowCount(); - - if ($rowCount > 0) { - //echo "token recibido con éxito."; - - $result = $stmt->fetch(PDO::FETCH_ASSOC); - $mail = $result['USERID']; - //header("Location: login.php?contrasenaCambiada=true"); - //exit(); // Detiene la ejecución del script después de enviar el encabezado de redirección - } else { - $mensaje = "El link ha expirado"; - header("Location: login.php?mensaje=$mensaje&error=true"); - exit(); - } -} catch (PDOException $pe) { - die("No se pudo conectar a la base de datos $dbname: " . $pe->getMessage()); -} finally { - $conn = null; // Cerramoos -} ?> - - - - - - - Cambiar Contraseña - - -
    - Music-Life -
    - - - - - -
    -
    - -
    -

    Nueva contraseña

    -
    -

    Para usuario:

    -
    -

    -
    - - -
    -
    -
    - - - - - - - - -errors))){ -// $mailer = MailerSingleton::obtenerInstancia(); -// $mailer->enviarCorreo($userMail, $motivo, $nombre, $mensajeExtra); -// } - -?> \ No newline at end of file diff --git a/public/mailer/cambiarPsswd2.php b/public/mailer/cambiarPsswd2.php deleted file mode 100644 index 992ab0b..0000000 --- a/public/mailer/cambiarPsswd2.php +++ /dev/null @@ -1,44 +0,0 @@ -getConnection(); - // Establecer el modo de error de PDO para excepciones - $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - $sql = "UPDATE user SET PASSWORD = :new_psswd WHERE EMAIL = :email"; - $stmt = $conn->prepare($sql); - - // Hashear la nueva contraseña - $hashPsswd = password_hash($new_psswd, PASSWORD_DEFAULT); - - $stmt->bindParam(':new_psswd', $hashPsswd, PDO::PARAM_STR); - $stmt->bindParam(':email', $email, PDO::PARAM_STR); - - $stmt->execute(); - - // Comprobar si se actualizó alguna fila - $rowCount = $stmt->rowCount(); - - if ($rowCount > 0) { - echo "Contraseña cambiada con éxito."; - header("Location: login.php?contrasenaCambiada=true"); - exit(); // Detiene la ejecución del script después de enviar el encabezado de redirección - } else { - echo "No se encontró el usuario o la contraseña no se cambió."; - header("Location: login.php?contrasenaCambiada=false"); - exit(); - } - -} catch (PDOException $pe) { - die("No se pudo conectar a la base de datos $dbname: " . $pe->getMessage()); -} finally { - $db->closeConnection(); -} diff --git a/public/mailer/mailer2.php b/public/mailer/mailer2.php deleted file mode 100644 index 358f6c0..0000000 --- a/public/mailer/mailer2.php +++ /dev/null @@ -1,56 +0,0 @@ -SMTPDebug = false; // or $mail->SMTPDebug = 0; - $mail->isSMTP(); // Send using SMTP - $mail->Host = 'smtp-relay.brevo.com'; // Set the SMTP server to send through - $mail->SMTPAuth = true; // Enable SMTP authentication - $mail->Username = 'sergiosahi25@gmail.com'; // SMTP username - $mail->Password = 'CDLYQwFST8gPJa32'; // SMTP password - $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged - $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above - - // From email address and name - $mail->setFrom('music-life@support.es', 'Soporte Music Life'); - - // To email addresss - $mail->addAddress($email); // Agrega el destinatario obtenido del formulario - $mail->addReplyTo('support@music-life.es', 'Reply'); // Recipent reply address - //$mail->addCC('sergiosahi25@gmail.com'); - //$mail->addBCC('sergiosahi25@gmail.com'); - - // Content - $mail->isHTML(true); // Set email format to HTML - $mail->Subject = $subject; - $mail->Body = $body; - $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; - - $mail->send(); - header("Location: http://music-life.es"); - exit(); - - //echo '

    Correo enviado, por favor revisa tu bandeja de entrada :)

    Volver a la web

    '; - - } catch (Exception $e) { - echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; - } -} \ No newline at end of file diff --git a/public/mailer/recuperarPsswd.php b/public/mailer/recuperarPsswd.php deleted file mode 100644 index 6856ed7..0000000 --- a/public/mailer/recuperarPsswd.php +++ /dev/null @@ -1,95 +0,0 @@ -getConnection(); - - $sql = 'SELECT * FROM user WHERE EMAIL = :USERID'; - $stmt = $conn->prepare($sql); - - $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); //ESTO FALTA OBTENER DEL FORMULARIO EL CORREO - - $stmt->execute(); - - if ($stmt->rowCount() > 0) { //Comprobamos si ese usuario existe, si no pues no seguimos - - try { - echo "Procesando peticion"; - $sql = 'DELETE FROM tokens WHERE TIPO = "RECOVERY" AND USERID = :USERID'; - $stmt = $conn->prepare($sql); - $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); //ESTO FALTA OBTENER DEL FORMULARIO EL CORREO - echo "."; - $stmt->execute(); - echo "."; - - $sql = "INSERT INTO tokens (TOKEN, USERID, EXPIRES,TIPO) VALUES(:TOKEN, :USERID, :EXPIRES, 'RECOVERY')"; - $stmt = $conn->prepare($sql); - echo "."; - - // Asignar valores a los parámetros - $stmt->bindParam(':TOKEN', $token, PDO::PARAM_STR); - $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); - $stmt->bindParam(':EXPIRES', $fechaExpiracion, PDO::PARAM_STR); - echo "."; - - $stmt->execute(); - echo "."; - - $creacionToken = true; - echo "."; - - } catch (PDOException $pe) { - die("No se pudo generar el token de usuario: " . $pe->getMessage()); - } - - } else { - echo "No se encontró ese correo entre nuestros usuarios"; - echo $CORREO; - } - -}catch (PDOException $pe) { - die("No se pudo comprobar si el usuario existe: " . $pe->getMessage()); -} finally { - //echo "Cerramos la conexion"; - $db->closeConnection(); -} - -if ($creacionToken == true) { - //echo "Se ha creado el token"; - // Si todo ha ido bien, mandamos los datos al mailer - $link = "
    "; - - $link .= "

    Soporte Music Life

    \n
    Has solicitado un cambio de contrasena para music-life.es.

    Tienes disponible durante 24 horas este link para poder hacerlo \n
    \n
    "; - $link .= "Cambiar contrasena
    "; - $link .= " href='http://music-life.es/mailer/cambiarPsswd?token=$token' "; - - //CAMBIAR ESTO AL SUBITR A INTENET - //$link .= "Cambiar contrasena
    "; - //http://localhost:3000/src/php/recuperarPsswd.php - $redirection = "index.php"; - -$redirection = "index.php"; - - // Crear un formulario dinámicamente con campos ocultos - echo '
    '; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    '; - - // Agregar JavaScript para enviar el formulario automáticamente - echo ''; - exit; -} \ No newline at end of file diff --git a/public/mailer2.php b/public/mailer2.php index 256c307..28f57a4 100644 --- a/public/mailer2.php +++ b/public/mailer2.php @@ -22,12 +22,12 @@ try { $mail->SMTPDebug = false; // or $mail->SMTPDebug = 0; $mail->isSMTP(); // Send using SMTP - $mail->Host = 'smtp-relay.brevo.com'; // Set the SMTP server to send through - $mail->SMTPAuth = true; // Enable SMTP authentication - $mail->Username = 'sergiosahi25@gmail.com'; // SMTP username - $mail->Password = 'CDLYQwFST8gPJa32'; // SMTP password + $mail->Host = 'smtp-relay.brevo.com'; // Set the SMTP server to send through + $mail->SMTPAuth = true; // Enable SMTP authentication + $mail->Username = 'sergiosahi25@gmail.com'; // SMTP username + $mail->Password = 'CDLYQwFST8gPJa32'; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged - $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above + $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above // From email address and name $mail->setFrom('music-life@support.es', 'Soporte Music Life'); @@ -41,13 +41,12 @@ // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $subject; - $mail->Body = $body; + $mail->Body = $body; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); header("Location: http://music-life.es?mensaje=Correo enviado, por favor revisa tu bandeja de entrada :)"); exit(); - //echo '

    Correo enviado, por favor revisa tu bandeja de entrada :)

    Volver a la web

    '; } catch (Exception $e) { diff --git a/public/mailer3.php b/public/mailer3.php new file mode 100644 index 0000000..ef22e4c --- /dev/null +++ b/public/mailer3.php @@ -0,0 +1,55 @@ +Motivo de contacto:

    $motivo

    "; + if ($motivo === 'otro') { + $body .= "

    Especificar:

    "; + $body .= "

    $otroMotivoTexto

    "; + } + $body .= "

    Nombre:

    $nombre

    "; + $body .= "

    Correo:

    $userMail

    "; + $body .= "

    Mensaje:

    "; + $body .= "

    $mensajeExtra

    "; + + + try { + $mail->SMTPDebug = false; + $mail->isSMTP(); + $mail->Host = 'smtp-relay.brevo.com'; + $mail->SMTPAuth = true; + $mail->Username = 'sergiosahi25@gmail.com'; + $mail->Password = 'CDLYQwFST8gPJa32'; + $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; + $mail->Port = 587; + + $mail->setFrom('music-life@support.es', 'Soporte Music Life'); + + $mail->addAddress('sergiosahi25@gmail.com'); + $mail->addReplyTo('support@music-life.es', 'Reply'); + + $mail->isHTML(true); + $mail->Subject = 'Soporte M-L'; + $mail->Body = $body; + $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; + + $mail->send(); + header("Location: http://music-life.es/index.php?mensaje=Correo enviado, por favor revisa tu bandeja de entrada :)"); + exit(); + + } catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; + } +} \ No newline at end of file diff --git a/public/oauthSpotifyLibrary.php b/public/oauthSpotifyLibrary.php index 663c592..c489d39 100644 --- a/public/oauthSpotifyLibrary.php +++ b/public/oauthSpotifyLibrary.php @@ -15,11 +15,15 @@ // Later, after Spotify redirects to your redirect URI if (isset($_GET['code'])) { $state = $_GET['state']; + //console log de php + $storedState = $_SESSION['state']; // Fetch the stored state value from somewhere. A session for example if ($state !== $storedState) { // The state returned isn't the same as the one we've stored, we shouldn't continue - header('Location: ' . DOC_ROOT . '/public/index.php'); + $msje = "Error al conectar con Spotify"; + $mensajeCodificado = urlencode($msj); + header("Location: http://music-life.es/index.php?mensaje=" . $mensajeCodificado); die('State mismatch'); } @@ -33,7 +37,10 @@ $_SESSION['accessToken'] = $accessToken; $_SESSION['refreshToken'] = $refreshToken; $userName = $_SESSION['user']; - + + //TODO save tokens to database, if $_SESSION['user'] is set + // and flag the user as spotifyOAuthed true. so next time the user logs in, we can check if the user is already connected to spotify + // $mdb = DbConnection::getInstance(); // $mdb->saveTokensToDatabase($userName, $accessToken, $refreshToken); @@ -46,10 +53,11 @@ $_SESSION['state'] = $state; $options = [ 'scope' => [ - 'user-read-email', - 'user-read-private', + 'user-read-email', + 'user-read-private', + 'user-top-read', 'playlist-read-private', - 'playlist-read-collaborative', + 'playlist-read-collaborative', 'playlist-modify-private', 'playlist-modify-public', ], diff --git a/public/perfil.php b/public/perfil.php index e111347..67077cb 100644 --- a/public/perfil.php +++ b/public/perfil.php @@ -1,137 +1,206 @@ -
    - - -
    -

    Playlists compartidas

    - showUserPlaylistsRandom($perfil, 0); - //$active = 'active'; - - if ($links) { - echo '
    '; - foreach ($links as $link) { - //echo '
    '; - echo ''; - //$active = ''; - //echo '
    '; + + + + + if (isset($_SESSION['user'])) { + $username = $_SESSION['user']; } - echo '
    '; + if (isset($_SESSION['user']) && !empty($_SESSION['user'])) { + $pdo2 = DbConnection::getInstance(); + $rating = $pdo2->showUserRatings($username, $link); - } else { - echo 'Todavia no ha subido ninguna playlist!'; + if ($rating) { + echo '
    '; + echo '

    ' . $rating['SCORE'] . '/5 ⭐

    '; + echo '
    '; + } else { + ?> + + + +
    +
    +
    Sin Valoración aún
    + +
    +
    + '; + echo '

    Debes estar logueado para valorar

    '; + echo '
    '; + } + echo '
    '; } - ?> -
    + + } else { + echo 'Todavia no ha subido ninguna playlist!'; + } + echo ''; + ?> + - - - - - - - - - + + + + + + + + diff --git a/public/recuperarPsswd.php b/public/recuperarPsswd.php index 2c783a1..6e3251f 100644 --- a/public/recuperarPsswd.php +++ b/public/recuperarPsswd.php @@ -1,6 +1,7 @@ getConnection(); + $mdb = DbConnection::getInstance(); + $db = $mdb->getConnection(); $sql = 'SELECT * FROM user WHERE EMAIL = :USERID'; - $stmt = $conn->prepare($sql); + $stmt = $db->prepare($sql); $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); //ESTO FALTA OBTENER DEL FORMULARIO EL CORREO - $stmt->execute(); if ($stmt->rowCount() > 0) { //Comprobamos si ese usuario existe, si no pues no seguimos try { - echo "Procesando peticion"; $sql = 'DELETE FROM tokens WHERE TIPO = "RECOVERY" AND USERID = :USERID'; - $stmt = $conn->prepare($sql); + $stmt = $db->prepare($sql); $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); //ESTO FALTA OBTENER DEL FORMULARIO EL CORREO - echo "."; $stmt->execute(); - echo "."; - + $sql = "INSERT INTO tokens (TOKEN, USERID, EXPIRES,TIPO) VALUES(:TOKEN, :USERID, :EXPIRES, 'RECOVERY')"; - $stmt = $conn->prepare($sql); - echo "."; - - // Asignar valores a los parámetros + $stmt = $db->prepare($sql); + $stmt->bindParam(':TOKEN', $token, PDO::PARAM_STR); $stmt->bindParam(':USERID', $CORREO, PDO::PARAM_STR); $stmt->bindParam(':EXPIRES', $fechaExpiracion, PDO::PARAM_STR); - echo "."; - + $stmt->execute(); - echo "."; $creacionToken = true; - echo "."; - + } catch (PDOException $pe) { - die("No se pudo generar el token de usuario: " . $pe->getMessage()); - } - + header("Location: ./login.php?mensaje=No se pudo generar el token de usuario :("); + exit(); + } + } else { - echo "No se encontró ese correo entre nuestros usuarios"; - echo $CORREO; + header("Location: ./login.php?mensaje=Mail no encontrado :("); + exit(); } -}catch (PDOException $pe) { - die("No se pudo comprobar si el usuario existe: " . $pe->getMessage()); +} catch (PDOException $pe) { + header("Location: ./login.php?mensaje=No encontramos al usuario :("); + exit(); } finally { - //echo "Cerramos la conexion"; - $db->closeConnection(); + $mdb->closeConnection(); } if ($creacionToken == true) { - //echo "Se ha creado el token"; - // Si todo ha ido bien, mandamos los datos al mailer $link = "
    "; $link .= "

    Soporte Music Life

    \n
    Has solicitado un cambio de contrasena para music-life.es.

    Tienes disponible durante 24 horas este link para poder hacerlo \n
    \n
    "; $link .= "Cambiar contrasena
    "; - //CAMBIAR ESTO AL SUBITR A INTENET - //$link .= "Cambiar contrasena"; - //http://localhost:3000/src/php/recuperarPsswd.php - $redirection = "index.php"; -$redirection = "index.php"; + $redirection = "index.php"; // Crear un formulario dinámicamente con campos ocultos echo '
    '; @@ -85,7 +72,6 @@ echo ''; echo ''; echo '
    '; - // Agregar JavaScript para enviar el formulario automáticamente echo ''; exit; diff --git a/public/requestFriend.php b/public/requestFriend.php index ab1aaac..abba2ed 100644 --- a/public/requestFriend.php +++ b/public/requestFriend.php @@ -1,31 +1,29 @@ getConnection(); - $stmt = $db->prepare("INSERT INTO requests (REQUEST_USER, REQUESTED_USER) VALUES (:username, :search)"); - $result = $stmt->execute([$username, $search]); - - if ($result) { - - header("Location: ./usuario.php?mensaje=Solicitud enviada correctamente"); - exit(); - } else { - - echo "Error: " . $stmt->errorInfo()[2]; - header("Location: ./usuario.php?mensaje=El usuario introducido no existe"); + try { + $db = DbConnection::getInstance()->getConnection(); + $stmt = $db->prepare("INSERT INTO requests (REQUEST_USER, REQUESTED_USER) VALUES (:username, :search)"); + $result = $stmt->execute([':username' => $username, ':search' => $search]); + if ($result) { + header("Location: ./usuario.php?mensaje=Solicitud enviada correctamente :)"); + exit(); + } else { + header("Location: ./usuario.php?mensaje=El usuario introducido no existe :("); + exit(); + } + } catch (Exception $error) { + header("Location: ./usuario.php?mensaje=El usuario introducido no existe :("); + exit(); } } \ No newline at end of file diff --git a/public/spotify.html b/public/spotify.html index 0a49565..ac5232c 100644 --- a/public/spotify.html +++ b/public/spotify.html @@ -1,118 +1,125 @@ - - - - - Spotify - Music Life - - - - - - - - -
    - -
    - + ---------LOGIN linea 60 0) : ?> -
    +
  • diff --git a/public/templates/header.php b/public/templates/header.php index 3bbc7dd..4df965a 100644 --- a/public/templates/header.php +++ b/public/templates/header.php @@ -52,8 +52,8 @@ - + + - - -
    - -
    - \ No newline at end of file diff --git a/public/usuario.php b/public/usuario.php index b4dfcfa..1abdf76 100644 --- a/public/usuario.php +++ b/public/usuario.php @@ -10,133 +10,156 @@ exit(); } +if (isset($_GET['mensaje'])) { + echo '
    '; + echo $_GET['mensaje']; + echo '
    '; +} ?> -
    -