\Fix navigation stack behavior and update tests"
This commit is contained in:
@@ -28,8 +28,8 @@ async def list_all_users(
|
||||
):
|
||||
return session.exec(select(User)).all()
|
||||
|
||||
@router.delete("/users/{user_id}")
|
||||
async def delete_user(
|
||||
@router.post("/users/{user_id}/toggle-status")
|
||||
async def toggle_user_status(
|
||||
user_id: int,
|
||||
admin=Depends(RoleChecker([UserRole.ADMIN])),
|
||||
session: Session = Depends(get_session)
|
||||
@@ -38,12 +38,10 @@ async def delete_user(
|
||||
if not target_user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if target_user.id == admin.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot delete yourself")
|
||||
|
||||
session.delete(target_user)
|
||||
target_user.is_active = not target_user.is_active
|
||||
session.add(target_user)
|
||||
session.commit()
|
||||
return {"message": "User deleted successfully"}
|
||||
return {"message": f"User {target_user.username} active status set to {target_user.is_active}"}
|
||||
|
||||
@router.get("/moderation")
|
||||
async def list_pending_songs(
|
||||
|
||||
@@ -77,6 +77,9 @@ async def login(data: dict, session: Session = Depends(get_session)):
|
||||
if not user or not verify_password(data.get("password"), user.hashed_password):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="Account is deactivated. Please contact administrator.")
|
||||
|
||||
return {"access_token": create_access_token({"sub": user.username}), "token_type": "bearer", "role": user.role}
|
||||
|
||||
@router.put("/change-password")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi import Depends, HTTPException, status, Request
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlmodel import Session, select
|
||||
from app.db.session import get_session
|
||||
@@ -25,6 +25,25 @@ async def get_current_user(
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return user
|
||||
|
||||
async def get_optional_user(
|
||||
request: Request,
|
||||
session: Session = Depends(get_session)
|
||||
):
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header or not auth_header.startswith("Bearer "):
|
||||
return None
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
try:
|
||||
payload = decode_access_token(token)
|
||||
if not payload:
|
||||
return None
|
||||
username = payload.get("sub")
|
||||
user = session.exec(select(User).where(User.username == username)).first()
|
||||
return user
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
class RoleChecker:
|
||||
def __init__(self, allowed_roles: list[UserRole]):
|
||||
self.allowed_roles = allowed_roles
|
||||
|
||||
@@ -7,6 +7,29 @@ from app.api.dependencies import RoleChecker, get_current_user
|
||||
|
||||
router = APIRouter(prefix="/playlists", tags=["playlists"])
|
||||
|
||||
@router.get("/liked")
|
||||
async def get_liked_songs(
|
||||
user=Depends(get_current_user),
|
||||
session: Session = Depends(get_session)
|
||||
):
|
||||
from app.models.music import UserLike, Song
|
||||
# Get all likes for the user with type LIKE
|
||||
likes = session.exec(UserLike.select().where(
|
||||
(UserLike.user_id == user.id) & (UserLike.like_type == "like")
|
||||
)).all()
|
||||
|
||||
results = []
|
||||
for like in likes:
|
||||
song = session.get(Song, like.song_id)
|
||||
if song:
|
||||
results.append({
|
||||
"id": song.id,
|
||||
"title": song.title,
|
||||
"artist": song.artist.username if song.artist else "Unknown",
|
||||
"duration": song.duration
|
||||
})
|
||||
return results
|
||||
|
||||
@router.post("/")
|
||||
async def create_playlist(
|
||||
name: str,
|
||||
|
||||
@@ -5,7 +5,7 @@ from fastapi.responses import FileResponse
|
||||
from sqlmodel import Session, select
|
||||
from app.db.session import get_session
|
||||
from app.models.music import Song, UserRole, UserLike, LikeType
|
||||
from app.api.dependencies import RoleChecker, get_current_user
|
||||
from app.api.dependencies import RoleChecker, get_current_user, get_optional_user
|
||||
from app.core.security import settings
|
||||
|
||||
router = APIRouter(prefix="/songs", tags=["songs"])
|
||||
@@ -52,12 +52,39 @@ async def stream_song(song_id: int, session: Session = Depends(get_session)):
|
||||
@router.get("/")
|
||||
async def list_songs(
|
||||
session: Session = Depends(get_session),
|
||||
user=Depends(get_current_user)
|
||||
user=Depends(get_optional_user)
|
||||
):
|
||||
# Only show approved songs to everyone, but let authors see their own unapproved songs
|
||||
stmt = select(Song).where(Song.is_approved == True)
|
||||
songs = session.exec(stmt).all()
|
||||
|
||||
# Also add current user's unapproved songs if they are the artist
|
||||
if user:
|
||||
unapproved_own = session.exec(select(Song).where((Song.artist_id == user.id) & (Song.is_approved == False))).all()
|
||||
songs.extend(unapproved_own)
|
||||
|
||||
# Get likes/dislikes for current user
|
||||
like_map = {}
|
||||
if user:
|
||||
user_likes = session.exec(select(UserLike).where(UserLike.user_id == user.id)).all()
|
||||
like_map = {l.song_id: l.like_type for l in user_likes}
|
||||
|
||||
results = []
|
||||
for song in songs:
|
||||
results.append({
|
||||
"id": song.id,
|
||||
"title": song.title,
|
||||
"artist": song.artist.username if song.artist else "Unknown",
|
||||
"album": "Single",
|
||||
"duration": song.duration,
|
||||
"likeType": like_map.get(song.id), # 'like', 'dislike' or None
|
||||
"isApproved": song.is_approved
|
||||
})
|
||||
return results
|
||||
# Only show approved songs to everyone, but let authors see their own unapproved songs
|
||||
stmt = select(Song).where(Song.is_approved == True)
|
||||
songs = session.exec(stmt).all()
|
||||
|
||||
# Also add current user's unapproved songs if they are the artist
|
||||
unapproved_own = session.exec(select(Song).where((Song.artist_id == user.id) & (Song.is_approved == False))).all()
|
||||
songs.extend(unapproved_own)
|
||||
|
||||
@@ -19,6 +19,7 @@ class User(SQLModel, table=True):
|
||||
hashed_password: str
|
||||
role: UserRole = Field(default=UserRole.LISTENER)
|
||||
is_verified: bool = Field(default=False) # Verified Author/Admin status
|
||||
is_active: bool = Field(default=True) # Active account status
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
songs: List["Song"] = Relationship(back_populates="artist", sa_relationship_kwargs={"cascade": "all, delete-orphan"})
|
||||
|
||||
@@ -21,32 +21,31 @@ async def test_admin_list_users():
|
||||
assert len(users) > 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_delete_user():
|
||||
async def test_admin_toggle_user_status():
|
||||
token = await get_token("admin", "password123")
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
# Create a temporary user to delete
|
||||
# Create a temporary user to toggle
|
||||
async with httpx.AsyncClient() as client:
|
||||
reg_res = await client.post(f"{BASE_URL}/auth/register", json={
|
||||
"username": "todelete",
|
||||
"email": "delete@example.com",
|
||||
"username": "totoggle",
|
||||
"email": "toggle@example.com",
|
||||
"password": "password123",
|
||||
"role": "listener"
|
||||
})
|
||||
user_id = reg_res.json().get("id") # Need to check if register returns id, otherwise we list users first
|
||||
user_id = reg_res.json().get("id")
|
||||
|
||||
# If registration doesn't return ID, get it from the list
|
||||
if not user_id:
|
||||
users_res = await client.get(f"{BASE_URL}/admin/users", headers=headers)
|
||||
user = next((u for u in users_res.json() if u["username"] == "todelete"), None)
|
||||
user = next((u for u in users_res.json() if u["username"] == "totoggle"), None)
|
||||
user_id = user["id"] if user else None
|
||||
|
||||
|
||||
assert user_id is not None
|
||||
|
||||
# Delete the user
|
||||
del_res = await client.delete(f"{BASE_URL}/admin/users/{user_id}", headers=headers)
|
||||
assert del_res.status_code == 200
|
||||
assert del_res.json()["message"] == "User deleted successfully"
|
||||
# Toggle the status
|
||||
toggle_res = await client.post(f"{BASE_URL}/admin/users/{user_id}/toggle-status", headers=headers)
|
||||
assert toggle_res.status_code == 200
|
||||
assert "active status set to" in toggle_res.json()["message"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_access_forbidden_for_author():
|
||||
|
||||
107
backend/tests/test_all_e2e.py
Normal file
107
backend/tests/test_all_e2e.py
Normal file
@@ -0,0 +1,107 @@
|
||||
import requests
|
||||
import json
|
||||
|
||||
BASE_URL = "http://localhost:8000"
|
||||
|
||||
def test_flow():
|
||||
print("--- Starting Full System Test Flow ---")
|
||||
uploaded_song_id = None
|
||||
listener_username = "listener"
|
||||
author_username = "author"
|
||||
admin_username = "admin"
|
||||
password = "password123"
|
||||
|
||||
# 1. Author Flow: Upload a song
|
||||
print("\n--- Testing Author Flow ---")
|
||||
login_author = {"username": author_username, "password": password}
|
||||
r = requests.post(f"{BASE_URL}/auth/login", json=login_author)
|
||||
if r.status_code != 200:
|
||||
print(f"Author Login failed: {r.status_code} - {r.text}")
|
||||
return
|
||||
|
||||
token_author = r.json().get("access_token")
|
||||
headers_author = {"Authorization": f"Bearer {token_author}"}
|
||||
|
||||
# Upload a song
|
||||
files = {'file': ('test_song.mp3', b'fake audio content', 'audio/mpeg')}
|
||||
data = {'title': 'E2E Test Song', 'genre': 'Pop'}
|
||||
r = requests.post(f"{BASE_URL}/songs/upload", headers=headers_author, files=files, data=data)
|
||||
print(f"Upload: {r.status_code} - {r.text}")
|
||||
if r.status_code == 200 or r.status_code == 201:
|
||||
try:
|
||||
uploaded_song_id = r.json().get("song_id")
|
||||
print(f"Uploaded Song ID: {uploaded_song_id}")
|
||||
except Exception as e:
|
||||
print(f"Failed to get song id from response: {e}")
|
||||
|
||||
# 2. Admin Flow: Approve the uploaded song AND ensure listener is active
|
||||
print("\n--- Testing Admin Moderation & User Mgmt ---")
|
||||
login_admin = {"username": admin_username, "password": password}
|
||||
r = requests.post(f"{BASE_URL}/auth/login", json=login_admin)
|
||||
if r.status_code != 200:
|
||||
print(f"Admin Login failed: {r.status_code} - {r.text}")
|
||||
return
|
||||
|
||||
token_admin = r.json().get("access_token")
|
||||
headers_admin = {"Authorization": f"Bearer {token_admin}"}
|
||||
|
||||
# Activate listener if deactivated
|
||||
r = requests.get(f"{BASE_URL}/admin/users", headers=headers_admin)
|
||||
if r.status_code == 200:
|
||||
users = r.json()
|
||||
target_user = next((u for u in users if u['username'] == listener_username), None)
|
||||
if target_user and not target_user['is_active']:
|
||||
r = requests.post(f"{BASE_URL}/admin/users/{target_user['id']}/toggle-status", headers=headers_admin)
|
||||
print(f"Admin Reactivated Listener: {r.status_code}")
|
||||
|
||||
if uploaded_song_id:
|
||||
r = requests.post(f"{BASE_URL}/admin/moderation/{uploaded_song_id}/approve", headers=headers_admin)
|
||||
print(f"Approve Song {uploaded_song_id}: {r.status_code} - {r.text}")
|
||||
else:
|
||||
print("No uploaded song ID available to approve.")
|
||||
|
||||
# 3. Listener Flow: Discover, Like, and Stream the approved song
|
||||
print("\n--- Testing Listener Flow ---")
|
||||
login_listener = {"username": listener_username, "password": password}
|
||||
r = requests.post(f"{BASE_URL}/auth/login", json=login_listener)
|
||||
if r.status_code != 200:
|
||||
print(f"Listener Login failed: {r.status_code} - {r.text}")
|
||||
return
|
||||
|
||||
token_listener = r.json().get("access_token")
|
||||
headers_listener = {"Authorization": f"Bearer {token_listener}"}
|
||||
|
||||
# Discover songs
|
||||
r = requests.get(f"{BASE_URL}/songs/", headers=headers_listener)
|
||||
print(f"Discover: {r.status_code} - {r.text}")
|
||||
|
||||
if uploaded_song_id:
|
||||
# Like the specific song we uploaded (which adds it to Liked Songs)
|
||||
r = requests.post(f"{BASE_URL}/songs/{uploaded_song_id}/like", headers=headers_listener)
|
||||
print(f"Like Song {uploaded_song_id}: {r.status_code} - {r.text}")
|
||||
|
||||
# Stream the specific song we uploaded
|
||||
r = requests.get(f"{BASE_URL}/songs/{uploaded_song_id}/stream")
|
||||
print(f"Stream Song {uploaded_song_id}: {r.status_code}")
|
||||
else:
|
||||
print("No uploaded song ID available to test saving/streaming.")
|
||||
|
||||
# 4. Admin Flow: List users and toggle status of listener (instead of deleting, for repeatable tests)
|
||||
print("\n--- Testing Admin User Management ---")
|
||||
# List users
|
||||
r = requests.get(f"{BASE_URL}/admin/users", headers=headers_admin)
|
||||
print(f"List Users: {r.status_code} - {r.text}")
|
||||
if r.status_code == 200:
|
||||
users = r.json()
|
||||
target_user = next((u for u in users if u['username'] == listener_username), None)
|
||||
if target_user:
|
||||
user_id = target_user['id']
|
||||
r = requests.post(f"{BASE_URL}/admin/users/{user_id}/toggle-status", headers=headers_admin)
|
||||
print(f"Admin Toggle Status User {user_id}: {r.status_code} - {r.text}")
|
||||
else:
|
||||
print("Target listener user not found.")
|
||||
else:
|
||||
print("Could not list users.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_flow()
|
||||
@@ -19,5 +19,17 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
frontend:
|
||||
build: ./frontend
|
||||
ports:
|
||||
- "8081:8081"
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
- /app/node_modules
|
||||
environment:
|
||||
- EXPO_PUBLIC_API_URL=http://localhost:8000
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
7
frontend/Dockerfile
Normal file
7
frontend/Dockerfile
Normal file
@@ -0,0 +1,7 @@
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
EXPOSE 8081
|
||||
CMD ["npx", "expo", "start", "--web", "--clear"]
|
||||
@@ -2,8 +2,10 @@ import axios from 'axios';
|
||||
import { Platform } from 'react-native';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
const BASE_URL = Platform.OS === 'web' ? 'http://localhost:8000' : 'http://192.168.1.130:8000';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: Platform.OS === 'web' ? 'http://localhost:8000' : 'http://192.168.1.130:8000', // Use localhost for web, local IP for physical device (Expo Go)
|
||||
baseURL: BASE_URL, // Use localhost for web, local IP for physical device (Expo Go)
|
||||
});
|
||||
|
||||
// Add interceptor to attach JWT token
|
||||
@@ -15,4 +17,5 @@ api.interceptors.request.use(async (config) => {
|
||||
return config;
|
||||
});
|
||||
|
||||
export { BASE_URL };
|
||||
export default api;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { Audio } from 'expo-av';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
import { BASE_URL } from '../api/client';
|
||||
|
||||
export default function AudioPlayer() {
|
||||
const navigation = useNavigation();
|
||||
@@ -28,7 +29,7 @@ export default function AudioPlayer() {
|
||||
}
|
||||
|
||||
const { sound: newSound } = await Audio.Sound.createAsync(
|
||||
`http://localhost:8000/songs/${currentSong.id}/stream`,
|
||||
`${BASE_URL}/songs/${currentSong.id}/stream`,
|
||||
{ shouldPlay: isPlaying }
|
||||
);
|
||||
|
||||
|
||||
268
frontend/src/components/SongListItem.tsx
Normal file
268
frontend/src/components/SongListItem.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, Text, TouchableOpacity, StyleSheet, Alert, Modal, FlatList, TextInput } from 'react-native';
|
||||
import api from '../api/client';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
import { usePlaylistStore } from '../store/playlistStore';
|
||||
|
||||
export default function SongListItem({ song, index, onPress }) {
|
||||
const { toggleSave, savedSongs, setSongs, allSongs } = useSongStore();
|
||||
const { playlists, setPlaylists, addPlaylist } = usePlaylistStore();
|
||||
const [isModalVisible, setIsModalVisible] = useState(false);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [newPlaylistName, setNewPlaylistName] = useState('');
|
||||
const handleAddToPlaylist = () => {
|
||||
setIsModalVisible(true);
|
||||
setIsCreating(false);
|
||||
};
|
||||
const isSaved = savedSongs.includes(song.id);
|
||||
|
||||
|
||||
const handleLike = async () => {
|
||||
try {
|
||||
let newLikeType;
|
||||
if (song.likeType === 'like') {
|
||||
await api.delete(`/songs/${song.id}/unlike`);
|
||||
newLikeType = undefined;
|
||||
} else if (song.likeType === 'dislike') {
|
||||
await api.post(`/songs/${song.id}/like`);
|
||||
newLikeType = 'like';
|
||||
} else {
|
||||
await api.post(`/songs/${song.id}/like`);
|
||||
newLikeType = 'like';
|
||||
}
|
||||
|
||||
const updatedSongs = allSongs.map(s => s.id === song.id ? { ...s, likeType: newLikeType } : s);
|
||||
setSongs(updatedSongs);
|
||||
} catch (e) {
|
||||
console.error('Like error:', e);
|
||||
Alert.alert('Error', 'Could not update like status');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
if (!isSaved) {
|
||||
const response = await api.get(`/songs/${song.id}/stream`, { responseType: 'blob' });
|
||||
if (typeof window !== 'undefined') {
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${song.title}.mp3`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.parentNode.removeChild(link);
|
||||
} else {
|
||||
Alert.alert('Save Offline', 'Offline saving is currently only supported on web.');
|
||||
}
|
||||
}
|
||||
toggleSave(song.id);
|
||||
} catch (e) {
|
||||
console.error('Save error:', e);
|
||||
Alert.alert('Error', 'Failed to save song for offline use');
|
||||
}
|
||||
};
|
||||
|
||||
const addSongToPlaylist = async (playlistId) => {
|
||||
try {
|
||||
await api.post(`/playlists/${playlistId}/songs/${song.id}`);
|
||||
Alert.alert('Success', 'Song added to playlist');
|
||||
setIsModalVisible(false);
|
||||
} catch (e) {
|
||||
console.error('Add to playlist error:', e);
|
||||
Alert.alert('Error', 'Failed to add song to playlist');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreatePlaylist = async () => {
|
||||
if (!newPlaylistName.trim()) {
|
||||
Alert.alert('Error', 'Please enter a playlist name');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await api.post('/playlists', { params: { name: newPlaylistName } });
|
||||
const newPlaylist = response.data;
|
||||
addPlaylist(newPlaylist);
|
||||
await addSongToPlaylist(newPlaylist.id);
|
||||
setNewPlaylistName('');
|
||||
setIsCreating(false);
|
||||
} catch (e) {
|
||||
console.error('Create playlist error:', e);
|
||||
Alert.alert('Error', 'Failed to create playlist');
|
||||
}
|
||||
};
|
||||
|
||||
// Format time in seconds to mm:ss
|
||||
const formatTime = (seconds) => {
|
||||
if (!seconds && seconds !== 0) return '00:00';
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = Math.floor(seconds % 60);
|
||||
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<View>
|
||||
<TouchableOpacity style={styles.container} onPress={() => onPress(song)}>
|
||||
<View style={styles.info}>
|
||||
<Text style={styles.text}>{index + 1}. {song.title}</Text>
|
||||
<Text style={styles.artist}> — {song.artist}</Text>
|
||||
<Text style={styles.duration}> {formatTime(song.duration)}</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.actions}>
|
||||
<TouchableOpacity onPress={handleLike} style={styles.actionBtn}>
|
||||
<Text style={{ fontSize: 16 }}>{song.likeType === 'like' ? '❤️' : '♡'}</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={handleAddToPlaylist} style={styles.actionBtn}>
|
||||
<Text style={{ fontSize: 18, fontWeight: 'bold' }}>+</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={handleSave} style={styles.actionBtn}>
|
||||
<Text style={{ color: isSaved ? '#ff6347' : '#ccc', fontSize: 16 }}>■</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
|
||||
<Modal visible={isModalVisible} transparent={true} animationType="fade">
|
||||
<View style={styles.modalOverlay}>
|
||||
<View style={styles.modalContent}>
|
||||
<Text style={styles.modalTitle}>Add to Playlist</Text>
|
||||
{isCreating ? (
|
||||
<View style={styles.createPlaylistContainer}>
|
||||
<TextInput
|
||||
style={styles.playlistInput}
|
||||
placeholder="Enter playlist name..."
|
||||
value={newPlaylistName}
|
||||
onChangeText={setNewPlaylistName}
|
||||
/>
|
||||
<TouchableOpacity style={styles.confirmBtn} onPress={handleCreatePlaylist}>
|
||||
<Text style={{ color: 'white', fontWeight: 'bold' }}>Confirm</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={styles.cancelBtn} onPress={() => setIsCreating(false)}>
|
||||
<Text style={{ color: 'gray' }}>Cancel</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
<FlatList
|
||||
data={playlists}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
renderItem={({ item }) => (
|
||||
<TouchableOpacity style={styles.playlistOption} onPress={() => addSongToPlaylist(item.id)}>
|
||||
<Text>{item.name}</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
/>
|
||||
<TouchableOpacity style={styles.createBtn} onPress={() => setIsCreating(true)}>
|
||||
<Text style={{ color: '#ff6347', fontWeight: 'bold' }}>+ Create New Playlist</Text>
|
||||
</TouchableOpacity>
|
||||
</>
|
||||
)}>
|
||||
<TouchableOpacity style={styles.closeBtn} onPress={() => setIsModalVisible(false)}>
|
||||
<Text style={{ color: 'gray' }}>Cancel</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
padding: 12,
|
||||
backgroundColor: 'white',
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#eee',
|
||||
},
|
||||
info: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
flex: 1,
|
||||
},
|
||||
text: {
|
||||
fontSize: 16,
|
||||
fontWeight: '500',
|
||||
color: '#333',
|
||||
},
|
||||
artist: {
|
||||
fontSize: 14,
|
||||
color: '#888',
|
||||
},
|
||||
duration: {
|
||||
fontSize: 12,
|
||||
color: '#aaa',
|
||||
marginLeft: 5,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
actionBtn: {
|
||||
width: 30,
|
||||
alignItems: 'center',
|
||||
paddingHorizontal: 5,
|
||||
},
|
||||
modalOverlay: {
|
||||
flex: 1,
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
modalContent: {
|
||||
backgroundColor: 'white',
|
||||
width: '80%',
|
||||
borderRadius: 20,
|
||||
padding: 20,
|
||||
maxHeight: '60%',
|
||||
},
|
||||
modalTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: 15,
|
||||
textAlign: 'center',
|
||||
},
|
||||
playlistOption: {
|
||||
paddingVertical: 12,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#eee',
|
||||
alignItems: 'center',
|
||||
},
|
||||
createBtn: {
|
||||
marginTop: 15,
|
||||
alignItems: 'center',
|
||||
padding: 10,
|
||||
},
|
||||
closeBtn: {
|
||||
marginTop: 10,
|
||||
alignItems: 'center',
|
||||
padding: 10,
|
||||
},
|
||||
createPlaylistContainer: {
|
||||
width: '100%',
|
||||
alignItems: 'center',
|
||||
},
|
||||
playlistInput: {
|
||||
width: '100%',
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#ccc',
|
||||
paddingVertical: 10,
|
||||
fontSize: 16,
|
||||
marginBottom: 20,
|
||||
textAlign: 'center',
|
||||
},
|
||||
confirmBtn: {
|
||||
backgroundColor: '#ff6347',
|
||||
padding: 10,
|
||||
borderRadius: 10,
|
||||
width: '100%',
|
||||
alignItems: 'center',
|
||||
marginBottom: 10,
|
||||
},
|
||||
cancelBtn: {
|
||||
padding: 10,
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
}
|
||||
});
|
||||
@@ -18,8 +18,13 @@ export default function CreatePlaylistScreen({ navigation }) {
|
||||
// FastAPI by default takes these as query params if not specified as Body.
|
||||
const response = await api.post(`/playlists/?name=${encodeURIComponent(name)}&description=${encodeURIComponent(description)}`);
|
||||
addPlaylist(response.data);
|
||||
Alert.alert('Success', 'Playlist created!');
|
||||
navigation.navigate('Playlists');
|
||||
Alert.alert('Success', 'Playlist created!', [
|
||||
{ text: 'OK', onPress: () => {
|
||||
setName('');
|
||||
setDescription('');
|
||||
navigation.navigate('Playlists');
|
||||
}}
|
||||
]);
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Failed to create playlist');
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
|
||||
import api from '../api/client';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import SongListItem from '../components/SongListItem';
|
||||
|
||||
export default function DiscoveryScreen({ navigation }) {
|
||||
const { allSongs, setSongs, setCurrentSong } = useSongStore();
|
||||
@@ -21,63 +22,6 @@ export default function DiscoveryScreen({ navigation }) {
|
||||
}
|
||||
};
|
||||
|
||||
const renderItem = ({ item }) => {
|
||||
const likeType = item.likeType; // 'like', 'dislike' or undefined
|
||||
|
||||
const handleLikeAction = async (type) => {
|
||||
try {
|
||||
if (type === 'like') {
|
||||
await api.post(`/songs/${item.id}/like`);
|
||||
} else if (type === 'dislike') {
|
||||
await api.post(`/songs/${item.id}/dislike`);
|
||||
} else {
|
||||
await api.delete(`/songs/${item.id}/unlike`);
|
||||
}
|
||||
setSongs(useSongStore.getState().allSongs.map(s => s.id === item.id ? { ...s, likeType: type === 'unlike' ? undefined : type } : s));
|
||||
} catch (error) {
|
||||
console.error('Error updating like:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadForOffline = async () => {
|
||||
try {
|
||||
const response = await api.get(`/songs/${item.id}/stream`, { responseType: 'blob' });
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${item.title}.mp3`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.parentNode.removeChild(link);
|
||||
} catch (error) {
|
||||
console.error('Error downloading song:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<TouchableOpacity style={styles.songItem} onPress={() => setCurrentSong(item)}>
|
||||
<View style={styles.songInfo}>
|
||||
<Text style={styles.songTitle}>{item.title}</Text>
|
||||
<Text style={styles.songArtist}>{item.artist}</Text>
|
||||
</View>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
|
||||
<TouchableOpacity onPress={() => handleLikeAction('like')} style={{ marginRight: 10 }}>
|
||||
<Text style={{ fontSize: 20, color: likeType === 'like' ? 'red' : 'gray' }}>❤️</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={() => handleLikeAction('dislike')} style={{ marginRight: 10 }}>
|
||||
<Text style={{ fontSize: 20, color: likeType === 'dislike' ? 'blue' : 'gray' }}>👎</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={downloadForOffline} style={{ marginRight: 10 }}>
|
||||
<Text style={{ fontSize: 20 }}>💾</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<TouchableOpacity style={styles.playButton} onPress={() => setCurrentSong(item)}>
|
||||
<Text style={{ color: 'white' }}>Play</Text>
|
||||
</TouchableOpacity>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.menuBar}>
|
||||
@@ -113,7 +57,9 @@ export default function DiscoveryScreen({ navigation }) {
|
||||
<FlatList
|
||||
data={allSongs}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
renderItem={renderItem}
|
||||
renderItem={({ item, index }) => (
|
||||
<SongListItem song={item} index={index} onPress={() => setCurrentSong(item)} />
|
||||
)}
|
||||
ListEmptyComponent={<Text style={styles.emptyText}>No songs found.</Text>}
|
||||
/>
|
||||
</View>
|
||||
@@ -129,23 +75,5 @@ const styles = StyleSheet.create({
|
||||
justifyContent: 'space-around'
|
||||
},
|
||||
menuItem: { padding: 8 },
|
||||
songItem: {
|
||||
flexDirection: 'row',
|
||||
padding: 15,
|
||||
backgroundColor: 'white',
|
||||
borderBottomWidth: 1,
|
||||
borderColor: '#eee',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
},
|
||||
songInfo: { flex: 1 },
|
||||
songTitle: { fontSize: 16, fontWeight: 'bold' },
|
||||
songArtist: { fontSize: 14, color: '#666' },
|
||||
playButton: {
|
||||
backgroundColor: '#ff6347',
|
||||
padding: 8,
|
||||
borderRadius: 20,
|
||||
marginLeft: 10
|
||||
},
|
||||
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { View, Text, TouchableOpacity, StyleSheet, Dimensions, Alert } from 'react-native';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Dimensions, Alert } from 'react-native';
|
||||
import api from '../api/client';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
|
||||
@@ -35,6 +35,26 @@ export default function NowPlayingScreen({ navigation }) {
|
||||
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
|
||||
};
|
||||
|
||||
const handleSaveForOffline = async () => {
|
||||
try {
|
||||
const response = await api.get(`/songs/${currentSong.id}/stream`, { responseType: 'blob' });
|
||||
if (typeof window !== 'undefined') {
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${currentSong.title}.mp3`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.parentNode.removeChild(link);
|
||||
} else {
|
||||
Alert.alert('Save Offline', 'Offline saving is currently only supported on web.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error downloading song:', e);
|
||||
Alert.alert('Error', 'Failed to save song for offline use');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLikeAction = async (type) => {
|
||||
try {
|
||||
if (type === 'like') await api.post(`/songs/${currentSong.id}/like`);
|
||||
@@ -60,8 +80,7 @@ export default function NowPlayingScreen({ navigation }) {
|
||||
<View style={[styles.progress, { width: `${(position / duration) * 100}%` }]} />
|
||||
</TouchableOpacity>
|
||||
<View style={styles.timeRow}>
|
||||
<Text style={styles.time}>{formatTime(position)}</Text>
|
||||
<Text style={styles.time}>{formatTime(duration)}</Text>
|
||||
<Text style={styles.time}>{formatTime(position)} / {formatTime(duration)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -84,6 +103,9 @@ export default function NowPlayingScreen({ navigation }) {
|
||||
<TouchableOpacity onPress={() => handleLikeAction('dislike')} style={styles.actionButton}>
|
||||
<Text style={styles.actionText}>👎 Dislike</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={handleSaveForOffline} style={styles.actionButton}>
|
||||
<Text style={styles.actionText}>💾 Save</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={styles.footerRow}>
|
||||
@@ -114,7 +136,7 @@ const styles = StyleSheet.create({
|
||||
sliderContainer: { width: '100%', marginBottom: 40 },
|
||||
sliderBar: { height: 8, backgroundColor: '#eee', borderRadius: 4, position: 'relative' },
|
||||
progress: { height: '100%', backgroundColor: '#ff6347', borderRadius: 4 },
|
||||
timeRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 5 },
|
||||
timeRow: { flexDirection: 'row', justifyContent: 'center', marginTop: 5 },
|
||||
time: { fontSize: 12, color: '#999' },
|
||||
mainControls: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 40 },
|
||||
controlButton: { marginHorizontal: 30 },
|
||||
@@ -122,9 +144,9 @@ const styles = StyleSheet.create({
|
||||
playButton: { backgroundColor: '#ff6347', width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center' },
|
||||
playText: { fontSize: 40, color: 'white' },
|
||||
actionRow: { flexDirection: 'row', justifyContent: 'space-around', marginBottom: 30 },
|
||||
actionButton: { padding: 10, backgroundColor: '#f0f0f0', borderRadius: 10, width: '45%', alignItems: 'center' },
|
||||
actionButton: { padding: 10, backgroundColor: '#f0f0f0', borderRadius: 10, width: '30%', alignItems: 'center' },
|
||||
actionText: { fontWeight: 'bold', color: '#333' },
|
||||
footerRow: { flexDirection: 'row', justifyContent: 'space-around' },
|
||||
secondaryButton: { padding: 12, backgroundColor: '#eee', borderRadius: 10, width: '45%', alignItems: 'center' },
|
||||
secondaryText: { color: '#666', fontSize: 14 }
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert } from 'react-native';
|
||||
import { View, Text, FlatList, StyleSheet } from 'react-native';
|
||||
import api from '../api/client';
|
||||
import SongListItem from '../components/SongListItem';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
|
||||
export default function PlaylistDetailScreen({ route }) {
|
||||
const { playlistId } = route.params;
|
||||
const [songs, setSongs] = useState([]);
|
||||
const { setCurrentSong } = useSongStore();
|
||||
|
||||
useEffect(() => {
|
||||
fetchSongs();
|
||||
@@ -12,39 +15,22 @@ export default function PlaylistDetailScreen({ route }) {
|
||||
|
||||
const fetchSongs = async () => {
|
||||
try {
|
||||
const response = await api.get(`/playlists/${playlistId}/songs`);
|
||||
// The backend returns PlaylistSong objects which contain song_id.
|
||||
// We need to resolve these to Song objects or just show the ID for now.
|
||||
const endpoint = playlistId === 'liked' ? '/playlists/liked' : `/playlists/${playlistId}/songs`;
|
||||
const response = await api.get(endpoint);
|
||||
setSongs(response.data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching playlist songs:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const renderItem = ({ item }) => (
|
||||
<View style={styles.songItem}>
|
||||
<Text>{item.title} - {item.artist}</Text>
|
||||
<TouchableOpacity onPress={() => removeSong(item.id)}>
|
||||
<Text style={{ color: 'red' }}>Remove</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
|
||||
const removeSong = async (songId) => {
|
||||
try {
|
||||
// Backend doesn't have a delete endpoint for playlist songs yet!
|
||||
Alert.alert('Not Implemented', 'Removing songs from playlists is not yet implemented in backend.');
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Failed to remove song');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<FlatList
|
||||
data={songs}
|
||||
keyExtractor={(item, index) => index.toString()}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item, index) => (item.id || index).toString()}
|
||||
renderItem={({ item, index }) => (
|
||||
<SongListItem song={item} index={index} onPress={() => setCurrentSong(item)} />
|
||||
)}
|
||||
ListEmptyComponent={<Text style={styles.emptyText}>This playlist is empty.</Text>}
|
||||
/>
|
||||
</View>
|
||||
@@ -53,13 +39,5 @@ export default function PlaylistDetailScreen({ route }) {
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: '#f5f5f5' },
|
||||
songItem: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
padding: 15,
|
||||
backgroundColor: 'white',
|
||||
borderBottomWidth: 1,
|
||||
borderColor: '#eee'
|
||||
},
|
||||
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
|
||||
});
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
|
||||
import api from '../api/client';
|
||||
import { usePlaylistStore } from '../store/playlistStore';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
|
||||
export default function PlaylistsScreen({ navigation }) {
|
||||
const { playlists, setPlaylists } = usePlaylistStore();
|
||||
const { savedSongs } = useSongStore();
|
||||
const [hasLikedSongs, setHasLikedSongs] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPlaylists();
|
||||
checkLikedSongs();
|
||||
}, []);
|
||||
|
||||
const checkLikedSongs = async () => {
|
||||
try {
|
||||
const response = await api.get('/playlists/liked');
|
||||
setHasLikedSongs(response.data.length > 0);
|
||||
} catch (error) {
|
||||
console.error('Error checking liked songs:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchPlaylists = async () => {
|
||||
try {
|
||||
const response = await api.get('/playlists/');
|
||||
@@ -35,7 +48,31 @@ export default function PlaylistsScreen({ navigation }) {
|
||||
data={playlists}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
renderItem={renderItem}
|
||||
ListEmptyComponent={<Text style={styles.emptyText}>No playlists yet.</Text>}
|
||||
ListHeaderComponent={() => (
|
||||
<>
|
||||
{hasLikedSongs && (
|
||||
<TouchableOpacity
|
||||
style={[styles.playlistItem, { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1 }]}
|
||||
onPress={() => navigation.navigate('PlaylistDetail', { playlistId: 'liked' })}
|
||||
>
|
||||
<Text style={[styles.playlistName, { color: '#ff6347' }]}>❤️ Liked Songs</Text>
|
||||
<Text style={styles.playlistDesc}>All your liked tracks</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
{savedSongs.length > 0 && (
|
||||
<TouchableOpacity
|
||||
style={[styles.playlistItem, { backgroundColor: '#eef9ff', borderColor: '#4682b4', borderWidth: 1 }]}
|
||||
onPress={() => navigation.navigate('PlaylistDetail', { playlistId: 'saved' })}
|
||||
>
|
||||
<Text style={[styles.playlistName, { color: '#4682b4' }]}>💾 Saved Songs</Text>
|
||||
<Text style={styles.playlistDesc}>Downloaded for offline use</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
ListEmptyComponent={playlists.length === 0 && !hasLikedSongs && savedSongs.length === 0 ? (
|
||||
<View><Text style={styles.emptyText}>No playlists yet.</Text></View>
|
||||
) : null}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={styles.fab}
|
||||
|
||||
@@ -1,30 +1,27 @@
|
||||
import React from 'react';
|
||||
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
|
||||
import { View, Text, FlatList, StyleSheet } from 'react-native';
|
||||
import { useSongStore } from '../store/songStore';
|
||||
import SongListItem from '../components/SongListItem';
|
||||
|
||||
export default function QueueScreen({ navigation }) {
|
||||
const { queue, setCurrentSong, currentIndex } = useSongStore();
|
||||
|
||||
const renderItem = ({ item, index }) => (
|
||||
<TouchableOpacity
|
||||
style={[styles.item, index === currentIndex && styles.activeItem]}
|
||||
onPress={() => setCurrentSong(item)}
|
||||
>
|
||||
<View style={styles.info}>
|
||||
<Text style={[styles.title, index === currentIndex && styles.activeTitle]}>{item.title}</Text>
|
||||
<Text style={[styles.artist, index === currentIndex && styles.activeArtist]}>{item.artist}</Text>
|
||||
</View>
|
||||
{index === currentIndex && <Text style={styles.nowPlaying}>Now Playing</Text>}
|
||||
</TouchableOpacity>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.header}>Up Next</Text>
|
||||
<FlatList
|
||||
data={queue}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
renderItem={renderItem}
|
||||
renderItem={({ item, index }) => (
|
||||
<View style={[index === currentIndex && styles.activeWrapper]}>
|
||||
<SongListItem
|
||||
song={item}
|
||||
index={index}
|
||||
onPress={() => setCurrentSong(item)}
|
||||
/>
|
||||
{index === currentIndex && <Text style={styles.nowPlaying}>Now Playing</Text>}
|
||||
</View>
|
||||
)}
|
||||
ListEmptyComponent={<Text style={styles.emptyText}>Queue is empty.</Text>}
|
||||
/>
|
||||
</View>
|
||||
@@ -34,21 +31,7 @@ export default function QueueScreen({ navigation }) {
|
||||
const styles = StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: '#f5f5f5', padding: 20 },
|
||||
header: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, color: '#333' },
|
||||
item: {
|
||||
flexDirection: 'row',
|
||||
padding: 15,
|
||||
backgroundColor: 'white',
|
||||
borderRadius: 10,
|
||||
marginBottom: 10,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
},
|
||||
activeItem: { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1 },
|
||||
info: { flex: 1 },
|
||||
title: { fontSize: 16, fontWeight: 'bold' },
|
||||
artist: { fontSize: 14, color: '#666' },
|
||||
activeTitle: { color: '#ff6347', fontWeight: 'bold' },
|
||||
activeArtist: { color: '#ff6347' },
|
||||
nowPlaying: { fontSize: 12, color: '#ff6347', fontWeight: 'bold' },
|
||||
activeWrapper: { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1, borderRadius: 5 },
|
||||
nowPlaying: { fontSize: 12, color: '#ff6347', fontWeight: 'bold', textAlign: 'center', paddingBottom: 5 },
|
||||
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
|
||||
});
|
||||
@@ -7,8 +7,15 @@ export default function RegisterScreen({ navigation }) {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isAuthor, setIsAuthor] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!username || !email || !password) {
|
||||
Alert.alert('Error', 'Please fill in all fields');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const endpoint = isAuthor ? '/auth/register-author' : '/auth/register';
|
||||
await api.post(endpoint, {
|
||||
@@ -22,6 +29,8 @@ export default function RegisterScreen({ navigation }) {
|
||||
} catch (error) {
|
||||
const message = error.response?.data?.detail || 'Registration failed';
|
||||
Alert.alert('Error', message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -29,45 +38,56 @@ export default function RegisterScreen({ navigation }) {
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.title}>Create Account</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, isLoading && { opacity: 0.5 }]}
|
||||
placeholder="Username"
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
editable={!isLoading}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, isLoading && { opacity: 0.5 }]}
|
||||
placeholder="Email"
|
||||
keyboardType="email-address"
|
||||
value={email}
|
||||
onChangeText={setEmail}
|
||||
editable={!isLoading}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, isLoading && { opacity: 0.5 }]}
|
||||
placeholder="Password"
|
||||
secureTextEntry
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
editable={!isLoading}
|
||||
/>
|
||||
|
||||
<View style={styles.roleContainer}>
|
||||
<TouchableOpacity
|
||||
style={[styles.roleButton, !isAuthor && styles.activeRole]}
|
||||
onPress={() => setIsAuthor(false)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={[styles.roleText, !isAuthor && styles.activeRoleText]}>Listener</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={[styles.roleButton, isAuthor && styles.activeRole]}
|
||||
onPress={() => setIsAuthor(true)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={[styles.roleText, isAuthor && styles.activeRoleText]}>Author</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<Button title="Register" onPress={handleRegister} />
|
||||
<View style={{ marginTop: 20, alignItems: 'center' }}>
|
||||
<Button title="Already have an account? Login" onPress={() => navigation.navigate('Login')} />
|
||||
</View>
|
||||
|
||||
{isLoading ? (
|
||||
<Text style={{ textAlign: 'center', marginBottom: 20 }}>Registering...</Text>
|
||||
) : (
|
||||
<>
|
||||
<Button title="Register" onPress={handleRegister} />
|
||||
<View style={{ marginTop: 20, alignItems: 'center' }}>
|
||||
<Button title="Already have an account? Login" onPress={() => navigation.navigate('Login')} />
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -46,11 +46,14 @@ export default function UploadScreen({ navigation }) {
|
||||
|
||||
await api.post('/songs/upload', formData);
|
||||
|
||||
Alert.alert('Success', 'Song uploaded successfully!');
|
||||
navigation.navigate('Discovery');
|
||||
setTitle('');
|
||||
setGenre('');
|
||||
setFile(null);
|
||||
Alert.alert('Success', 'Song uploaded successfully!', [
|
||||
{ text: 'OK', onPress: () => {
|
||||
setTitle('');
|
||||
setGenre('');
|
||||
setFile(null);
|
||||
navigation.navigate('Discovery');
|
||||
}}
|
||||
]);
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
Alert.alert('Error', 'Failed to upload song');
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware/persist';
|
||||
|
||||
interface Song {
|
||||
id: number;
|
||||
@@ -19,61 +20,83 @@ interface SongState {
|
||||
position: number; // current playback position in ms
|
||||
duration: number; // total song duration in ms
|
||||
seekPosition: number | null; // target position to seek to
|
||||
savedSongs: number[]; // IDs of saved songs
|
||||
setSongs: (songs: Song[]) => void;
|
||||
setCurrentSong: (song: Song | null) => void;
|
||||
setIsPlaying: (playing: boolean) => void;
|
||||
setPosition: (pos: number) => void;
|
||||
setDuration: (dur: number) => void;
|
||||
setSeekPosition: (pos: number | null) => void;
|
||||
toggleSave: (songId: number) => void;
|
||||
addToQueue: (song: Song) => void;
|
||||
setQueue: (songs: Song[]) => void;
|
||||
playNext: () => void;
|
||||
playPrev: () => void;
|
||||
}
|
||||
|
||||
export const useSongStore = create<SongState>((set, get) => ({
|
||||
allSongs: [],
|
||||
currentSong: null,
|
||||
queue: [],
|
||||
currentIndex: -1,
|
||||
isPlaying: false,
|
||||
position: 0,
|
||||
duration: 0,
|
||||
seekPosition: null,
|
||||
setSongs: (songs) => set({ allSongs: songs }),
|
||||
setCurrentSong: (song) => {
|
||||
if (!song) {
|
||||
set({ currentSong: null, position: 0 });
|
||||
return;
|
||||
export const useSongStore = create<SongState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
allSongs: [],
|
||||
currentSong: null,
|
||||
queue: [],
|
||||
currentIndex: -1,
|
||||
isPlaying: false,
|
||||
position: 0,
|
||||
duration: 0,
|
||||
seekPosition: null,
|
||||
savedSongs: [],
|
||||
setSongs: (songs) => set({ allSongs: songs }),
|
||||
setCurrentSong: (song) => {
|
||||
if (!song) {
|
||||
set({ currentSong: null, position: 0 });
|
||||
return;
|
||||
}
|
||||
let queue = get().queue;
|
||||
let index = queue.findIndex(s => s.id === song.id);
|
||||
|
||||
if (index === -1) {
|
||||
queue = [...queue, song];
|
||||
index = queue.length - 1;
|
||||
}
|
||||
|
||||
set({
|
||||
currentSong: song,
|
||||
currentIndex: index,
|
||||
position: 0
|
||||
});
|
||||
},
|
||||
setIsPlaying: (playing) => set({ isPlaying: playing }),
|
||||
setPosition: (pos) => set({ position: pos }),
|
||||
setDuration: (dur) => set({ duration: dur }),
|
||||
setSeekPosition: (pos) => set({ seekPosition: pos }),
|
||||
toggleSave: (songId) => set((state) => ({
|
||||
savedSongs: state.savedSongs.includes(songId)
|
||||
? state.savedSongs.filter(id => id !== songId)
|
||||
: [...state.savedSongs, songId]
|
||||
})),
|
||||
addToQueue: (song) => set((state) => ({
|
||||
queue: [...state.queue, song]
|
||||
})),
|
||||
setQueue: (songs) => set({ queue: songs, currentIndex: -1 }),
|
||||
playNext: () => {
|
||||
const { queue, currentIndex } = get();
|
||||
if (currentIndex < queue.length - 1) {
|
||||
const nextSong = queue[currentIndex + 1];
|
||||
set({ currentSong: nextSong, currentIndex: currentIndex + 1 });
|
||||
}
|
||||
},
|
||||
playPrev: () => {
|
||||
const { queue, currentIndex } = get();
|
||||
if (currentIndex > 0) {
|
||||
const prevSong = queue[currentIndex - 1];
|
||||
set({ currentSong: prevSong, currentIndex: currentIndex - 1 });
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'song-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
const queue = get().queue;
|
||||
const index = queue.findIndex(s => s.id === song.id);
|
||||
set({
|
||||
currentSong: song,
|
||||
currentIndex: index !== -1 ? index : queue.length,
|
||||
position: 0
|
||||
});
|
||||
},
|
||||
setIsPlaying: (playing) => set({ isPlaying: playing }),
|
||||
setPosition: (pos) => set({ position: pos }),
|
||||
setDuration: (dur) => set({ duration: dur }),
|
||||
setSeekPosition: (pos) => set({ seekPosition: pos }),
|
||||
addToQueue: (song) => set((state) => ({
|
||||
queue: [...state.queue, song]
|
||||
})),
|
||||
setQueue: (songs) => set({ queue: songs, currentIndex: -1 }),
|
||||
playNext: () => {
|
||||
const { queue, currentIndex } = get();
|
||||
if (currentIndex < queue.length - 1) {
|
||||
const nextSong = queue[currentIndex + 1];
|
||||
set({ currentSong: nextSong, currentIndex: currentIndex + 1 });
|
||||
}
|
||||
},
|
||||
playPrev: () => {
|
||||
const { queue, currentIndex } = get();
|
||||
if (currentIndex > 0) {
|
||||
const prevSong = queue[currentIndex - 1];
|
||||
set({ currentSong: prevSong, currentIndex: currentIndex - 1 });
|
||||
}
|
||||
},
|
||||
}));
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user