Merge remote-tracking branch 'origin/main' into tobi-dev
This commit is contained in:
commit
5f071b6cfe
11 changed files with 372 additions and 149 deletions
65
.dockerignore
Normal file
65
.dockerignore
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
# Git
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
# Documentation
|
||||||
|
README.md
|
||||||
|
LICENSE
|
||||||
|
*.md
|
||||||
|
|
||||||
|
# Node modules (will be installed in container)
|
||||||
|
frontend/node_modules
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
backend/build
|
||||||
|
frontend/build
|
||||||
|
backend/.gradle
|
||||||
|
backend/bin
|
||||||
|
|
||||||
|
# IDE files
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
*.iml
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Environment files
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
pids
|
||||||
|
*.pid
|
||||||
|
*.seed
|
||||||
|
*.pid.lock
|
||||||
|
|
||||||
|
# Coverage directory used by tools like istanbul
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# Dependency directories
|
||||||
|
jspm_packages/
|
||||||
|
|
||||||
|
# Optional npm cache directory
|
||||||
|
.npm
|
||||||
|
|
||||||
|
# Optional REPL history
|
||||||
|
.node_repl_history
|
||||||
|
|
||||||
|
# Output of 'npm pack'
|
||||||
|
*.tgz
|
||||||
|
|
||||||
|
# Yarn Integrity file
|
||||||
|
.yarn-integrity
|
65
Dockerfile
65
Dockerfile
|
@ -0,0 +1,65 @@
|
||||||
|
# Multi-stage Dockerfile for Serena (Backend + Frontend)
|
||||||
|
|
||||||
|
# Stage 1: Build Frontend
|
||||||
|
FROM node:18-alpine AS frontend-builder
|
||||||
|
|
||||||
|
WORKDIR /app/frontend
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY frontend/package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm ci --only=production
|
||||||
|
|
||||||
|
# Copy frontend source
|
||||||
|
COPY frontend/ ./
|
||||||
|
|
||||||
|
# Build frontend
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Stage 2: Build Backend
|
||||||
|
FROM openjdk:21-jdk-slim AS backend-builder
|
||||||
|
|
||||||
|
WORKDIR /app/backend
|
||||||
|
|
||||||
|
# Copy Gradle wrapper and build files
|
||||||
|
COPY backend/gradlew ./
|
||||||
|
COPY backend/gradle/ ./gradle/
|
||||||
|
COPY backend/build.gradle ./
|
||||||
|
COPY backend/settings.gradle ./
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY backend/src/ ./src/
|
||||||
|
|
||||||
|
# Make gradlew executable and build
|
||||||
|
RUN chmod +x gradlew
|
||||||
|
RUN ./gradlew build --no-daemon -x test
|
||||||
|
|
||||||
|
# Stage 3: Runtime
|
||||||
|
FROM openjdk:21-jre-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install curl for health checks
|
||||||
|
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Copy built backend JAR
|
||||||
|
COPY --from=backend-builder /app/backend/build/libs/*.jar app.jar
|
||||||
|
|
||||||
|
# Copy built frontend (will be served by Spring Boot)
|
||||||
|
COPY --from=frontend-builder /app/frontend/build/ /app/static/
|
||||||
|
|
||||||
|
# Create non-root user
|
||||||
|
RUN groupadd -r serena && useradd -r -g serena serena
|
||||||
|
RUN chown -R serena:serena /app
|
||||||
|
USER serena
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# Health check
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||||
|
CMD curl -f http://localhost:8080/actuator/health || exit 1
|
||||||
|
|
||||||
|
# Run the application
|
||||||
|
ENTRYPOINT ["java", "-jar", "app.jar"]
|
124
README.md
124
README.md
|
@ -1,2 +1,124 @@
|
||||||
# team-5
|
# Serena - Collaborative Radio Station Platform
|
||||||
|
|
||||||
|
**Serena** is a collaborative radio station platform that enables users to create and join virtual music stations for shared listening experiences. The application features a React frontend and Spring Boot backend, integrating with the Spotify API to provide real-time music playback and queue management.
|
||||||
|
|
||||||
|
## 🎵 Features
|
||||||
|
|
||||||
|
- **Create & Join Stations**: Users can create radio stations with unique join codes or join existing stations
|
||||||
|
- **Collaborative Queuing**: Multiple users can add songs to their preferred queues
|
||||||
|
- **Intelligent Recommendations**: Advanced algorithm considers song popularity, tempo similarity, audio features, and user preferences
|
||||||
|
- **Real-time Playback**: Spotify integration for seamless music streaming (station owners control playback)
|
||||||
|
- **User Authentication**: JWT-based authentication system with owner and client roles
|
||||||
|
- **Responsive UI**: Modern React interface with animated backgrounds and intuitive controls
|
||||||
|
|
||||||
|
## 🏗️ Architecture
|
||||||
|
|
||||||
|
### Backend (Spring Boot)
|
||||||
|
- **Language**: Java
|
||||||
|
- **Framework**: Spring Boot
|
||||||
|
- **Authentication**: JWT tokens
|
||||||
|
- **Queue Algorithm**: Multi-factor recommendation system
|
||||||
|
- **API**: RESTful endpoints for station and queue management
|
||||||
|
|
||||||
|
### Frontend (React)
|
||||||
|
- **Language**: JavaScript (JSX)
|
||||||
|
- **Framework**: React 19.1.1
|
||||||
|
- **Routing**: React Router DOM
|
||||||
|
- **Spotify Integration**: Web Playback SDK
|
||||||
|
- **Styling**: CSS with animations
|
||||||
|
|
||||||
|
### External APIs
|
||||||
|
- **Spotify Web API**: Music data and playback control
|
||||||
|
- **Spotify Web Playback SDK**: Browser-based music streaming
|
||||||
|
|
||||||
|
## 🚀 Quick Start
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
- Node.js (v16+)
|
||||||
|
- Java 11+
|
||||||
|
- Gradle
|
||||||
|
- Docker (optional)
|
||||||
|
- Spotify Premium account (for playback control)
|
||||||
|
|
||||||
|
|
||||||
|
### Backend Setup
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
./gradlew bootRun
|
||||||
|
```
|
||||||
|
|
||||||
|
The backend will start on `http://localhost:8080`
|
||||||
|
|
||||||
|
### Frontend Setup
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
The frontend will start on `http://localhost:3000`
|
||||||
|
|
||||||
|
### Docker Setup (Alternative)
|
||||||
|
```bash
|
||||||
|
docker-compose up
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📖 API Documentation
|
||||||
|
|
||||||
|
Detailed API documentation is available in [`backend/API_DOCUMENTATION.md`](backend/API_DOCUMENTATION.md).
|
||||||
|
|
||||||
|
### Key Endpoints
|
||||||
|
- `POST /api/radio-stations` - Create a new radio station
|
||||||
|
- `GET /api/radio-stations` - List all radio stations
|
||||||
|
- `POST /api/clients/connect` - Join a station with join code
|
||||||
|
- `POST /api/songs/queue` - Add song to client's preferred queue
|
||||||
|
- `GET /api/songs/queue/recommended` - Get intelligently sorted queue
|
||||||
|
|
||||||
|
## 🎯 How It Works
|
||||||
|
|
||||||
|
### Station Creation
|
||||||
|
1. User creates a station with name and description
|
||||||
|
2. System generates unique station ID and 6-character join code
|
||||||
|
3. Creator becomes the station owner with playback control
|
||||||
|
|
||||||
|
### Joining Stations
|
||||||
|
1. Users join with the station's join code
|
||||||
|
2. Receive client authentication token
|
||||||
|
3. Can add songs to their preferred queue
|
||||||
|
|
||||||
|
### Queue Algorithm
|
||||||
|
The intelligent queue system considers:
|
||||||
|
- **Preferred Queue Position** (30%): User song preferences
|
||||||
|
- **Popularity** (20%): Spotify popularity scores
|
||||||
|
- **Tempo Similarity** (20%): BPM matching with current song
|
||||||
|
- **Audio Features** (30%): Danceability, energy, valence, etc.
|
||||||
|
|
||||||
|
### Playback Control
|
||||||
|
- Only station owners can control playback
|
||||||
|
- Automatic progression through recommended queue
|
||||||
|
- Real-time sync with Spotify Web Playback SDK
|
||||||
|
|
||||||
|
## 🔧 Configuration
|
||||||
|
|
||||||
|
### Backend Configuration
|
||||||
|
Update `backend/src/main/resources/application.properties`:
|
||||||
|
```properties
|
||||||
|
# Add your Spotify credentials and other settings
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend Configuration
|
||||||
|
Update Spotify credentials in `frontend/src/constants/ApiConstants.js`
|
||||||
|
|
||||||
|
## 🧪 Testing
|
||||||
|
|
||||||
|
### Backend Tests
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
./gradlew test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend Tests
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm test
|
||||||
|
```
|
|
@ -0,0 +1,69 @@
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# Backend Service
|
||||||
|
serena-backend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: serena-backend
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
environment:
|
||||||
|
- SPRING_PROFILES_ACTIVE=docker
|
||||||
|
- SERVER_PORT=8080
|
||||||
|
- SPRING_WEB_CORS_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 60s
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- serena-network
|
||||||
|
|
||||||
|
# Frontend Development Service (alternative to built-in static files)
|
||||||
|
serena-frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
dockerfile: Dockerfile.dev
|
||||||
|
container_name: serena-frontend
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
environment:
|
||||||
|
- REACT_APP_API_URL=http://localhost:8080
|
||||||
|
- CHOKIDAR_USEPOLLING=true
|
||||||
|
volumes:
|
||||||
|
- ./frontend:/app
|
||||||
|
- /app/node_modules
|
||||||
|
depends_on:
|
||||||
|
- serena-backend
|
||||||
|
networks:
|
||||||
|
- serena-network
|
||||||
|
profiles:
|
||||||
|
- development
|
||||||
|
|
||||||
|
# Production Frontend (served by backend)
|
||||||
|
serena-app:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: serena-app
|
||||||
|
ports:
|
||||||
|
- "80:8080"
|
||||||
|
environment:
|
||||||
|
- SPRING_PROFILES_ACTIVE=production
|
||||||
|
- SERVER_PORT=8080
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- serena-network
|
||||||
|
profiles:
|
||||||
|
- production
|
||||||
|
|
||||||
|
networks:
|
||||||
|
serena-network:
|
||||||
|
driver: bridge
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
node_modules:
|
2
frontend/.gitignore
vendored
2
frontend/.gitignore
vendored
|
@ -21,3 +21,5 @@
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
|
||||||
|
music/*
|
35
frontend/src/components/AudioPlayer.jsx
Normal file
35
frontend/src/components/AudioPlayer.jsx
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
import React, { useRef, useState } from "react";
|
||||||
|
|
||||||
|
const SingleAudioPlayer = ({ src }) => {
|
||||||
|
const audioRef = useRef(null);
|
||||||
|
const [isPlaying, setIsPlaying] = useState(false);
|
||||||
|
|
||||||
|
const togglePlay = () => {
|
||||||
|
const audio = audioRef.current;
|
||||||
|
if (!audio) return;
|
||||||
|
|
||||||
|
if (isPlaying) {
|
||||||
|
audio.pause();
|
||||||
|
} else {
|
||||||
|
audio.play().catch((e) => {
|
||||||
|
console.warn("Playback error:", e);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsPlaying(!isPlaying);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEnded = () => {
|
||||||
|
setIsPlaying(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
|
||||||
|
<button onClick={togglePlay}>{isPlaying ? "Pause" : "Play"}</button>
|
||||||
|
<span>{src.split("/").pop()}</span>
|
||||||
|
<audio ref={audioRef} src={src} onEnded={handleEnded} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SingleAudioPlayer;
|
|
@ -1,30 +0,0 @@
|
||||||
import React from 'react';
|
|
||||||
import { getSpotifyLoginUrl, isLoggedIn, removeAccessToken } from '../utils/spotifyAuth.js';
|
|
||||||
|
|
||||||
const LoginButton = () => {
|
|
||||||
const loggedIn = isLoggedIn();
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
|
||||||
removeAccessToken();
|
|
||||||
window.location.reload(); // Refresh to update UI
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loggedIn) {
|
|
||||||
return (
|
|
||||||
<div className="login-status">
|
|
||||||
<span>✓ Connected to Spotify</span>
|
|
||||||
<button onClick={handleLogout} className="logout-btn">
|
|
||||||
Logout
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<a href={getSpotifyLoginUrl()}>
|
|
||||||
<button className="spotify-login-btn">Login with Spotify</button>
|
|
||||||
</a>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default LoginButton;
|
|
|
@ -3,6 +3,3 @@ export const RADIOSTATION_URL = "http://localhost:8080/api";
|
||||||
export const CREATE_RADIOSTATION_ENDPOINT = "/radio-stations";
|
export const CREATE_RADIOSTATION_ENDPOINT = "/radio-stations";
|
||||||
export const LIST_RADIOSTATIONS_ENDPOINT = "/radio-stations";
|
export const LIST_RADIOSTATIONS_ENDPOINT = "/radio-stations";
|
||||||
export const ADD_CLIENT_ENDPOINT = "/clients/connect";
|
export const ADD_CLIENT_ENDPOINT = "/clients/connect";
|
||||||
|
|
||||||
export const SPOTIFY_PREMIUM_TOKEN =
|
|
||||||
"BQCEnWrYVdmta4Eekdkewazun99IuocRAyPEbwPSrHuGYgZYg7JGlXG2BLmRL6fwjzPJkrmHiqlTLSn1yqR36awA9Rv4n9dwvTBv1DjAitsuzaEVg7PtYdbUHXqP2HJJ4dDDvTtvUfWIBDY_Afa7WgY1cyRbl-p4VobNHXUR9N3Ye1qBTgH3RZ5ziIbIoNWe_JrxYvcedkvr23zXUVabOyahTgt_YdmnCWt2Iu8XT8sjhSyc8tOCqbs_KqE-Qe1WSPUCrGS8";
|
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
import AddSongModal from "./AddSongModal";
|
import React, { useState, useEffect } from "react";
|
||||||
import LoginButton from "../components/LoginButton";
|
|
||||||
import { addClientToStation } from "../utils/AddClientToStation";
|
import { addClientToStation } from "../utils/AddClientToStation";
|
||||||
|
import { getAudioFiles } from "../utils/AudioFiles";
|
||||||
|
import SingleAudioPlayer from "../components/AudioPlayer";
|
||||||
|
|
||||||
function StationPage() {
|
function StationPage() {
|
||||||
const { id: stationId } = useParams();
|
const { stationID } = useParams();
|
||||||
const [setClientToken] = useState("");
|
const [clientToken, setClientToken] = useState("");
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
|
||||||
const [accessDenied, setAccessDenied] = useState(true);
|
const [accessDenied, setAccessDenied] = useState(true);
|
||||||
const [currentSong] = useState({ progress: 0, duration: 1 });
|
const [currentSong] = useState({ progress: 0, duration: 1 });
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
@ -129,15 +129,7 @@ function StationPage() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const recommendedSongs = [];
|
const recommendedSongs = getAudioFiles() ?? [];
|
||||||
|
|
||||||
const openModal = () => {
|
|
||||||
setIsModalOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const closeModal = () => {
|
|
||||||
setIsModalOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="station-page">
|
<div className="station-page">
|
||||||
|
@ -151,15 +143,12 @@ function StationPage() {
|
||||||
<header className="station-header">
|
<header className="station-header">
|
||||||
<h1>Serena Station</h1>
|
<h1>Serena Station</h1>
|
||||||
<p className="station-subtitle">Collaborative Music Experience</p>
|
<p className="station-subtitle">Collaborative Music Experience</p>
|
||||||
<LoginButton />
|
|
||||||
</header>
|
</header>
|
||||||
|
<SingleAudioPlayer src={recommendedSongs[0]}></SingleAudioPlayer>
|
||||||
|
|
||||||
<div className="songs-section">
|
<div className="songs-section">
|
||||||
<div className="section-header">
|
<div className="section-header">
|
||||||
<h2>Song Queue</h2>
|
<h2>Song Queue</h2>
|
||||||
<button className="add-song-btn" onClick={openModal}>
|
|
||||||
Add Song
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="songs-list">
|
<div className="songs-list">
|
||||||
|
@ -168,31 +157,11 @@ function StationPage() {
|
||||||
<p>No songs in queue yet. Add some songs to get started!</p>
|
<p>No songs in queue yet. Add some songs to get started!</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
recommendedSongs.map((song) => (
|
recommendedSongs.map((song) => <p>{song}</p>)
|
||||||
<div key={song.id} className="song-item">
|
|
||||||
<div className="song-info">
|
|
||||||
<h4>{song.title}</h4>
|
|
||||||
<p>{song.artist}</p>
|
|
||||||
</div>
|
|
||||||
<span className="song-duration">{song.duration}</span>
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Progress Bar */}
|
|
||||||
<div className="progress-container">
|
|
||||||
<div className="progress-bar">
|
|
||||||
<div
|
|
||||||
className="progress-fill"
|
|
||||||
style={{ width: `${(currentSong.progress / currentSong.duration) * 100}%` }}
|
|
||||||
></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isModalOpen && <AddSongModal onClose={closeModal} />}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
5
frontend/src/utils/AudioFiles.js
Normal file
5
frontend/src/utils/AudioFiles.js
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
const importAll = (r) => r.keys().map(r);
|
||||||
|
|
||||||
|
export const getAudioFiles = () => {
|
||||||
|
return importAll(require.context("../../music", false, /\.(mp3|wav)$/));
|
||||||
|
};
|
|
@ -1,76 +0,0 @@
|
||||||
const CLIENT_ID = 'e1274b6593674771bea12d8366c7978b';
|
|
||||||
const REDIRECT_URI = 'http://localhost:3000/callback';
|
|
||||||
const SCOPES = [
|
|
||||||
'user-read-private',
|
|
||||||
'user-read-email',
|
|
||||||
'playlist-read-private',
|
|
||||||
'user-library-read',
|
|
||||||
];
|
|
||||||
|
|
||||||
export const getSpotifyLoginUrl = () => {
|
|
||||||
const scope = SCOPES.join('%20');
|
|
||||||
return `https://accounts.spotify.com/authorize?client_id=${CLIENT_ID}&response_type=token&redirect_uri=${encodeURIComponent(
|
|
||||||
REDIRECT_URI
|
|
||||||
)}&scope=${scope}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAccessTokenFromUrl = () => {
|
|
||||||
const hash = window.location.hash;
|
|
||||||
if (hash) {
|
|
||||||
const params = new URLSearchParams(hash.substring(1));
|
|
||||||
return params.get('access_token');
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeAccessToken = (token) => {
|
|
||||||
localStorage.setItem('spotify_access_token', token);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAccessToken = () => {
|
|
||||||
return localStorage.getItem('spotify_access_token');
|
|
||||||
};
|
|
||||||
|
|
||||||
export const removeAccessToken = () => {
|
|
||||||
localStorage.removeItem('spotify_access_token');
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isLoggedIn = () => {
|
|
||||||
return !!getAccessToken();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const searchSpotifyTracks = async (query) => {
|
|
||||||
const token = getAccessToken();
|
|
||||||
if (!token) {
|
|
||||||
throw new Error('No access token available');
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(
|
|
||||||
`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track&limit=20`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
if (response.status === 401) {
|
|
||||||
removeAccessToken();
|
|
||||||
throw new Error('Token expired');
|
|
||||||
}
|
|
||||||
throw new Error('Search failed');
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return data.tracks.items.map((track) => ({
|
|
||||||
id: track.id,
|
|
||||||
title: track.name,
|
|
||||||
artist: track.artists.map((artist) => artist.name).join(', '),
|
|
||||||
album: track.album.name,
|
|
||||||
coverUrl: track.album.images[0]?.url || '',
|
|
||||||
duration: track.duration_ms,
|
|
||||||
previewUrl: track.preview_url,
|
|
||||||
spotifyUrl: track.external_urls.spotify,
|
|
||||||
}));
|
|
||||||
};
|
|
Loading…
Add table
Add a link
Reference in a new issue