Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ported the Project to React and Express #46

Merged
merged 10 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// App.js
rahulpoonia29 marked this conversation as resolved.
Show resolved Hide resolved

import React, { useState, useEffect } from 'react';
import Player from './Player';
import SearchBox from './SearchBox';
import SearchResults from './SearchResults';

const App = () => {
const [data, setData] = useState(null);
const [audio] = useState(new Audio());
const [globalData, setGlobalData] = useState(null);
const [currplaying, setCurrplaying] = useState(0);

useEffect(() => {
fetchData();
}, []);

const fetchData = async () => {
try {
const response = await fetch("/search1");
const data = await response.json();
setGlobalData(data);
} catch (error) {
console.error("Error fetching data:", error);
}
};

const togglePlayPause = () => {
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
};

const updateProgress = () => {
const progress = (audio.currentTime / audio.duration) * 100;
// Update seek slider value and current time display
};

const seek = (e) => {
const seekTime = (audio.duration / 100) * e.target.value;
audio.currentTime = seekTime;
};

const seekForward = () => {
audio.currentTime += 10;
};

const seekBackward = () => {
audio.currentTime -= 10;
};

const nextPlay = () => {
setCurrplaying(currplaying + 1 >= globalData.length ? 0 : currplaying + 1);
const selectedMusic = globalData[currplaying];
updateAudio(selectedMusic);
};

const previousPlay = () => {
setCurrplaying(currplaying - 1 < 0 ? globalData.length - 1 : currplaying - 1);
const selectedMusic = globalData[currplaying];
updateAudio(selectedMusic);
};

const updateAudio = (selectedMusic) => {
audio.src = selectedMusic.url;
audio.play();
// Update other elements like image, name, author, etc.
};

// Add event listeners and other necessary setup
useEffect(() => {
audio.addEventListener("timeupdate", updateProgress);
// Add other event listeners
return () => {
audio.removeEventListener("timeupdate", updateProgress);
// Remove other event listeners
};
}, [audio]);

return (
<div className="ui">
<Player
audio={audio}
globalData={globalData}
currplaying={currplaying}
updateAudio={updateAudio}
togglePlayPause={togglePlayPause}
seekForward={seekForward}
seekBackward={seekBackward}
nextPlay={nextPlay}
previousPlay={previousPlay}
updateProgress={updateProgress}
seek={seek}
/>
<SearchBox fetchData={fetchData} />
<SearchResults data={data} />
</div>
);
};

export default App;
40 changes: 40 additions & 0 deletions Player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Player.js
import React, { useState } from 'react';

const Player = ({ data }) => {
const [isPlaying, setIsPlaying] = useState(false);

const togglePlayPause = () => {
setIsPlaying(!isPlaying);
};

const renderPlayer = () => {
if (!data || !data.length) {
return <div className="player">No data available</div>;
}

const currentTrack = data[0];

return (
<div className="player">
<div className="imgBx">
<img src={currentTrack.img} height="250px" width="250px" alt="Album cover" />
</div>

<ul className="details">
<li className="name">{currentTrack.name}</li>
<li className="author">{currentTrack.artist} - {currentTrack.year}</li>
</ul>

<div className="controls">
<button onClick={togglePlayPause}>{isPlaying ? 'Pause' : 'Play'}</button>
{/* Add more controls like seek, next, previous, etc. */}
</div>
</div>
);
};

return renderPlayer();
};

export default Player;
27 changes: 27 additions & 0 deletions SearchBox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SearchBox.js
import React, { useState } from 'react';

const SearchBox = ({ fetchData }) => {
const [query, setQuery] = useState('');

const handleSearch = () => {
fetchData(query);
};

return (
<div className="search-box">
<div className="search">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="box1"
required
/>
<button className="button" onClick={handleSearch}>Search</button>
</div>
</div>
);
};

export default SearchBox;
29 changes: 29 additions & 0 deletions SearchResults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React from 'react';

const SearchResults = ({ data }) => {
const renderResults = () => {
if (!data || !data.length) {
return <div className="results">No search results found.</div>;
}

return (
<div className="results">
{data.map((item, index) => (
<div className="result-item" key={index}>
<div className="songresult">
<img src={item.img} alt="Album cover" />
<div className="search-details">
<h4 className="element-name">{item.name}</h4>
<p className="artist-year">{`${item.artist} - ${item.year}`}</p>
</div>
</div>
</div>
))}
</div>
);
};

return renderResults();
};

export default SearchResults;
24 changes: 24 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
rahulpoonia29 marked this conversation as resolved.
Show resolved Hide resolved
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
98 changes: 98 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import express from "express";
import axios from "axios";
import bodyParser from "body-parser";
import cors from "cors"; // Import the cors middleware

const cache = new Map();

const app = express();
const port = 3030;
let name = "";

app.use(bodyParser.urlencoded({ extended: true }));

// Use CORS middleware
app.use(cors());

app.get("/", (req, res) => {
res.send("Welcome to the music search API");
});

app.get("/search", async (req, res) => {
name = req.query.song;
console.log("Name is", name);
try {
if (cache.has(name)) {
console.log("Fetching from cache...");
const music = cache.get(name);
res.json(music);
} else {
const response = await axios.get(
`https://jio-savaan-private.vercel.app/api/search/songs?query=${name}`
);
if (
response.data.data.results &&
response.data.data.results.length > 0
) {
const musicArray = response.data.data.results.map((result) => ({
url: result.downloadUrl[4].url,
name: result.name,
year: result.year,
artist: result.artists.primary[0].name,
img: result.image[2].url,
}));
cache.set(name, musicArray);
res.json(musicArray);
} else {
res.json([]);
}
}
} catch (error) {
console.error("Failed to make request:", error.message);
res.status(500).json({
error: "Error fetching song. Please try again later.",
});
}
});

app.get("/search1", async (req, res) => {
console.log(name);
try {
if (cache.has(name)) {
console.log("Fetching from cache...");
const music = cache.get(name);
res.json(music);
} else {
const response = await axios.get(
`https://jio-savaan-private.vercel.app/api/search/songs?query=${name}`
);
if (
response.data.data.results &&
response.data.data.results.length > 0
) {
const musicArray = response.data.data.results
.slice(0, 5)
.map((result) => ({
url: result.downloadUrl[4].url,
name: result.name,
year: result.year,
artist: result.artists.primary[0].name,
img: result.image[2].url,
}));
cache.set(name, musicArray);
res.json(musicArray);
} else {
res.json([]);
}
}
} catch (error) {
console.error("Failed to make request:", error.message);
res.status(500).json({
error: "Error fetching song. Please try again later.",
});
}
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Loading