Skip to content

Commit

Permalink
Update search and add new route API #27
Browse files Browse the repository at this point in the history
  • Loading branch information
Jhonatanjacome07 committed Dec 6, 2024
1 parent 21a16d9 commit 354bc49
Show file tree
Hide file tree
Showing 7 changed files with 305 additions and 33 deletions.
2 changes: 1 addition & 1 deletion frontend/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ["cdn-images.dzcdn.net"], // Dominio para poder trabajar con las imagenes
domains: ["cdn-images.dzcdn.net", "api.deezer.com"], //rutas para las imagenes de las canciones
},
};

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/(page)/explore/components/SongItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface SongItemProps {
title_short: string;
duration: string;
preview: string;
md5_image: string;
md5_image: string | null;
artist: string;
artistImage: string;
genres: string;
Expand Down
78 changes: 62 additions & 16 deletions frontend/src/app/(page)/explore/components/SongList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import React, { useState, useEffect, useCallback } from "react";
import SongItem from "./SongItem";
import Player from "@/components/ui/Player";
import { fetchSongs } from "@/utils/fetchSongs";
import {
fetchSongsByGenre,
fetchSongsBySearchTerm,
fetchSongs,
} from "@/utils/fetchSongs";
import { useFilterSongs } from "@/hooks/useFilterSongs";
import { Song } from "@/types/ui/Song";
import { formatDuration } from "@/utils/formatDuration";
import { mockSongs } from "@/data/mockSongs"; // Importa los datos hardcodeados
//import { mockSongs } from "@/data/mockSongs";

interface SongListProps {
searchTerm?: string;
Expand All @@ -18,35 +22,78 @@ export default function SongList({
}: SongListProps) {
const [selectedSong, setSelectedSong] = useState<Song | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [songs, setSongs] = useState<Song[]>([]); // Inicializar vacío
const [songs, setSongs] = useState<Song[]>([]);
const [initialSongs, setInitialSongs] = useState<Song[]>([]);

useEffect(() => {
const genres = [
"pop",
"rock",
"electronica",
"clasica",
"hip-hop",
"rap",
"k-pop",
];

const loadInitialSongs = async () => {
try {
const promises = genres.map((genre) => fetchSongsByGenre(genre));
const results = await Promise.all(promises);
const allSongs = results.flat();

const randomFetchedSongs = await fetchSongs("");

const combinedSongs: Song[] = [];
const maxLength = Math.max(allSongs.length, randomFetchedSongs.length);
for (let i = 0; i < maxLength; i++) {
if (i < allSongs.length) {
combinedSongs.push(allSongs[i]);
}
if (i < randomFetchedSongs.length) {
combinedSongs.push(randomFetchedSongs[i]);
}
}

setInitialSongs(combinedSongs);
} catch (error) {
console.error("Error fetching initial songs:", error);
}
};

loadInitialSongs();
}, []);

useEffect(() => {
const loadSongs = async () => {
try {
const fetchedSongs = await fetchSongs(searchTerm);
console.log("Fetched Songs:", fetchedSongs); // Debug log
let fetchedSongs: Song[] = [];

if (searchTerm) {
fetchedSongs = await fetchSongsBySearchTerm(searchTerm);
} else {
fetchedSongs = await fetchSongs("");
}

// Intercalar canciones de la API y mockSongs
const combinedSongs: Song[] = [];
const maxLength = Math.max(fetchedSongs.length, mockSongs.length);
const maxLength = Math.max(fetchedSongs.length, initialSongs.length);
for (let i = 0; i < maxLength; i++) {
if (i < fetchedSongs.length) {
combinedSongs.push(fetchedSongs[i]);
}
if (i < mockSongs.length) {
combinedSongs.push(mockSongs[i]);
if (i < initialSongs.length) {
combinedSongs.push(initialSongs[i]);
}
}

// Limitar a las primeras 15 canciones
setSongs(combinedSongs.slice(0, 15));
} catch (error) {
console.error("Error fetching songs:", error);
}
};

loadSongs();
}, [searchTerm]);
}, [searchTerm, initialSongs]);

const handlePlay = useCallback(
(song: Song) => {
Expand Down Expand Up @@ -91,7 +138,6 @@ export default function SongList({
}, []);

const filteredSongs = useFilterSongs(songs, searchTerm, selectedGenre);
console.log("Filtered Songs:", filteredSongs); // Debug log

return (
<div className="w-full">
Expand All @@ -106,8 +152,8 @@ export default function SongList({
duration={formatDuration(song.duration)}
md5_image={song.md5_image}
preview={song.preview}
artist={song.artist.name}
artistImage={song.artist.picture_medium}
artist={song.artist?.name || "Unknown Artist"}
artistImage={song.artist?.picture_medium || ""}
isFavorite={song.isFavorite}
isSelected={selectedSong?.id === song.id}
onPlay={() => handlePlay(song)}
Expand All @@ -119,10 +165,10 @@ export default function SongList({
<Player
currentSong={{
...selectedSong,
artist: selectedSong.artist.name,
artist: selectedSong.artist?.name || "Unknown Artist",
}}
genres={selectedSong.album.genres || ""}
artistImage={selectedSong.artist.picture_medium}
artistImage={selectedSong.artist?.picture_medium || ""}
isFavorite={selectedSong.isFavorite}
isPlaying={isPlaying}
onPlayPause={handlePlayPause}
Expand Down
28 changes: 27 additions & 1 deletion frontend/src/hooks/useFilterSongs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Song } from "@/types/ui/Song";
/*import { Song } from "@/types/ui/Song";
export const useFilterSongs = (
songs: Song[],
Expand All @@ -21,3 +21,29 @@ export const useFilterSongs = (
return matchesSearch && matchesGenre;
});
};
*/
import { Song } from "@/types/ui/Song";

export const useFilterSongs = (
songs: Song[],
searchTerm: string,
selectedGenre: string
): Song[] => {
if (!Array.isArray(songs)) {
return [];
}

return songs.filter((song) => {
const matchesSearch = [song.title, song.artist?.name, ...(Array.isArray(song.album.genres) ? song.album.genres : [song.album.genres])]
.map((field) => (typeof field === "string" ? field : "").toLowerCase())
.some((value) => value.includes(searchTerm.toLowerCase()));

const genres = Array.isArray(song.album.genres) ? song.album.genres : [song.album.genres];
const matchesGenre =
selectedGenre === "Todos" || genres.some((genre) =>
genre.toLowerCase().includes(selectedGenre.toLowerCase())
);

return matchesSearch && matchesGenre;
});
};
44 changes: 31 additions & 13 deletions frontend/src/types/ui/Song.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export interface Song {
title_short: string;
duration: string;
preview: string;
md5_image: string;
md5_image: string | null;
artist: Artist;
album: Album;
isFavorite: boolean;
Expand All @@ -16,23 +16,41 @@ export interface Song {
export interface Artist {
id: string;
name: string;
picture: string;
picture_small: string;
picture_medium: string;
picture_big: string;
picture_xl: string;
tracklist: string;
picture: string | null;
picture_small: string | null;
picture_big: string | null;
picture_xl: string | null;
tracklist: string | null;
}

export interface Album {
id: string;
title: string;
cover: string;
cover_small: string;
cover_medium: string;
cover_big: string;
cover_xl: string;
md5_image: string;
tracklist: string;
genres: string | null;
cover: string | null;
cover_small: string | null;
cover_medium: string | null;
cover_big: string | null;
cover_xl: string | null;
md5_image: string | null;
tracklist: string | null;

}

export interface newSong {
id: string;
title: string;
duration: number;
preview: string;
artist: {
id: string;
name: string;
picture_medium: string;
};
album: {
id: string;
title: string;
genres: string[];
};
}
95 changes: 94 additions & 1 deletion frontend/src/utils/fetchSongs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@

//Primera ruta api deezer

export const fetchSongs = async (track: string) => {
const genres = ["pop", "rock", "electronica", "clasica", "hip-hop", "rap", "k-pop"];

Expand All @@ -17,7 +20,7 @@ export const fetchSongs = async (track: string) => {
const data = await response.json();
//console.log('API Response:', data); // Debug log

// Asegurarse de acceder al arreglo de canciones dentro de la estructura de datos
// Acceder al arreglo de canciones dentro de la estructura de datos
const songs = data.data.data || [];
//console.log('Extracted Songs:', songs); // Debug log

Expand All @@ -28,3 +31,93 @@ export const fetchSongs = async (track: string) => {
return [];
}
};


//Nueva ruta
/*
export const fetchSongs = async (track: string) => {
const response = await fetch(`http://144.33.15.219:8080/search/?track=${encodeURIComponent(track)}&page=0&size=15`, {
headers: {
'accept': 'application/json'
}
});
if (!response.ok) {
throw new Error('Error fetching songs');
}
const data = await response.json();
const songs = data.data || [];
if (songs.length > 0) {
return songs.map(song => ({
id: song.id.toString(),
title: song.title,
title_short: song.title,
duration: song.duration.toString(),
preview: song.preview,
md5_image: null,
artist: {
id: song.artist.id.toString(),
name: song.artist.name,
picture_medium: song.artist.picture_medium,
picture: null,
picture_small: null,
picture_big: null,
picture_xl: null,
tracklist: null
},
album: {
id: song.album.id.toString(),
title: song.album.genres,
genres: song.album.genres,
cover: null,
cover_small: null,
cover_medium: null,
cover_big: null,
cover_xl: null,
md5_image: null,
tracklist: null
},
isFavorite: false
}));
} else {
console.warn('No songs found');
return [];
}
};
*/


//Ruta para traer canciones por genero
export const fetchSongsByGenre = async (genre: string) => {
const url = `http://144.33.15.219:8080/tracks?genre=${genre}`;
return fetchSongsList(url);
};

export const fetchSongsBySearchTerm = async (searchTerm: string) => {
const url = `http://144.33.15.219:8080/search?track=${encodeURIComponent(searchTerm)}`;
return fetchSongsList(url);
};

const fetchSongsList = async (url: string) => {
const response = await fetch(url, {
headers: {
'accept': 'application/json'
}
});

if (!response.ok) {
throw new Error('Error fetching songs');
}

const data = await response.json();
const songs = data.data || [];

if (songs.length > 0) {
return songs;
} else {
console.warn('No songs found');
return [];
}
};
Loading

0 comments on commit 354bc49

Please sign in to comment.