Merge remote-tracking branch 'origin/tobi-dev'
This commit is contained in:
commit
f69b12f155
31 changed files with 3129 additions and 975 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
|
||||
```
|
|
@ -23,6 +23,28 @@ Authorization: Bearer <token>
|
|||
|
||||
#### Create Radio Station
|
||||
|
||||
#### Get All Radio Stations
|
||||
|
||||
#### Get Radio Station by ID
|
||||
|
||||
#### Delete Radio Station
|
||||
|
||||
### Client Management
|
||||
|
||||
#### Connect Client to Station
|
||||
|
||||
### Song Queue Management
|
||||
|
||||
#### Add Song to Client's Preferred Queue
|
||||
|
||||
#### Get Radio Station Queue
|
||||
|
||||
#### Get Recommended Queue
|
||||
|
||||
## Radio Station Management
|
||||
|
||||
#### Create Radio Station
|
||||
|
||||
Creates a new radio station and returns an owner token.
|
||||
|
||||
**Endpoint:** `POST /radio-stations`
|
||||
|
@ -170,6 +192,123 @@ Connects a client to a radio station using a join code. No authentication requir
|
|||
}
|
||||
```
|
||||
|
||||
### Song Queue Management
|
||||
|
||||
#### Add Song to Client's Preferred Queue
|
||||
|
||||
Adds a song to a specific client's preferred queue. The frontend can merge track and audio features objects using `const merged = { ...trackObj, ...audioFeaturesObj };`
|
||||
|
||||
**Endpoint:** `POST /api/songs/queue`
|
||||
|
||||
**Request Body:**
|
||||
|
||||
```json
|
||||
{
|
||||
"song": {
|
||||
"id": "4iV5W9uYEdYUVa79Axb7Rh",
|
||||
"popularity": 85,
|
||||
"tempo": 120.5,
|
||||
"danceability": 0.8,
|
||||
"energy": 0.7,
|
||||
"valence": 0.6,
|
||||
"acousticness": 0.1,
|
||||
"instrumentalness": 0.0,
|
||||
"liveness": 0.1,
|
||||
"speechiness": 0.04
|
||||
},
|
||||
"clientId": "client-uuid",
|
||||
"radioStationId": "station-uuid"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Song added to client's preferred queue successfully",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
#### Get Radio Station Queue
|
||||
|
||||
Retrieves the main song queue for a radio station. Returns a list of song objects.
|
||||
|
||||
**Endpoint:** `GET /api/songs/queue?radioStationId={radioStationId}`
|
||||
|
||||
**Query Parameters:**
|
||||
|
||||
- `radioStationId` (required): The ID of the radio station
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Queue retrieved successfully",
|
||||
"data": [
|
||||
{
|
||||
"id": "4iV5W9uYEdYUVa79Axb7Rh",
|
||||
"popularity": 85,
|
||||
"tempo": 120.5,
|
||||
"danceability": 0.8,
|
||||
"energy": 0.7,
|
||||
"valence": 0.6,
|
||||
"acousticness": 0.1,
|
||||
"instrumentalness": 0.0,
|
||||
"liveness": 0.1,
|
||||
"speechiness": 0.04
|
||||
},
|
||||
{
|
||||
"id": "7ouMYWpwJ422jRcDASZB7P",
|
||||
"popularity": 78,
|
||||
"tempo": 95.0,
|
||||
"danceability": 0.6,
|
||||
"energy": 0.5,
|
||||
"valence": 0.8,
|
||||
"acousticness": 0.3,
|
||||
"instrumentalness": 0.0,
|
||||
"liveness": 0.2,
|
||||
"speechiness": 0.06
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Get Recommended Queue
|
||||
|
||||
**Endpoint:** `GET /api/songs/queue/recommended?radioStationId={radioStationId}¤tSongId={currentSongId}`
|
||||
|
||||
**Query Parameters:**
|
||||
|
||||
- `radioStationId` (required): The ID of the radio station
|
||||
- `currentSongId` (optional): The ID of the currently playing song for similarity analysis
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Recommended queue retrieved successfully",
|
||||
"data": [
|
||||
{
|
||||
"id": "4iV5W9uYEdYUVa79Axb7Rh",
|
||||
"popularity": 85,
|
||||
"tempo": 120.5,
|
||||
"audioFeatures": {
|
||||
"danceability": 0.8,
|
||||
"energy": 0.7,
|
||||
"valence": 0.6,
|
||||
"acousticness": 0.1,
|
||||
"instrumentalness": 0.0,
|
||||
"speechiness": 0.04
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Error Responses
|
||||
|
||||
All error responses follow this format:
|
||||
|
@ -213,3 +352,71 @@ curl -X GET "http://localhost:8080/api/radio-stations" \
|
|||
curl -X DELETE http://localhost:8080/api/radio-stations/{stationId} \
|
||||
-H "Authorization: Bearer {ownerToken}"
|
||||
```
|
||||
|
||||
### Adding a Song to Client's Preferred Queue
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/api/songs/queue \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer {clientToken}" \
|
||||
-d '{
|
||||
"song": {
|
||||
"id": "4iV5W9uYEdYUVa79Axb7Rh",
|
||||
"popularity": 85,
|
||||
"tempo": 120.5,
|
||||
"danceability": 0.8,
|
||||
"energy": 0.7,
|
||||
"valence": 0.6,
|
||||
"acousticness": 0.1,
|
||||
"instrumentalness": 0.0,
|
||||
"liveness": 0.1,
|
||||
"speechiness": 0.04
|
||||
},
|
||||
"clientId": "client-uuid",
|
||||
"radioStationId": "station-uuid"
|
||||
}'
|
||||
```
|
||||
|
||||
### Getting Radio Station Queue
|
||||
|
||||
```bash
|
||||
curl -X GET "http://localhost:8080/api/songs/queue?radioStationId=station-uuid" \
|
||||
-H "Authorization: Bearer {token}"
|
||||
```
|
||||
|
||||
## Frontend Integration Notes
|
||||
|
||||
### Merging Track and Audio Features
|
||||
|
||||
The frontend can easily merge track information with audio features using JavaScript object spread:
|
||||
|
||||
```javascript
|
||||
// Track object from Spotify API
|
||||
const trackObj = {
|
||||
id: "4iV5W9uYEdYUVa79Axb7Rh",
|
||||
popularity: 85,
|
||||
tempo: 120.5,
|
||||
};
|
||||
|
||||
// Audio features object from Spotify API
|
||||
const audioFeaturesObj = {
|
||||
danceability: 0.8,
|
||||
energy: 0.7,
|
||||
valence: 0.6,
|
||||
acousticness: 0.1,
|
||||
instrumentalness: 0.0,
|
||||
liveness: 0.1,
|
||||
speechiness: 0.04,
|
||||
};
|
||||
|
||||
// Merge objects for API request
|
||||
const merged = { ...trackObj, ...audioFeaturesObj };
|
||||
```
|
||||
|
||||
### Queue Data Structure
|
||||
|
||||
The queue endpoints return/accept arrays of song objects. Each song object contains:
|
||||
|
||||
- Basic track info (id, popularity, tempo)
|
||||
- Audio features (danceability, energy, valence, etc.)
|
||||
- All properties are at the root level (flattened structure)
|
||||
|
|
12
backend/gradlew
vendored
12
backend/gradlew
vendored
|
@ -15,8 +15,6 @@
|
|||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
|
@ -57,7 +55,7 @@
|
|||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
|
@ -86,7 +84,7 @@ done
|
|||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
@ -114,7 +112,7 @@ case "$( uname )" in #(
|
|||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
|
@ -205,7 +203,7 @@ fi
|
|||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
@ -213,7 +211,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
|||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
|
|
6
backend/gradlew.bat
vendored
6
backend/gradlew.bat
vendored
|
@ -13,8 +13,6 @@
|
|||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
|
@ -70,11 +68,11 @@ goto fail
|
|||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
|
|
@ -1,40 +1,97 @@
|
|||
package com.serena.backend.controller;
|
||||
|
||||
import com.serena.backend.dto.ApiResponse;
|
||||
import com.serena.backend.dto.ConnectClientRequest;
|
||||
import com.serena.backend.dto.AddSongRequest;
|
||||
import com.serena.backend.dto.AddSongToClientQueueRequest;
|
||||
import com.serena.backend.model.Song;
|
||||
import com.serena.backend.service.RadioStationService;
|
||||
import com.serena.backend.service.QueueService;
|
||||
import com.serena.backend.service.JwtService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
import java.util.ArrayList;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/songs/")
|
||||
@RequestMapping("/api/songs")
|
||||
@CrossOrigin(origins = "*")
|
||||
public class SongController {
|
||||
|
||||
@Autowired
|
||||
private RadioStationService radioStationService;
|
||||
|
||||
@Autowired
|
||||
private QueueService queueService;
|
||||
|
||||
@Autowired
|
||||
private JwtService jwtService;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ApiResponse<Void>> addSong(@RequestBody AddSongRequest request) {
|
||||
if (request.getSong() == null || request.getRadioStationId() == null) {
|
||||
@PostMapping("/queue")
|
||||
public ResponseEntity<ApiResponse<Void>> addSongToClientQueue(@RequestBody AddSongToClientQueueRequest request) {
|
||||
if (request.getSong() == null || request.getClientId() == null) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(new ApiResponse<>(false, "Song data and radio station ID are required", null));
|
||||
.body(new ApiResponse<>(false, "Song data and client ID are required", null));
|
||||
}
|
||||
|
||||
boolean success = radioStationService.addSongToQueue(request.getRadioStationId(), request.getSong());
|
||||
boolean success = radioStationService.addSongToClientQueue(request.getClientId(), request.getSong());
|
||||
|
||||
if (success) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, "Song added to queue successfully", null));
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, "Song added to client's preferred queue successfully", null));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new ApiResponse<>(false, "Radio station not found or inactive", null));
|
||||
.body(new ApiResponse<>(false, "Client not found", null));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/queue")
|
||||
public ResponseEntity<ApiResponse<Queue<Song>>> getRadioStationQueue(@RequestParam String radioStationId) {
|
||||
Optional<com.serena.backend.model.RadioStation> station = radioStationService.getRadioStation(radioStationId);
|
||||
|
||||
if (station.isPresent()) {
|
||||
Queue<Song> queue = station.get().getSongQueue();
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, "Queue retrieved successfully", queue));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new ApiResponse<>(false, "Radio station not found", null));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/queue/recommended")
|
||||
public ResponseEntity<ApiResponse<List<Song>>> getRecommendedQueue(
|
||||
@RequestParam String radioStationId,
|
||||
@RequestParam(required = false) String currentSongId) {
|
||||
|
||||
Optional<com.serena.backend.model.RadioStation> stationOpt = radioStationService.getRadioStation(radioStationId);
|
||||
|
||||
if (stationOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new ApiResponse<>(false, "Radio station not found", null));
|
||||
}
|
||||
|
||||
com.serena.backend.model.RadioStation station = stationOpt.get();
|
||||
|
||||
List<Song> queueList = new ArrayList<>(station.getSongQueue());
|
||||
|
||||
if (queueList.isEmpty()) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, "Empty queue", queueList));
|
||||
}
|
||||
|
||||
Song currentSong = null;
|
||||
if (currentSongId != null && !currentSongId.isEmpty()) {
|
||||
currentSong = queueList.stream()
|
||||
.filter(song -> song.getId().equals(currentSongId))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
List<com.serena.backend.model.Client> clients = radioStationService.getConnectedClients(radioStationId);
|
||||
|
||||
List<Song> sortedQueue = queueService.sortQueue(currentSong, queueList, clients);
|
||||
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, "Recommended queue retrieved successfully", sortedQueue));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,8 @@ public class AddSongRequest {
|
|||
private Song song;
|
||||
private String radioStationId;
|
||||
|
||||
public AddSongRequest() {}
|
||||
public AddSongRequest() {
|
||||
}
|
||||
|
||||
public AddSongRequest(Song song, String radioStationId) {
|
||||
this.song = song;
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package com.serena.backend.dto;
|
||||
|
||||
import com.serena.backend.model.Song;
|
||||
|
||||
public class AddSongToClientQueueRequest {
|
||||
private Song song;
|
||||
private String clientId;
|
||||
private String radioStationId;
|
||||
|
||||
public AddSongToClientQueueRequest() {}
|
||||
|
||||
public AddSongToClientQueueRequest(Song song, String clientId, String radioStationId) {
|
||||
this.song = song;
|
||||
this.clientId = clientId;
|
||||
this.radioStationId = radioStationId;
|
||||
}
|
||||
|
||||
public Song getSong() {
|
||||
return song;
|
||||
}
|
||||
|
||||
public void setSong(Song song) {
|
||||
this.song = song;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public String getRadioStationId() {
|
||||
return radioStationId;
|
||||
}
|
||||
|
||||
public void setRadioStationId(String radioStationId) {
|
||||
this.radioStationId = radioStationId;
|
||||
}
|
||||
}
|
|
@ -2,16 +2,20 @@ package com.serena.backend.model;
|
|||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
public class Client {
|
||||
private String id;
|
||||
private String username;
|
||||
private String radioStationId;
|
||||
private LocalDateTime connectedAt;
|
||||
private Queue<Song> preferredQueue;
|
||||
|
||||
public Client() {
|
||||
this.id = UUID.randomUUID().toString();
|
||||
this.connectedAt = LocalDateTime.now();
|
||||
this.preferredQueue = new LinkedList<>();
|
||||
}
|
||||
|
||||
public Client(String username, String radioStationId) {
|
||||
|
@ -53,4 +57,20 @@ public class Client {
|
|||
this.connectedAt = connectedAt;
|
||||
}
|
||||
|
||||
public Queue<Song> getPreferredQueue() {
|
||||
return preferredQueue;
|
||||
}
|
||||
|
||||
public void setPreferredQueue(Queue<Song> preferredQueue) {
|
||||
this.preferredQueue = preferredQueue;
|
||||
}
|
||||
|
||||
public void addSongToPreferredQueue(Song song) {
|
||||
this.preferredQueue.offer(song);
|
||||
}
|
||||
|
||||
public Song getNextPreferredSong() {
|
||||
return this.preferredQueue.poll();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -15,7 +15,7 @@ public class RadioStation {
|
|||
private String ownerId;
|
||||
private String joinCode;
|
||||
private LocalDateTime createdAt;
|
||||
private List<String> connectedClients;
|
||||
private List<Client> connectedClients;
|
||||
private Queue<Song> songQueue;
|
||||
|
||||
public RadioStation() {
|
||||
|
@ -93,11 +93,11 @@ public class RadioStation {
|
|||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public List<String> getConnectedClients() {
|
||||
public List<Client> getConnectedClients() {
|
||||
return connectedClients;
|
||||
}
|
||||
|
||||
public void setConnectedClients(List<String> connectedClients) {
|
||||
public void setConnectedClients(List<Client> connectedClients) {
|
||||
this.connectedClients = connectedClients;
|
||||
}
|
||||
|
||||
|
|
|
@ -57,4 +57,28 @@ public class Song {
|
|||
public void setAudioFeatures(Map<String, Double> audioFeatures) {
|
||||
this.audioFeatures = audioFeatures;
|
||||
}
|
||||
|
||||
public double getAcousticness() {
|
||||
return audioFeatures.getOrDefault("acousticness", 0.0);
|
||||
}
|
||||
|
||||
public double getDanceability() {
|
||||
return audioFeatures.getOrDefault("danceability", 0.0);
|
||||
}
|
||||
|
||||
public double getEnergy() {
|
||||
return audioFeatures.getOrDefault("energy", 0.0);
|
||||
}
|
||||
|
||||
public double getInstrumentalness() {
|
||||
return audioFeatures.getOrDefault("instrumentalness", 0.0);
|
||||
}
|
||||
|
||||
public double getSpeechiness() {
|
||||
return audioFeatures.getOrDefault("speechiness", 0.0);
|
||||
}
|
||||
|
||||
public double getValence() {
|
||||
return audioFeatures.getOrDefault("valence", 0.0);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,182 @@
|
|||
package com.serena.backend.service;
|
||||
|
||||
import com.serena.backend.model.Song;
|
||||
import com.serena.backend.model.Client;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class QueueService {
|
||||
|
||||
private static final double W1_PREFERRED_QUEUE = 0.3; // preferred queue position
|
||||
private static final double W2_POPULARITY = 0.2; // popularity
|
||||
private static final double W3_TEMPO_SIMILARITY = 0.2; // tempo similarity
|
||||
private static final double W4_AUDIO_FEATURES = 0.3; // audio feature distance
|
||||
|
||||
public List<Song> sortQueue(Song currentSong, List<Song> queue, List<Client> clients) {
|
||||
if (queue == null || queue.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
if (currentSong == null) {
|
||||
return queue.stream()
|
||||
.sorted((s1, s2) -> Integer.compare(s2.getPopularity(), s1.getPopularity()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
Map<Song, Double> songScores = new HashMap<>();
|
||||
|
||||
for (Song song : queue) {
|
||||
double totalScore = calculateRecommendationScore(currentSong, song, clients, queue);
|
||||
songScores.put(song, totalScore);
|
||||
}
|
||||
|
||||
return queue.stream()
|
||||
.sorted((s1, s2) -> Double.compare(songScores.get(s2), songScores.get(s1)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private double calculateRecommendationScore(Song currentSong, Song song, List<Client> clients, List<Song> queue) {
|
||||
double p1 = calculatePreferredQueueScore(song, clients);
|
||||
double p2 = calculatePopularityScore(song);
|
||||
double p3 = calculateTempoSimilarityScore(currentSong, song, queue);
|
||||
double p4 = calculateAudioFeatureScore(currentSong, song);
|
||||
|
||||
return W1_PREFERRED_QUEUE * p1 + W2_POPULARITY * p2 + W3_TEMPO_SIMILARITY * p3 + W4_AUDIO_FEATURES * p4;
|
||||
}
|
||||
|
||||
/**
|
||||
* P1: Preferred Queue Position Score
|
||||
* For each client, find the song's rank in their preferred queue and normalize.
|
||||
*/
|
||||
private double calculatePreferredQueueScore(Song song, List<Client> clients) {
|
||||
if (clients == null || clients.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
List<Double> clientScores = new ArrayList<>();
|
||||
|
||||
for (Client client : clients) {
|
||||
Queue<Song> preferredQueue = client.getPreferredQueue();
|
||||
if (preferredQueue == null || preferredQueue.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
List<Song> preferredList = new ArrayList<>(preferredQueue);
|
||||
int position = -1;
|
||||
|
||||
for (int i = 0; i < preferredList.size(); i++) {
|
||||
if (preferredList.get(i).getId().equals(song.getId())) {
|
||||
position = i + 1; // 1-based position
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (position > 0) {
|
||||
// Normalize: 1 = most preferred (position 1), approaches 0 for later positions
|
||||
double normalizedScore = 1.0 - ((double) (position - 1) / preferredList.size());
|
||||
clientScores.add(normalizedScore);
|
||||
}
|
||||
}
|
||||
|
||||
return clientScores.isEmpty() ? 0.0 : clientScores.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* P2: Popularity Score
|
||||
* Normalize popularity from 0-100 to 0.0-1.0
|
||||
*/
|
||||
private double calculatePopularityScore(Song song) {
|
||||
return song.getPopularity() / 100.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* P3: Tempo Similarity Score
|
||||
* Calculate similarity based on tempo difference, normalized by max tempo.
|
||||
*/
|
||||
private double calculateTempoSimilarityScore(Song currentSong, Song song, List<Song> queue) {
|
||||
double currentTempo = currentSong.getTempo();
|
||||
double songTempo = song.getTempo();
|
||||
|
||||
// Find max tempo among current song and queue
|
||||
double maxTempo = Math.max(currentTempo,
|
||||
queue.stream().mapToDouble(Song::getTempo).max().orElse(currentTempo));
|
||||
|
||||
if (maxTempo == 0) {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
double tempoDistance = Math.abs(currentTempo - songTempo);
|
||||
return 1.0 - (tempoDistance / maxTempo);
|
||||
}
|
||||
|
||||
/**
|
||||
* P4: Audio Feature Distance Score
|
||||
* Calculate Euclidean distance between audio features and invert for similarity
|
||||
* score.
|
||||
*/
|
||||
private double calculateAudioFeatureScore(Song currentSong, Song song) {
|
||||
double distanceSquared = 0.0;
|
||||
int featureCount = 0;
|
||||
|
||||
// Calculate Euclidean distance for each audio feature
|
||||
double currentAcousticness = currentSong.getAcousticness();
|
||||
double songAcousticness = song.getAcousticness();
|
||||
distanceSquared += Math.pow(currentAcousticness - songAcousticness, 2);
|
||||
featureCount++;
|
||||
|
||||
double currentDanceability = currentSong.getDanceability();
|
||||
double songDanceability = song.getDanceability();
|
||||
distanceSquared += Math.pow(currentDanceability - songDanceability, 2);
|
||||
featureCount++;
|
||||
|
||||
double currentEnergy = currentSong.getEnergy();
|
||||
double songEnergy = song.getEnergy();
|
||||
distanceSquared += Math.pow(currentEnergy - songEnergy, 2);
|
||||
featureCount++;
|
||||
|
||||
double currentInstrumentalness = currentSong.getInstrumentalness();
|
||||
double songInstrumentalness = song.getInstrumentalness();
|
||||
distanceSquared += Math.pow(currentInstrumentalness - songInstrumentalness, 2);
|
||||
featureCount++;
|
||||
|
||||
double currentSpeechiness = currentSong.getSpeechiness();
|
||||
double songSpeechiness = song.getSpeechiness();
|
||||
distanceSquared += Math.pow(currentSpeechiness - songSpeechiness, 2);
|
||||
featureCount++;
|
||||
|
||||
double currentValence = currentSong.getValence();
|
||||
double songValence = song.getValence();
|
||||
distanceSquared += Math.pow(currentValence - songValence, 2);
|
||||
featureCount++;
|
||||
|
||||
if (featureCount == 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double distance = Math.sqrt(distanceSquared);
|
||||
|
||||
double maxDistance = Math.sqrt(featureCount);
|
||||
double normalizedDistance = distance / maxDistance;
|
||||
|
||||
return 1.0 - normalizedDistance;
|
||||
}
|
||||
|
||||
public static double getW1PreferredQueue() {
|
||||
return W1_PREFERRED_QUEUE;
|
||||
}
|
||||
|
||||
public static double getW2Popularity() {
|
||||
return W2_POPULARITY;
|
||||
}
|
||||
|
||||
public static double getW3TempoSimilarity() {
|
||||
return W3_TEMPO_SIMILARITY;
|
||||
}
|
||||
|
||||
public static double getW4AudioFeatures() {
|
||||
return W4_AUDIO_FEATURES;
|
||||
}
|
||||
}
|
|
@ -54,9 +54,10 @@ public class RadioStationService {
|
|||
RadioStation station = radioStations.get(stationId);
|
||||
if (station != null) {
|
||||
// Disconnect all clients
|
||||
for (Client client : station.getConnectedClients()) {
|
||||
clients.remove(client.getId());
|
||||
}
|
||||
station.getConnectedClients().clear();
|
||||
// Remove from clients map
|
||||
clients.entrySet().removeIf(entry -> stationId.equals(entry.getValue().getRadioStationId()));
|
||||
radioStations.remove(stationId);
|
||||
return true;
|
||||
}
|
||||
|
@ -69,7 +70,7 @@ public class RadioStationService {
|
|||
if (station != null && station.getJoinCode().equals(joinCode)) {
|
||||
Client client = new Client(username, radioStationId);
|
||||
clients.put(client.getId(), client);
|
||||
station.getConnectedClients().add(client.getId());
|
||||
station.getConnectedClients().add(client);
|
||||
return Optional.of(client);
|
||||
}
|
||||
return Optional.empty();
|
||||
|
@ -81,7 +82,7 @@ public class RadioStationService {
|
|||
RadioStation station = stationOpt.get();
|
||||
Client client = new Client(username, station.getId());
|
||||
clients.put(client.getId(), client);
|
||||
station.getConnectedClients().add(client.getId());
|
||||
station.getConnectedClients().add(client);
|
||||
return Optional.of(client);
|
||||
}
|
||||
return Optional.empty();
|
||||
|
@ -92,7 +93,7 @@ public class RadioStationService {
|
|||
if (client != null) {
|
||||
RadioStation station = radioStations.get(client.getRadioStationId());
|
||||
if (station != null) {
|
||||
station.getConnectedClients().remove(clientId);
|
||||
station.getConnectedClients().removeIf(c -> c.getId().equals(clientId));
|
||||
}
|
||||
clients.remove(clientId);
|
||||
return true;
|
||||
|
@ -107,10 +108,7 @@ public class RadioStationService {
|
|||
public List<Client> getConnectedClients(String radioStationId) {
|
||||
RadioStation station = radioStations.get(radioStationId);
|
||||
if (station != null) {
|
||||
return station.getConnectedClients().stream()
|
||||
.map(clients::get)
|
||||
.filter(client -> client != null)
|
||||
.toList();
|
||||
return new ArrayList<>(station.getConnectedClients());
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
@ -132,4 +130,22 @@ public class RadioStationService {
|
|||
return Optional.empty();
|
||||
}
|
||||
|
||||
// Client Queue Management
|
||||
public boolean addSongToClientQueue(String clientId, Song song) {
|
||||
Client client = clients.get(clientId);
|
||||
if (client != null) {
|
||||
client.addSongToPreferredQueue(song);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Optional<Song> getNextClientSong(String clientId) {
|
||||
Client client = clients.get(clientId);
|
||||
if (client != null) {
|
||||
return Optional.ofNullable(client.getNextPreferredSong());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
music/*
|
|
@ -1,10 +1,10 @@
|
|||
import React from 'react';
|
||||
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
|
||||
import Home from './screens/Home';
|
||||
import CreateStation from './screens/CreateStation';
|
||||
import JoinStation from './screens/JoinStation';
|
||||
import StationPage from './screens/StationPage';
|
||||
import './App.css';
|
||||
import React from "react";
|
||||
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
|
||||
import Home from "./screens/Home";
|
||||
import CreateStation from "./screens/CreateStation";
|
||||
import JoinStation from "./screens/JoinStation";
|
||||
import StationPage from "./screens/StationPage";
|
||||
import "./App.css";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
|
@ -14,7 +14,7 @@ function App() {
|
|||
<Route path="/" element={<Home />} />
|
||||
<Route path="/create-station" element={<CreateStation />} />
|
||||
<Route path="/join-station" element={<JoinStation />} />
|
||||
<Route path="/station" element={<StationPage />} />
|
||||
<Route path="/station/:id" element={<StationPage />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
</div>
|
||||
|
|
40
frontend/src/components/AudioPlayer.jsx
Normal file
40
frontend/src/components/AudioPlayer.jsx
Normal file
|
@ -0,0 +1,40 @@
|
|||
import React, { useRef, useState } from "react";
|
||||
|
||||
const SingleAudioPlayer = ({ src }) => {
|
||||
const audioRef = useRef(null);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
|
||||
// Early return if no src provided
|
||||
if (!src) {
|
||||
return <div>No audio file available</div>;
|
||||
}
|
||||
|
||||
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;
|
|
@ -2,3 +2,4 @@ export const RADIOSTATION_URL = "http://localhost:8080/api";
|
|||
|
||||
export const CREATE_RADIOSTATION_ENDPOINT = "/radio-stations";
|
||||
export const LIST_RADIOSTATIONS_ENDPOINT = "/radio-stations";
|
||||
export const ADD_CLIENT_ENDPOINT = "/clients/connect";
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,26 +1,146 @@
|
|||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { searchSpotifyTracks, isLoggedIn } from '../utils/spotifyAuth.js';
|
||||
|
||||
function AddSongModal({ onClose }) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleBackdropClick = (e) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearch = async (e) => {
|
||||
const query = e.target.value;
|
||||
setSearchQuery(query);
|
||||
setError('');
|
||||
|
||||
if (query.length > 2) {
|
||||
if (!isLoggedIn()) {
|
||||
setError('Please login to Spotify to search for songs');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const results = await searchSpotifyTracks(query);
|
||||
setSearchResults(results);
|
||||
} catch (err) {
|
||||
setError(err.message === 'Token expired' ? 'Session expired. Please login again.' : 'Search failed. Please try again.');
|
||||
setSearchResults([]);
|
||||
if (err.message === 'Token expired') {
|
||||
setTimeout(() => window.location.reload(), 2000);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyPress = async (e) => {
|
||||
if (e.key === 'Enter' && searchQuery.trim() && searchQuery.length > 2) {
|
||||
if (!isLoggedIn()) {
|
||||
setError('Please login to Spotify to search for songs');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const results = await searchSpotifyTracks(searchQuery);
|
||||
setSearchResults(results);
|
||||
setError('');
|
||||
} catch (err) {
|
||||
setError(err.message === 'Token expired' ? 'Session expired. Please login again.' : 'Search failed. Please try again.');
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={handleBackdropClick}>
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h2>Add Song</h2>
|
||||
<button className="close-btn" onClick={onClose}>
|
||||
<div className="add-song-modal-backdrop" onClick={handleBackdropClick}>
|
||||
<div className="add-song-modal-content">
|
||||
<div className="add-song-modal-header">
|
||||
<h2>Add Song to Station</h2>
|
||||
<button className="add-song-close-btn" onClick={onClose}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="modal-body">
|
||||
<p>Song addition functionality coming soon...</p>
|
||||
<div className="add-song-modal-body">
|
||||
<div className="add-song-search-container">
|
||||
<div className="add-song-search-box">
|
||||
<svg className="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
|
||||
</svg>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search for songs, artists, or albums..."
|
||||
value={searchQuery}
|
||||
onChange={handleSearch}
|
||||
onKeyPress={handleKeyPress}
|
||||
autoFocus
|
||||
/>
|
||||
{isLoading && (
|
||||
<div className="search-loading">
|
||||
<div className="loading-spinner"></div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="add-song-results-container">
|
||||
{error && (
|
||||
<div className="add-song-error">
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
)}
|
||||
{searchQuery.length === 0 ? (
|
||||
<div className="add-song-placeholder">
|
||||
<svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
|
||||
</svg>
|
||||
<p>Search for music to add to your station</p>
|
||||
<p className="placeholder-subtitle">Enter song title, artist, or album name</p>
|
||||
</div>
|
||||
) : searchQuery.length <= 2 ? (
|
||||
<div className="add-song-placeholder">
|
||||
<p>Type at least 3 characters to search</p>
|
||||
</div>
|
||||
) : searchResults.length === 0 && !isLoading && !error ? (
|
||||
<div className="add-song-placeholder">
|
||||
<p>No results found for "{searchQuery}"</p>
|
||||
<p className="placeholder-subtitle">Try different keywords</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="add-song-results-list">
|
||||
{searchResults.map(song => (
|
||||
<div key={song.id} className="add-song-result-item">
|
||||
<img src={song.coverUrl} alt={`${song.title} cover`} className="result-song-cover" />
|
||||
<div className="result-song-info">
|
||||
<h4>{song.title}</h4>
|
||||
<p className="result-artist">{song.artist}</p>
|
||||
<p className="result-album">{song.album}</p>
|
||||
</div>
|
||||
<button className="add-song-btn" onClick={() => console.log('Adding song:', song)}>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
|
||||
</svg>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -1,34 +1,184 @@
|
|||
import React, { useState } from "react";
|
||||
import { createStation } from "../utils/StationsCreate";
|
||||
|
||||
// I UNDERSTAND THIS!! --Noah
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
function CreateStation() {
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [joinCode, setJoinCode] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
|
||||
const handleCreateStation = () => {
|
||||
createStation(name, description);
|
||||
const handleCreateStation = async () => {
|
||||
if (!name.trim() || !description.trim()) {
|
||||
setError("Please fill in all fields");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const code = await createStation(name, description);
|
||||
setJoinCode(code);
|
||||
} catch (error) {
|
||||
setError(error.message || "Failed to create station");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoToStation = () => {
|
||||
// Navigate to the station or home page
|
||||
navigate("/");
|
||||
};
|
||||
|
||||
const handleCopyCode = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(joinCode);
|
||||
setIsCopied(true);
|
||||
// Reset the animation after 2 seconds
|
||||
setTimeout(() => {
|
||||
setIsCopied(false);
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
console.error('Failed to copy: ', err);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="create-station">
|
||||
<header className="create-station-header">
|
||||
<h1>Create a Station on Serena</h1>
|
||||
</header>
|
||||
<div className="create-station-container">
|
||||
<div className="create-station-main">
|
||||
{/* Left Section - Vinyl Animation */}
|
||||
<div className="create-station-left-section">
|
||||
<div className="create-station-vinyl-container">
|
||||
<div className="create-station-vinyl-record">
|
||||
<div className="vinyl-center"></div>
|
||||
<div className="vinyl-grooves"></div>
|
||||
</div>
|
||||
|
||||
{/* Animated Music Notes */}
|
||||
<div className="create-station-music-notes">
|
||||
<div className="music-note note-1">♪</div>
|
||||
<div className="music-note note-2">♫</div>
|
||||
<div className="music-note note-3">♪</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main className="create-station-content">
|
||||
<textarea onChange={(e) => setName(e.target.value)} />
|
||||
<textarea onChange={(e) => setDescription(e.target.value)} />
|
||||
{/* Right Section - Create Station Form */}
|
||||
<div className="create-station-right-section">
|
||||
<div className="create-station-content">
|
||||
<header className="create-station-header">
|
||||
<h1>Create a Station on Serena</h1>
|
||||
<p className="create-station-subtitle">Start your own collaborative music experience</p>
|
||||
</header>
|
||||
|
||||
<button
|
||||
className="create-station-final-btn"
|
||||
onClick={handleCreateStation}
|
||||
disabled={!name || !description}
|
||||
>
|
||||
Create Radio Station
|
||||
</button>
|
||||
</main>
|
||||
{!joinCode ? (
|
||||
<form className="create-station-form" onSubmit={(e) => e.preventDefault()}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="station-name">Station Name</label>
|
||||
<input
|
||||
id="station-name"
|
||||
type="text"
|
||||
placeholder="Enter your station name..."
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="station-description">Description</label>
|
||||
<textarea
|
||||
id="station-description"
|
||||
placeholder="Describe your station's vibe..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
disabled={isLoading}
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="error-message">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2L13.09 8.26L22 9L13.09 9.74L12 16L10.91 9.74L2 9L10.91 8.26L12 2Z"/>
|
||||
</svg>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="create-station-final-btn"
|
||||
onClick={handleCreateStation}
|
||||
disabled={!name.trim() || !description.trim() || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="loading-spinner"></div>
|
||||
Creating Station...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2L13.09 8.26L22 9L13.09 9.74L12 16L10.91 9.74L2 9L10.91 8.26L12 2Z"/>
|
||||
</svg>
|
||||
Create Radio Station
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="success-state">
|
||||
<div className="success-icon">
|
||||
<svg width="60" height="60" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h2>Station Created Successfully!</h2>
|
||||
<p>Your station is ready to go. Share this join code with your friends:</p>
|
||||
|
||||
<div className="join-code-display">
|
||||
<span className="join-code">{joinCode}</span>
|
||||
<button
|
||||
className={`copy-btn ${isCopied ? 'copied' : ''}`}
|
||||
onClick={handleCopyCode}
|
||||
>
|
||||
{isCopied ? (
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isCopied && (
|
||||
<div className="copy-feedback">
|
||||
<span className="copy-success-message">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
|
||||
</svg>
|
||||
Copied to clipboard!
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button className="go-to-station-btn" onClick={handleGoToStation}>
|
||||
Go to Home
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,36 +1,42 @@
|
|||
import React from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import React from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
function Home() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleCreateStation = () => {
|
||||
navigate('/create-station');
|
||||
navigate("/create-station");
|
||||
};
|
||||
|
||||
const handleJoinStation = () => {
|
||||
navigate('/join-station');
|
||||
navigate("/join-station");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="home-container">
|
||||
<div className="content">
|
||||
<h1 className="title">Radio Station Hub</h1>
|
||||
<p className="subtitle">Create or join a radio station to share music with friends</p>
|
||||
|
||||
<div className="button-container">
|
||||
<button
|
||||
className="action-button primary"
|
||||
<div className="home-content">
|
||||
<div className="home-header">
|
||||
<h1 className="home-title">Serena Station Hub</h1>
|
||||
<p className="home-subtitle">
|
||||
Create or join a radio station to share music with friends
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="home-actions">
|
||||
<button
|
||||
className="home-btn home-btn-primary"
|
||||
onClick={handleCreateStation}
|
||||
>
|
||||
Create Radio Station
|
||||
<span className="btn-icon">🎵</span>
|
||||
Create Station
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="action-button secondary"
|
||||
|
||||
<button
|
||||
className="home-btn home-btn-secondary"
|
||||
onClick={handleJoinStation}
|
||||
>
|
||||
Join Radio Station
|
||||
<span className="btn-icon">🎧</span>
|
||||
Join Station
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -5,33 +5,108 @@ import { getStations } from "../utils/GetStations";
|
|||
function JoinStation() {
|
||||
const navigate = useNavigate();
|
||||
const [stations, setStations] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const handleJoinStation = (stationID) => {
|
||||
console.log("Joining station with ID:" + stationID);
|
||||
navigate("/station");
|
||||
navigate(`/station/${stationID}`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
console.log("Test");
|
||||
|
||||
getStations(getStations());
|
||||
async function fetchStations() {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await getStations();
|
||||
setStations(result);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch stations:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
fetchStations();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="join-station">
|
||||
<header className="join-station-header">
|
||||
<h1>Join a Station on Serena</h1>
|
||||
</header>
|
||||
|
||||
<main className="join-station-content">
|
||||
{stations.map((station, index) => {
|
||||
return (
|
||||
<div className="verify-method-section">
|
||||
<text>station</text>
|
||||
<div className="join-station-container">
|
||||
<div className="join-station-main">
|
||||
{/* Left Section - Vinyl Animation */}
|
||||
<div className="join-station-left-section">
|
||||
<div className="join-station-vinyl-container">
|
||||
<div className="join-station-vinyl-record">
|
||||
<div className="vinyl-center"></div>
|
||||
<div className="vinyl-grooves"></div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</main>
|
||||
|
||||
{/* Animated Music Notes */}
|
||||
<div className="join-station-music-notes">
|
||||
<div className="music-note note-1">♪</div>
|
||||
<div className="music-note note-2">♫</div>
|
||||
<div className="music-note note-3">♪</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Section - Join Station Content */}
|
||||
<div className="join-station-right-section">
|
||||
<div className="join-station-content">
|
||||
<header className="join-station-header">
|
||||
<h1>Join a Station on Serena</h1>
|
||||
<p className="join-station-subtitle">Connect to an existing collaborative music experience</p>
|
||||
</header>
|
||||
|
||||
<div className="join-station-body">
|
||||
{isLoading ? (
|
||||
<div className="loading-state">
|
||||
<div className="loading-spinner"></div>
|
||||
<p>Loading available stations...</p>
|
||||
</div>
|
||||
) : stations.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">
|
||||
<svg width="60" height="60" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3>No stations available</h3>
|
||||
<p>There are currently no active stations to join. Create one to get started!</p>
|
||||
<button
|
||||
className="create-station-btn"
|
||||
onClick={() => navigate('/create-station')}
|
||||
>
|
||||
Create Station
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="stations-grid">
|
||||
<h2>Available Stations</h2>
|
||||
<div className="stations-list">
|
||||
{stations.map((station, index) => (
|
||||
<div key={index} className="station-card">
|
||||
<div className="station-info">
|
||||
<h3>{station.name}</h3>
|
||||
<p className="station-description">{station.description}</p>
|
||||
<div className="station-meta">
|
||||
<span className="station-id">ID: {station.id}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="join-station-btn"
|
||||
onClick={() => handleJoinStation(station.id)}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
Join Station
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,37 +1,134 @@
|
|||
import React, { useState } from 'react';
|
||||
import AddSongModal from './AddSongModal';
|
||||
import LoginButton from '../components/LoginButton';
|
||||
import { useParams } from "react-router-dom";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { addClientToStation } from "../utils/AddClientToStation";
|
||||
import { getAudioFiles } from "../utils/AudioFiles";
|
||||
import SingleAudioPlayer from "../components/AudioPlayer";
|
||||
|
||||
function StationPage() {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [currentSong, setCurrentSong] = useState({
|
||||
title: "No song playing",
|
||||
artist: "Add songs to get started",
|
||||
isPlaying: false
|
||||
});
|
||||
const { stationID } = useParams();
|
||||
const [clientToken, setClientToken] = useState("");
|
||||
const [accessDenied, setAccessDenied] = useState(true);
|
||||
const [currentSong] = useState({ progress: 0, duration: 1 });
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// Empty song list - no songs initially
|
||||
const recommendedSongs = [];
|
||||
const [userName, setUserName] = useState("");
|
||||
const [joinCode, setJoinCode] = useState("");
|
||||
|
||||
const handlePlayPause = () => {
|
||||
setCurrentSong(prev => ({ ...prev, isPlaying: !prev.isPlaying }));
|
||||
const auth = async () => {
|
||||
if (!userName.trim() || !joinCode.trim()) {
|
||||
setError("Please fill in all fields");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const token = await addClientToStation(userName, joinCode);
|
||||
setClientToken(token);
|
||||
setAccessDenied(false);
|
||||
} catch (error) {
|
||||
console.error("Auth failed:", error);
|
||||
setError(error.message || "Failed to join station");
|
||||
setAccessDenied(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
console.log('Next song');
|
||||
};
|
||||
if (accessDenied) {
|
||||
return (
|
||||
<div className="join-station-container">
|
||||
<div className="join-station-main">
|
||||
{/* Left Section - Vinyl Animation */}
|
||||
<div className="join-station-left-section">
|
||||
<div className="join-station-vinyl-container">
|
||||
<div className="join-station-vinyl-record">
|
||||
<div className="vinyl-center"></div>
|
||||
<div className="vinyl-grooves"></div>
|
||||
</div>
|
||||
|
||||
{/* Animated Music Notes */}
|
||||
<div className="join-station-music-notes">
|
||||
<div className="music-note note-1">♪</div>
|
||||
<div className="music-note note-2">♫</div>
|
||||
<div className="music-note note-3">♪</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
const handlePrevious = () => {
|
||||
console.log('Previous song');
|
||||
};
|
||||
{/* Right Section - Authentication Form */}
|
||||
<div className="join-station-right-section">
|
||||
<div className="join-station-content">
|
||||
<header className="join-station-header">
|
||||
<h1>Join Station {stationID}</h1>
|
||||
<p className="join-station-subtitle">Enter your details to access this collaborative music experience</p>
|
||||
</header>
|
||||
|
||||
const openModal = () => {
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
<form className="create-station-form" onSubmit={(e) => e.preventDefault()}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="user-name">Your Name</label>
|
||||
<input
|
||||
id="user-name"
|
||||
type="text"
|
||||
placeholder="Enter your name..."
|
||||
value={userName}
|
||||
onChange={(e) => setUserName(e.target.value)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
const closeModal = () => {
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
<div className="form-group">
|
||||
<label htmlFor="join-code">Join Code</label>
|
||||
<input
|
||||
id="join-code"
|
||||
type="text"
|
||||
placeholder="Enter the station join code..."
|
||||
value={joinCode}
|
||||
onChange={(e) => setJoinCode(e.target.value)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="error-message">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2L13.09 8.26L22 9L13.09 9.74L12 16L10.91 9.74L2 9L10.91 8.26L12 2Z"/>
|
||||
</svg>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="create-station-final-btn"
|
||||
onClick={auth}
|
||||
disabled={!userName.trim() || !joinCode.trim() || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="loading-spinner"></div>
|
||||
Joining Station...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
Join RadioTower
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const recommendedSongs = getAudioFiles() ?? [];
|
||||
|
||||
return (
|
||||
<div className="station-page">
|
||||
|
@ -45,71 +142,27 @@ function StationPage() {
|
|||
<header className="station-header">
|
||||
<h1>Serena Station</h1>
|
||||
<p className="station-subtitle">Collaborative Music Experience</p>
|
||||
<LoginButton />
|
||||
</header>
|
||||
|
||||
<div className="media-controls-section">
|
||||
<div className="current-song">
|
||||
<h3>{currentSong.title}</h3>
|
||||
<p>{currentSong.artist}</p>
|
||||
</div>
|
||||
|
||||
<div className="media-controls">
|
||||
<button className="control-btn" onClick={handlePrevious}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button className="control-btn play-pause" onClick={handlePlayPause}>
|
||||
{currentSong.isPlaying ? (
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button className="control-btn" onClick={handleNext}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{recommendedSongs.length > 0 && (
|
||||
<SingleAudioPlayer src={recommendedSongs[0]}></SingleAudioPlayer>
|
||||
)}
|
||||
|
||||
<div className="songs-section">
|
||||
<div className="section-header">
|
||||
<h2>Song Queue</h2>
|
||||
<button className="add-song-btn" onClick={openModal}>
|
||||
Add Song
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="songs-list">
|
||||
{recommendedSongs.length === 0 ? (
|
||||
<div className="empty-songs-state">
|
||||
<p>No songs in queue yet. Add some songs to get started!</p>
|
||||
</div>
|
||||
) : (
|
||||
recommendedSongs.map(song => (
|
||||
<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>
|
||||
))
|
||||
recommendedSongs.map((song) => <p>{song}</p>)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isModalOpen && <AddSongModal onClose={closeModal} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
33
frontend/src/utils/AddClientToStation.js
Normal file
33
frontend/src/utils/AddClientToStation.js
Normal file
|
@ -0,0 +1,33 @@
|
|||
import {
|
||||
RADIOSTATION_URL,
|
||||
ADD_CLIENT_ENDPOINT,
|
||||
} from "../constants/ApiConstants";
|
||||
|
||||
export async function addClientToStation(username, joinCode) {
|
||||
const body = {
|
||||
username,
|
||||
joinCode,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(RADIOSTATION_URL + ADD_CLIENT_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
console.error("Failed to connect to station:", data.message);
|
||||
throw new Error(data.message || "Unknown error");
|
||||
}
|
||||
|
||||
return data.data.clientToken;
|
||||
} catch (error) {
|
||||
console.error("Error connecting client to station:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
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)$/));
|
||||
};
|
|
@ -4,17 +4,22 @@ import {
|
|||
} from "../constants/ApiConstants";
|
||||
|
||||
export async function getStations() {
|
||||
fetch(RADIOSTATION_URL + LIST_RADIOSTATIONS_ENDPOINT, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
console.log("Station:", data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error creating station:", error);
|
||||
});
|
||||
try {
|
||||
const response = await fetch(
|
||||
RADIOSTATION_URL + LIST_RADIOSTATIONS_ENDPOINT,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Station:", data.data);
|
||||
return data.data;
|
||||
} catch (error) {
|
||||
console.error("Error fetching stations:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,22 +7,32 @@ import {
|
|||
|
||||
export async function createStation(name, description) {
|
||||
const body = {
|
||||
name: "My Awesome Station",
|
||||
description: "The best music station ever",
|
||||
name: name,
|
||||
description: description,
|
||||
};
|
||||
|
||||
fetch(RADIOSTATION_URL + CREATE_RADIOSTATION_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
console.log("Station created:", data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error creating station:", error);
|
||||
});
|
||||
try {
|
||||
const response = await fetch(
|
||||
RADIOSTATION_URL + CREATE_RADIOSTATION_ENDPOINT,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
console.error("Failed to create station:", data.message);
|
||||
throw new Error(data.message || "Unknown error");
|
||||
}
|
||||
|
||||
return data.data.station.joinCode;
|
||||
} catch (error) {
|
||||
console.error("Error connecting client to station:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,40 +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();
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue