From 863b3dfb5bea258fbffb74058b38b2116485a29e Mon Sep 17 00:00:00 2001 From: Mikan <72257910+Mikan-DS@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:46:45 +0400 Subject: [PATCH] \Fix navigation stack behavior and update tests" --- backend/app/api/admin.py | 12 +- backend/app/api/auth.py | 3 + backend/app/api/dependencies.py | 21 +- backend/app/api/playlists.py | 23 ++ backend/app/api/songs.py | 31 +- backend/app/models/music.py | 1 + backend/tests/test_admin.py | 23 +- backend/tests/test_all_e2e.py | 107 +++++++ docker-compose.yml | 12 + frontend/Dockerfile | 7 + frontend/src/api/client.ts | 5 +- frontend/src/components/AudioPlayer.tsx | 3 +- frontend/src/components/SongListItem.tsx | 268 ++++++++++++++++++ frontend/src/screens/CreatePlaylistScreen.tsx | 9 +- frontend/src/screens/DiscoveryScreen.tsx | 82 +----- frontend/src/screens/NowPlayingScreen.tsx | 36 ++- frontend/src/screens/PlaylistDetailScreen.tsx | 42 +-- frontend/src/screens/PlaylistsScreen.tsx | 41 ++- frontend/src/screens/QueueScreen.tsx | 45 +-- frontend/src/screens/RegisterScreen.tsx | 36 ++- frontend/src/screens/UploadScreen.tsx | 13 +- frontend/src/store/songStore.ts | 113 +++++--- 22 files changed, 700 insertions(+), 233 deletions(-) create mode 100644 backend/tests/test_all_e2e.py create mode 100644 frontend/Dockerfile create mode 100644 frontend/src/components/SongListItem.tsx diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index b8621e8..97dc061 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -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( diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py index 2dc66d6..ded81ef 100644 --- a/backend/app/api/auth.py +++ b/backend/app/api/auth.py @@ -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") diff --git a/backend/app/api/dependencies.py b/backend/app/api/dependencies.py index 1b1b2c6..86b3032 100644 --- a/backend/app/api/dependencies.py +++ b/backend/app/api/dependencies.py @@ -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 diff --git a/backend/app/api/playlists.py b/backend/app/api/playlists.py index 11100d8..761eed7 100644 --- a/backend/app/api/playlists.py +++ b/backend/app/api/playlists.py @@ -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, diff --git a/backend/app/api/songs.py b/backend/app/api/songs.py index df05472..98c5fa6 100644 --- a/backend/app/api/songs.py +++ b/backend/app/api/songs.py @@ -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) diff --git a/backend/app/models/music.py b/backend/app/models/music.py index 52f06e1..be78f98 100644 --- a/backend/app/models/music.py +++ b/backend/app/models/music.py @@ -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"}) diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index fba8ba2..dfd00f4 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -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(): diff --git a/backend/tests/test_all_e2e.py b/backend/tests/test_all_e2e.py new file mode 100644 index 0000000..05f06a5 --- /dev/null +++ b/backend/tests/test_all_e2e.py @@ -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() diff --git a/docker-compose.yml b/docker-compose.yml index 2a0af33..8af6884 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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: diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..c033220 --- /dev/null +++ b/frontend/Dockerfile @@ -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"] diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index c55e9b4..3e2c110 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -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; diff --git a/frontend/src/components/AudioPlayer.tsx b/frontend/src/components/AudioPlayer.tsx index b1a6eb1..3b2c973 100644 --- a/frontend/src/components/AudioPlayer.tsx +++ b/frontend/src/components/AudioPlayer.tsx @@ -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 } ); diff --git a/frontend/src/components/SongListItem.tsx b/frontend/src/components/SongListItem.tsx new file mode 100644 index 0000000..976d7e9 --- /dev/null +++ b/frontend/src/components/SongListItem.tsx @@ -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 ( + + onPress(song)}> + + {index + 1}. {song.title} + — {song.artist} + {formatTime(song.duration)} + + + + + {song.likeType === 'like' ? '❤️' : '♡'} + + + + + + + ■ + + + + + + + + Add to Playlist + {isCreating ? ( + + + + Confirm + + setIsCreating(false)}> + Cancel + + + ) : ( + <> + item.id.toString()} + renderItem={({ item }) => ( + addSongToPlaylist(item.id)}> + {item.name} + + )} + /> + setIsCreating(true)}> + + Create New Playlist + + + )}> + setIsModalVisible(false)}> + Cancel + + + + + + ); +} + +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%', + } +}); diff --git a/frontend/src/screens/CreatePlaylistScreen.tsx b/frontend/src/screens/CreatePlaylistScreen.tsx index f3b096b..1bc3e56 100644 --- a/frontend/src/screens/CreatePlaylistScreen.tsx +++ b/frontend/src/screens/CreatePlaylistScreen.tsx @@ -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'); } diff --git a/frontend/src/screens/DiscoveryScreen.tsx b/frontend/src/screens/DiscoveryScreen.tsx index c55cfca..d5fa471 100644 --- a/frontend/src/screens/DiscoveryScreen.tsx +++ b/frontend/src/screens/DiscoveryScreen.tsx @@ -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 ( - setCurrentSong(item)}> - - {item.title} - {item.artist} - - - handleLikeAction('like')} style={{ marginRight: 10 }}> - ❤️ - - handleLikeAction('dislike')} style={{ marginRight: 10 }}> - 👎 - - - 💾 - - - setCurrentSong(item)}> - Play - - - ); - }; - return ( @@ -113,7 +57,9 @@ export default function DiscoveryScreen({ navigation }) { item.id.toString()} - renderItem={renderItem} + renderItem={({ item, index }) => ( + setCurrentSong(item)} /> + )} ListEmptyComponent={No songs found.} /> @@ -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' } }); \ No newline at end of file diff --git a/frontend/src/screens/NowPlayingScreen.tsx b/frontend/src/screens/NowPlayingScreen.tsx index 5e286a7..ebc1c58 100644 --- a/frontend/src/screens/NowPlayingScreen.tsx +++ b/frontend/src/screens/NowPlayingScreen.tsx @@ -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 }) { - {formatTime(position)} - {formatTime(duration)} + {formatTime(position)} / {formatTime(duration)} @@ -84,6 +103,9 @@ export default function NowPlayingScreen({ navigation }) { handleLikeAction('dislike')} style={styles.actionButton}> 👎 Dislike + + 💾 Save + @@ -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 } -}); \ No newline at end of file +}); diff --git a/frontend/src/screens/PlaylistDetailScreen.tsx b/frontend/src/screens/PlaylistDetailScreen.tsx index 132e9da..b2ba5f7 100644 --- a/frontend/src/screens/PlaylistDetailScreen.tsx +++ b/frontend/src/screens/PlaylistDetailScreen.tsx @@ -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 }) => ( - - {item.title} - {item.artist} - removeSong(item.id)}> - Remove - - - ); - - 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 ( index.toString()} - renderItem={renderItem} + keyExtractor={(item, index) => (item.id || index).toString()} + renderItem={({ item, index }) => ( + setCurrentSong(item)} /> + )} ListEmptyComponent={This playlist is empty.} /> @@ -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' } }); diff --git a/frontend/src/screens/PlaylistsScreen.tsx b/frontend/src/screens/PlaylistsScreen.tsx index 165c034..6f4600d 100644 --- a/frontend/src/screens/PlaylistsScreen.tsx +++ b/frontend/src/screens/PlaylistsScreen.tsx @@ -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={No playlists yet.} + ListHeaderComponent={() => ( + <> + {hasLikedSongs && ( + navigation.navigate('PlaylistDetail', { playlistId: 'liked' })} + > + ❤️ Liked Songs + All your liked tracks + + )} + {savedSongs.length > 0 && ( + navigation.navigate('PlaylistDetail', { playlistId: 'saved' })} + > + 💾 Saved Songs + Downloaded for offline use + + )} + + )} + ListEmptyComponent={playlists.length === 0 && !hasLikedSongs && savedSongs.length === 0 ? ( + No playlists yet. + ) : null} /> ( - setCurrentSong(item)} - > - - {item.title} - {item.artist} - - {index === currentIndex && Now Playing} - - ); - return ( Up Next item.id.toString()} - renderItem={renderItem} + renderItem={({ item, index }) => ( + + setCurrentSong(item)} + /> + {index === currentIndex && Now Playing} + + )} ListEmptyComponent={Queue is empty.} /> @@ -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' } }); \ No newline at end of file diff --git a/frontend/src/screens/RegisterScreen.tsx b/frontend/src/screens/RegisterScreen.tsx index 353e8e7..62c05c3 100644 --- a/frontend/src/screens/RegisterScreen.tsx +++ b/frontend/src/screens/RegisterScreen.tsx @@ -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 }) { Create Account setIsAuthor(false)} + disabled={isLoading} > Listener setIsAuthor(true)} + disabled={isLoading} > Author - -