Merge remote-tracking branch 'origin/main' into tobi-dev
This commit is contained in:
commit
e80cb2469a
18 changed files with 764 additions and 205 deletions
|
@ -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)
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -2,3 +2,7 @@ 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";
|
||||
|
||||
export const SPOTIFY_PREMIUM_TOKEN =
|
||||
"BQCEnWrYVdmta4Eekdkewazun99IuocRAyPEbwPSrHuGYgZYg7JGlXG2BLmRL6fwjzPJkrmHiqlTLSn1yqR36awA9Rv4n9dwvTBv1DjAitsuzaEVg7PtYdbUHXqP2HJJ4dDDvTtvUfWIBDY_Afa7WgY1cyRbl-p4VobNHXUR9N3Ye1qBTgH3RZ5ziIbIoNWe_JrxYvcedkvr23zXUVabOyahTgt_YdmnCWt2Iu8XT8sjhSyc8tOCqbs_KqE-Qe1WSPUCrGS8";
|
||||
|
|
|
@ -6,9 +6,10 @@ import { createStation } from "../utils/StationsCreate";
|
|||
function CreateStation() {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [joinCode, setJoinCode] = useState("");
|
||||
|
||||
const handleCreateStation = () => {
|
||||
createStation(name, description);
|
||||
setJoinCode(createStation(name, description));
|
||||
};
|
||||
|
||||
return (
|
||||
|
@ -49,6 +50,8 @@ function CreateStation() {
|
|||
>
|
||||
Create Radio Station
|
||||
</button>
|
||||
|
||||
<p>your joinCode: {joinCode}</p>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -1,65 +1,39 @@
|
|||
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="home-main">
|
||||
{/* Left Section - Logo/Animation */}
|
||||
<div className="home-left-section">
|
||||
<div className="home-vinyl-container">
|
||||
<div className="home-vinyl-record">
|
||||
<div className="vinyl-center"></div>
|
||||
<div className="vinyl-grooves"></div>
|
||||
</div>
|
||||
|
||||
{/* Animated Music Notes */}
|
||||
<div className="home-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>
|
||||
<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>
|
||||
|
||||
{/* Right Section - Content */}
|
||||
<div className="home-right-section">
|
||||
<div className="home-content">
|
||||
<h1 className="home-title">Serena Hub</h1>
|
||||
<p className="home-subtitle">Create or join a radio station to share music with friends</p>
|
||||
|
||||
<div className="home-button-container">
|
||||
<button
|
||||
className="home-action-button primary"
|
||||
onClick={handleCreateStation}
|
||||
>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
|
||||
</svg>
|
||||
Create Radio Station
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="home-action-button secondary"
|
||||
onClick={handleJoinStation}
|
||||
>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
|
||||
</svg>
|
||||
Join Radio Station
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="button-container">
|
||||
<button
|
||||
className="action-button primary"
|
||||
onClick={handleCreateStation}
|
||||
>
|
||||
Create Radio Station
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="action-button secondary"
|
||||
onClick={handleJoinStation}
|
||||
>
|
||||
Join Radio Station
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -7,14 +7,17 @@ function JoinStation() {
|
|||
const [stations, setStations] = useState([]);
|
||||
|
||||
const handleJoinStation = (stationID) => {
|
||||
console.log("Joining station with ID:" + stationID);
|
||||
navigate("/station");
|
||||
// console.log("Joining station with ID:" + stationID);
|
||||
|
||||
navigate(`/station/${stationID}`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
console.log("Test");
|
||||
|
||||
getStations(getStations());
|
||||
async function fetchStations() {
|
||||
const result = await getStations();
|
||||
setStations(result);
|
||||
}
|
||||
fetchStations();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
|
@ -47,8 +50,12 @@ function JoinStation() {
|
|||
<main className="join-station-content">
|
||||
{stations.map((station, index) => {
|
||||
return (
|
||||
<div className="verify-method-section">
|
||||
<text>station</text>
|
||||
<div key={index}>
|
||||
<p>Station Name: {station.name}</p>
|
||||
<p>Station Description: {station.description}</p>
|
||||
<button onClick={() => handleJoinStation(station.id)}>
|
||||
join this station
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
|
|
@ -1,27 +1,41 @@
|
|||
import React, { useState } from 'react';
|
||||
import AddSongModal from './AddSongModal';
|
||||
import { useParams } from "react-router-dom";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import AddSongModal from "./AddSongModal";
|
||||
import LoginButton from "../components/LoginButton";
|
||||
import { addClientToStation } from "../utils/AddClientToStation";
|
||||
|
||||
function StationPage() {
|
||||
const { stationID } = useParams();
|
||||
const [clientToken, setClientToken] = useState("");
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [currentSong, setCurrentSong] = useState({
|
||||
title: "No song playing",
|
||||
artist: "Add songs to get started",
|
||||
isPlaying: false,
|
||||
progress: 0,
|
||||
duration: 180 // 3 minutes in seconds
|
||||
});
|
||||
const [accessDenied, setAccessDenied] = useState(true);
|
||||
|
||||
const [nextSong] = useState({
|
||||
title: "No song queued",
|
||||
artist: "No Artist Queued"
|
||||
});
|
||||
const [userName, setUserName] = useState("");
|
||||
const [joinCode, setJoinCode] = useState("");
|
||||
|
||||
const auth = async () => {
|
||||
try {
|
||||
const token = await addClientToStation(userName, joinCode);
|
||||
setClientToken(token);
|
||||
setAccessDenied(false);
|
||||
} catch (error) {
|
||||
console.error("Auth failed:", error);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
};
|
||||
|
||||
if (accessDenied) {
|
||||
return (
|
||||
<div>
|
||||
<textarea onChange={(e) => setUserName(e.target.value)} />
|
||||
<textarea onChange={(e) => setJoinCode(e.target.value)} />
|
||||
<button onClick={auth}>Access RadioTower</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const recommendedSongs = [];
|
||||
|
||||
const handlePlayPause = () => {
|
||||
setCurrentSong(prev => ({ ...prev, isPlaying: !prev.isPlaying }));
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
@ -31,83 +45,44 @@ function StationPage() {
|
|||
};
|
||||
|
||||
return (
|
||||
<div className="station-page-desktop">
|
||||
{/* Main Layout */}
|
||||
<div className="desktop-main">
|
||||
{/* Left Section */}
|
||||
<div className="left-section">
|
||||
{/* Vinyl Record */}
|
||||
<div className="vinyl-container">
|
||||
<div className={`vinyl-record-desktop ${currentSong.isPlaying ? 'spinning' : ''}`}>
|
||||
<div className="vinyl-center"></div>
|
||||
<div className="vinyl-grooves"></div>
|
||||
</div>
|
||||
|
||||
{/* Animated Music Notes */}
|
||||
{currentSong.isPlaying && (
|
||||
<div className="music-notes-desktop">
|
||||
<div className="music-note note-1">♪</div>
|
||||
<div className="music-note note-2">♫</div>
|
||||
<div className="music-note note-3">♪</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="station-page">
|
||||
<div className="animated-background">
|
||||
{[...Array(20)].map((_, i) => (
|
||||
<div key={i} className={`star star-${i + 1}`}></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Next Song Info */}
|
||||
<div className="next-song-info">
|
||||
<p className="next-label">Next song:</p>
|
||||
<h4>{nextSong.title}</h4>
|
||||
<p className="next-artist">{nextSong.artist}</p>
|
||||
</div>
|
||||
<div className="station-content">
|
||||
<header className="station-header">
|
||||
<h1>Serena Station</h1>
|
||||
<p className="station-subtitle">Collaborative Music Experience</p>
|
||||
<LoginButton />
|
||||
</header>
|
||||
|
||||
{/* Bottom Play Icon */}
|
||||
<div className="bottom-play-icon">
|
||||
<button className="mini-play-btn" 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>
|
||||
)}
|
||||
<div className="songs-section">
|
||||
<div className="section-header">
|
||||
<h2>Song Queue</h2>
|
||||
<button className="add-song-btn" onClick={openModal}>
|
||||
Add Song
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Section - Recommendations */}
|
||||
<div className="right-section">
|
||||
<div className="recommendations-container">
|
||||
<div className="recommendations-header">
|
||||
<h2>Song Suggestions</h2>
|
||||
<button className="add-suggestion-btn" onClick={openModal}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="recommendations-list">
|
||||
{recommendedSongs.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '40px', color: '#aaa' }}>
|
||||
<p>No songs suggested yet</p>
|
||||
<p style={{ fontSize: '14px', marginTop: '10px' }}>Add songs to get started!</p>
|
||||
</div>
|
||||
) : (
|
||||
recommendedSongs.map(song => (
|
||||
<div key={song.id} className="recommendation-item">
|
||||
<img src={song.coverUrl} alt={`${song.title} cover`} className="song-cover" />
|
||||
<div className="song-info">
|
||||
<h4>{song.title}</h4>
|
||||
<p className="artist">{song.artist}</p>
|
||||
<p className="album">{song.album}</p>
|
||||
</div>
|
||||
<span className="duration">{song.duration}</span>
|
||||
<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>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<span className="song-duration">{song.duration}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue