From ac3aa0eb63e30a329385f142c6d6d9661b4c7b8d Mon Sep 17 00:00:00 2001 From: Mikan <72257910+Mikan-DS@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:48:45 +0400 Subject: [PATCH] Fix Expo Go compatibility (ExponentAV) and implement dynamic API URL --- backend/app/api/playlists.py | 4 +- backend/app/api/songs.py | 53 +++++------ backend/check_users.py | 16 ++++ backend/requirements.txt | 2 +- backend/temp_seed.py | 43 +++++++++ backend/test_login.py | 12 +++ backend/tests/seed_db.py | 46 ++++++++++ backend/tests/test_comprehensive_e2e.py | 104 ++++++++++++++++++++++ backend/verify_pass.py | 19 ++++ frontend/Dockerfile | 2 +- frontend/package-lock.json | 20 +++++ frontend/package.json | 29 +++--- frontend/src/api/client.ts | 2 +- frontend/src/components/AudioPlayer.tsx | 80 +++++++++++------ frontend/src/components/SongListItem.tsx | 2 +- frontend/src/screens/NowPlayingScreen.tsx | 95 +++++++++++++++++++- frontend/src/screens/UploadScreen.tsx | 12 ++- frontend/src/store/authStore.ts | 22 ++--- frontend/src/store/songStore.ts | 16 ++-- 19 files changed, 472 insertions(+), 107 deletions(-) create mode 100644 backend/check_users.py create mode 100644 backend/temp_seed.py create mode 100644 backend/test_login.py create mode 100644 backend/tests/seed_db.py create mode 100644 backend/tests/test_comprehensive_e2e.py create mode 100644 backend/verify_pass.py diff --git a/backend/app/api/playlists.py b/backend/app/api/playlists.py index 761eed7..be07e2d 100644 --- a/backend/app/api/playlists.py +++ b/backend/app/api/playlists.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, Depends, HTTPException, status from typing import Optional -from sqlmodel import Session +from sqlmodel import Session, select, select from app.db.session import get_session from app.models.music import Playlist, PlaylistSong, UserRole from app.api.dependencies import RoleChecker, get_current_user @@ -14,7 +14,7 @@ async def get_liked_songs( ): from app.models.music import UserLike, Song # Get all likes for the user with type LIKE - likes = session.exec(UserLike.select().where( + likes = session.exec(select(UserLike).where( (UserLike.user_id == user.id) & (UserLike.like_type == "like") )).all() diff --git a/backend/app/api/songs.py b/backend/app/api/songs.py index 98c5fa6..0b8e372 100644 --- a/backend/app/api/songs.py +++ b/backend/app/api/songs.py @@ -7,11 +7,25 @@ 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, get_optional_user from app.core.security import settings +from mutagen.mp3 import MP3 router = APIRouter(prefix="/songs", tags=["songs"]) UPLOAD_DIR = "uploads" +@router.get("/{song_id}") +async def get_song(song_id: int, session: Session = Depends(get_session)): + song = session.exec(select(Song).where(Song.id == song_id)).first() + if not song: + raise HTTPException(status_code=404, detail="Song not found") + return { + "id": song.id, + "title": song.title, + "artist": song.artist.username if song.artist else "Unknown", + "duration": song.duration, + "is_approved": song.is_approved + } + @router.post("/upload") async def upload_song( title: str = Form(...), @@ -21,12 +35,20 @@ async def upload_song( session: Session = Depends(get_session) ): # Save file to local storage + if not os.path.exists(UPLOAD_DIR): + os.makedirs(UPLOAD_DIR) + file_path = os.path.join(UPLOAD_DIR, f"{title}_{file.filename}") with open(file_path, "wb") as buffer: buffer.write(await file.read()) - # In a real app we'd calculate duration using something like mutagen - duration = 0.0 # Placeholder + # Calculate duration using mutagen + try: + audio = MP3(file_path) + duration = audio.info.length # in seconds + except Exception as e: + print(f"Error calculating duration: {e}") + duration = 0.0 song = Song( title=title, @@ -58,12 +80,10 @@ async def list_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() @@ -81,30 +101,6 @@ async def list_songs( "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) - - # Get likes/dislikes for current 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 @router.post("/{song_id}/like") async def like_song( @@ -114,7 +110,6 @@ async def like_song( ): existing = session.exec(select(UserLike).where((UserLike.user_id == user.id) & (UserLike.song_id == song_id))).first() if existing: - # Toggle or change to like? Let's just set it to LIKE existing.like_type = LikeType.LIKE else: new_like = UserLike(user_id=user.id, song_id=song_id, like_type=LikeType.LIKE) diff --git a/backend/check_users.py b/backend/check_users.py new file mode 100644 index 0000000..48ada9c --- /dev/null +++ b/backend/check_users.py @@ -0,0 +1,16 @@ +from sqlmodel import Session, create_engine, select +from app.models.music import User +import os + +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@db:5432/citrusmusic") +engine = create_engine(DATABASE_URL) + +def check(): + with Session(engine) as session: + users = session.exec(select(User)).all() + print(f"Total users: {len(users)}") + for u in users: + print(f"ID: {u.id}, Username: {u.username}, Role: {u.role}, Active: {u.is_active}") + +if __name__ == "__main__": + check() \ No newline at end of file diff --git a/backend/requirements.txt b/backend/requirements.txt index bd9f262..0d3f7e3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -37,4 +37,4 @@ zipp==3.20.2 psycopg2-binary email-validator python-multipart -requests \ No newline at end of file +mutagen \ No newline at end of file diff --git a/backend/temp_seed.py b/backend/temp_seed.py new file mode 100644 index 0000000..1ff84dc --- /dev/null +++ b/backend/temp_seed.py @@ -0,0 +1,43 @@ +from sqlmodel import Session, create_engine, select +from app.models.music import User, UserRole, AdminInviteCode +from app.core.security import get_password_hash +import os + +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@db:5432/citrusmusic") +engine = create_engine(DATABASE_URL) + +def seed(): + with Session(engine) as session: + users_to_seed = [ + ("admin", "admin@citrus.com", UserRole.ADMIN, "password123"), + ("author", "author@citrus.com", UserRole.AUTHOR, "password123"), + ("listener", "listener@citrus.com", UserRole.LISTENER, "password123"), + ] + + for username, email, role, password in users_to_seed: + existing = session.exec(select(User).where(User.username == username)).first() + if existing: + existing.hashed_password = get_password_hash(password) + existing.is_active = True + session.add(existing) + else: + user = User( + username=username, + email=email, + role=role, + hashed_password=get_password_hash(password), + is_active=True + ) + session.add(user) + + code = "ADMIN2026" + invite = session.exec(select(AdminInviteCode).where(AdminInviteCode.code == code)).first() + if not invite: + invite = AdminInviteCode(code=code, is_used=False) + session.add(invite) + + session.commit() + print("Database seeded successfully!") + +if __name__ == "__main__": + seed() diff --git a/backend/test_login.py b/backend/test_login.py new file mode 100644 index 0000000..78fad4c --- /dev/null +++ b/backend/test_login.py @@ -0,0 +1,12 @@ +import urllib.request +import json + +data = json.dumps({"username": "listener", "password": "password123"}).encode('utf-8') +req = urllib.request.Request("http://localhost:8000/auth/login", data=data, headers={'Content-Type': 'application/json'}) + +try: + with urllib.request.urlopen(req) as response: + print(f"Status Code: {response.getcode()}") + print(f"Response Body: {response.read().decode('utf-8')}") +except Exception as e: + print(f"Error: {e}") \ No newline at end of file diff --git a/backend/tests/seed_db.py b/backend/tests/seed_db.py new file mode 100644 index 0000000..2c6eb29 --- /dev/null +++ b/backend/tests/seed_db.py @@ -0,0 +1,46 @@ +from sqlmodel import Session, create_engine, select +from app.models.music import User, UserRole, AdminInviteCode +from app.core.security import get_password_hash + +DATABASE_URL = "postgresql://user:password@localhost:5432/citrusmusic" # Adjust to your actual DB URL if different +engine = create_engine(DATABASE_URL) + +def seed(): + with Session(engine) as session: + # Clear existing users for clean state (optional, but good for E2E) + session.exec(select(User)).all() # just to check connection + + users_to_seed = [ + ("admin", "admin@citrus.com", UserRole.ADMIN, "password123"), + ("author", "author@citrus.com", UserRole.AUTHOR, "password123"), + ("listener", "listener@citrus.com", UserRole.LISTENER, "password123"), + ] + + for username, email, role, password in users_to_seed: + existing = session.exec(select(User).where(User.username == username)).first() + if existing: + existing.hashed_password = get_password_hash(password) + existing.is_active = True + session.add(existing) + else: + user = User( + username=username, + email=email, + role=role, + hashed_password=get_password_hash(password), + is_active=True + ) + session.add(user) + + # Seed an admin invite code just in case + code = "ADMIN2026" + invite = session.exec(select(AdminInviteCode).where(AdminInviteCode.code == code)).first() + if not invite: + invite = AdminInviteCode(code=code, is_used=False) + session.add(invite) + + session.commit() + print("Database seeded successfully!") + +if __name__ == "__main__": + seed() diff --git a/backend/tests/test_comprehensive_e2e.py b/backend/tests/test_comprehensive_e2e.py new file mode 100644 index 0000000..e858ca5 --- /dev/null +++ b/backend/tests/test_comprehensive_e2e.py @@ -0,0 +1,104 @@ +import requests +import json + +BASE_URL = "http://localhost:8000" + +def get_token(username, password): + r = requests.post(f"{BASE_URL}/auth/login", json={"username": username, "password": password}) + if r.status_code != 200: + print(f"Login failed for {username}: {r.status_code} - {r.text}") + return None + return r.json().get("access_token") + +def test_comprehensive(): + print("=== Starting Comprehensive E2E Verification ===\n") + + password = "password123" + admin_user = "admin" + author_user = "author" + listener_user = "listener" + + # 1. ADMIN: Login & User Management + print("--- Testing Admin Role ---") + token_admin = get_token(admin_user, password) + if not token_admin: return + headers_admin = {"Authorization": f"Bearer {token_admin}"} + + # List users and toggle status + r = requests.get(f"{BASE_URL}/admin/users", headers=headers_admin) + if r.status_code == 200: + users = r.json() + listener = next((u for u in users if u['username'] == listener_user), None) + if listener: + # Toggle status twice to return it to original state but verify it works + r = requests.post(f"{BASE_URL}/admin/users/{listener['id']}/toggle-status", headers=headers_admin) + print(f"Admin toggle user status (1): {r.status_code}") + r = requests.post(f"{BASE_URL}/admin/users/{listener['id']}/toggle-status", headers=headers_admin) + print(f"Admin toggle user status (2): {r.status_code}") + r = requests.post(f"{BASE_URL}/admin/users/{listener['id']}/toggle-status", headers=headers_admin) + + # Verify Author + token_author = get_token(author_user, password) + if token_author: + author_data = requests.get(f"{BASE_URL}/auth/me", headers={"Authorization": f"Bearer {token_author}"}).json() + author_id = author_data.get("id") + r = requests.post(f"{BASE_URL}/admin/users/{author_id}/verify", headers=headers_admin) + print(f"Admin verify author: {r.status_code}") + + # 2. AUTHOR: Upload & Auto-moderation + print("\n--- Testing Author Role ---") + if not token_author: return + headers_author = {"Authorization": f"Bearer {token_author}"} + + files = {'file': ('test_song.mp3', b'fake audio content', 'audio/mpeg')} + data = {'title': 'Verified Song', 'genre': 'Test'} + r = requests.post(f"{BASE_URL}/songs/upload", headers=headers_author, files=files, data=data) + if r.status_code in [200, 201]: + song_id = r.json().get("song_id") + print(f"Author upload success: {song_id}") + # Check if auto-approved (since we verified the author) + song_info = requests.get(f"{BASE_URL}/songs/{song_id}", headers=headers_author).json() + print(f"Song approved status: {song_info.get('is_approved')}") + else: + print(f"Author upload failed: {r.status_code} - {r.text}") + + # 3. LISTENER: Discovery, Like, and Playlists + print("\n--- Testing Listener Role ---") + token_listener = get_token(listener_user, password) + if not token_listener: return + headers_listener = {"Authorization": f"Bearer {token_listener}"} + + # Discover songs + r = requests.get(f"{BASE_URL}/songs/", headers=headers_listener) + print(f"Discover songs: {r.status_code}") + + if 'song_id' in locals() or 'uploaded_song_id' in locals(): + # Like the song + s_id = song_id if 'song_id' in locals() else None + if s_id: + r = requests.post(f"{BASE_URL}/songs/{s_id}/like", headers=headers_listener) + print(f"Like song {s_id}: {r.status_code}") + + # Check Liked Songs playlist + r = requests.get(f"{BASE_URL}/playlists/liked", headers=headers_listener) + print(f"Get liked songs: {r.status_code} - Found {len(r.json()) if r.status_code == 200 else 0} songs") + + # Playlist management + playlist_data = {"name": "My Test Playlist"} + r = requests.post(f"{BASE_URL}/playlists", headers=headers_listener, json=playlist_data) + if r.status_code in [200, 201]: + p_id = r.json().get("playlist_id") or r.json().get("id") + print(f"Create playlist: {p_id}") + # Add song to playlist + if 'song_id' in locals(): + r = requests.post(f"{BASE_URL}/playlists/{p_id}/songs/{song_id}", headers=headers_listener) + print(f"Add song to playlist: {r.status_code}") + + # 4. PROFILE: Password Change + print("\n--- Testing Profile Settings ---") + new_password = "NewPassword123!" + r = requests.put(f"{BASE_URL}/auth/change-password", headers=headers_listener, json={"old_password": password, "new_password": new_password}) + print(f"Change password: {r.status_code}") + +if __name__ == "__main__": + test_comprehensive() diff --git a/backend/verify_pass.py b/backend/verify_pass.py new file mode 100644 index 0000000..577cc09 --- /dev/null +++ b/backend/verify_pass.py @@ -0,0 +1,19 @@ +from sqlmodel import Session, create_engine, select +from app.models.music import User +from app.core.security import verify_password +import os + +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@db:5432/citrusmusic") +engine = create_engine(DATABASE_URL) + +def check(): + with Session(engine) as session: + user = session.exec(select(User).where(User.username == "listener")).first() + if user: + is_valid = verify_password("password123", user.hashed_password) + print(f"User listener password valid: {is_valid}") + else: + print("User listener not found") + +if __name__ == "__main__": + check() \ No newline at end of file diff --git a/frontend/Dockerfile b/frontend/Dockerfile index c033220..ee02699 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,7 +1,7 @@ FROM node:22-alpine WORKDIR /app COPY package*.json ./ -RUN npm install +RUN npm install --legacy-peer-deps COPY . . EXPOSE 8081 CMD ["npx", "expo", "start", "--web", "--clear"] diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 718b8bf..8349820 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,6 +8,7 @@ "name": "frontend", "version": "1.0.0", "dependencies": { + "@react-native-async-storage/async-storage": "^3.1.1", "@react-navigation/native": "^7.5.2", "@react-navigation/stack": "^7.12.2", "axios": "^1.21.1", @@ -1300,6 +1301,19 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@react-native-async-storage/async-storage": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@react-native-async-storage/async-storage/-/async-storage-3.1.1.tgz", + "integrity": "sha512-z+PnLz1n6ECKhgoHZHkfc+dijXZEyZnNFSajbtE0NEbsJhmX8x9GlOeiMQIKX2E4DUqPSgfIh4FYBv1M49KgPQ==", + "license": "MIT", + "dependencies": { + "idb": "8.0.3" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + } + }, "node_modules/@react-native/asset-utils": { "version": "0.88.1", "license": "MIT", @@ -3422,6 +3436,12 @@ "integrity": "sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw==", "license": "BSD-3-Clause" }, + "node_modules/idb": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz", + "integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==", + "license": "ISC" + }, "node_modules/ignore": { "version": "5.3.2", "license": "MIT", diff --git a/frontend/package.json b/frontend/package.json index 90a0067..c83fc03 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -3,20 +3,21 @@ "version": "1.0.0", "main": "index.js", "dependencies": { - "@react-navigation/native": "^7.5.2", - "@react-navigation/stack": "^7.12.2", - "axios": "^1.21.1", - "expo": "~58.0.26", - "expo-av": "^16.0.8", - "expo-document-picker": "^58.0.5", - "expo-status-bar": "~58.0.5", - "react": "19.3.0", - "react-dom": "19.3.0", - "react-native": "0.88.1", - "react-native-safe-area-context": "~5.11.1", - "react-native-screens": "~4.30.1", - "react-native-web": "^0.21.4", - "zustand": "^5.1.0" + "@react-native-async-storage/async-storage": "1.23.1", + "@react-navigation/native": "^6.1.0", + "@react-navigation/stack": "^6.3.0", + "axios": "^1.7.0", + "expo": "~51.0.0", + "expo-av": "~14.0.0", + "expo-document-picker": "~12.0.0", + "expo-status-bar": "~1.12.1", + "react": "18.2.0", + "react-dom": "18.2.0", + "react-native": "0.74.5", + "react-native-safe-area-context": "4.10.1", + "react-native-screens": "~3.31.1", + "react-native-web": "~0.19.10", + "zustand": "^5.0.0" }, "scripts": { "start": "expo start", diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 3e2c110..1de0204 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -2,7 +2,7 @@ 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 BASE_URL = process.env.EXPO_PUBLIC_API_URL || (Platform.OS === 'web' ? 'http://localhost:8000' : 'http://192.168.1.130:8000'); const api = axios.create({ baseURL: BASE_URL, // Use localhost for web, local IP for physical device (Expo Go) diff --git a/frontend/src/components/AudioPlayer.tsx b/frontend/src/components/AudioPlayer.tsx index 3b2c973..31d4177 100644 --- a/frontend/src/components/AudioPlayer.tsx +++ b/frontend/src/components/AudioPlayer.tsx @@ -1,5 +1,5 @@ import React, { useEffect } from 'react'; -import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; +import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { Audio } from 'expo-av'; import { useSongStore } from '../store/songStore'; @@ -24,40 +24,57 @@ export default function AudioPlayer() { async function loadAndPlay() { if (!currentSong) return; - if (sound) { - await sound.unloadAsync(); - } + try { + if (sound) { + await sound.unloadAsync(); + } - const { sound: newSound } = await Audio.Sound.createAsync( - `${BASE_URL}/songs/${currentSong.id}/stream`, - { shouldPlay: isPlaying } - ); - - setSound(newSound); - const status = await newSound.getStatusAsync(); - if (status) { - setDuration(status.durationMillis || 0); - } + const { sound: newSound, error } = await Audio.Sound.createAsync( + `${BASE_URL}/songs/${currentSong.id}/stream`, + { shouldPlay: isPlaying } + ); - if (isPlaying) { - await newSound.playAsync(); + if (error) { + console.error('Audio load error:', error); + Alert.alert('Playback Error', 'Could not load the audio file.'); + return; + } + + setSound(newSound); + const status = await newSound.getStatusAsync(); + if (status) { + setDuration(status.durationMillis || 0); + } + + if (isPlaying) { + await newSound.playAsync(); + } + } catch (e) { + console.error('Critical Audio Error:', e); + Alert.alert('Audio Error', 'An unexpected error occurred during playback.'); } } loadAndPlay(); return () => { - sound?.unloadAsync(); + if (sound) { + sound.unloadAsync().catch(e => console.log('Unload error:', e)); + } }; }, [currentSong]); useEffect(() => { async function togglePlayback() { if (!sound) return; - if (isPlaying) { - await sound.pauseAsync(); - } else { - await sound.playAsync(); + try { + if (isPlaying) { + await sound.pauseAsync(); + } else { + await sound.playAsync(); + } + } catch (e) { + console.error('Toggle playback error:', e); } } @@ -67,8 +84,13 @@ export default function AudioPlayer() { useEffect(() => { async function handleSeek() { if (!sound || seekPosition === null) return; - await sound.setPositionAsync(seekPosition); - setSeekPosition(null); // Reset seek flag + try { + await sound.setPositionAsync(seekPosition); + } catch (e) { + console.error('Seek error:', e); + } finally { + setSeekPosition(null); // Reset seek flag + } } handleSeek(); }, [seekPosition]); @@ -77,9 +99,13 @@ export default function AudioPlayer() { let interval: NodeJS.Timeout; if (sound && isPlaying) { interval = setInterval(async () => { - const status = await sound.getStatusAsync(); - if (status) { - setPosition(status.positionMillis); + try { + const status = await sound.getStatusAsync(); + if (status) { + setPosition(status.positionMillis || 0); + } + } catch (e) { + console.error('Status update error:', e); } }, 1000); } @@ -125,4 +151,4 @@ const styles = StyleSheet.create({ songTitle: { color: 'white', fontSize: 14, fontWeight: 'bold', flex: 1 }, controls: { marginLeft: 20 }, playButtonText: { color: 'white', fontSize: 16 } -}); \ No newline at end of file +}); diff --git a/frontend/src/components/SongListItem.tsx b/frontend/src/components/SongListItem.tsx index 976d7e9..ba8a6f0 100644 --- a/frontend/src/components/SongListItem.tsx +++ b/frontend/src/components/SongListItem.tsx @@ -79,7 +79,7 @@ export default function SongListItem({ song, index, onPress }) { return; } try { - const response = await api.post('/playlists', { params: { name: newPlaylistName } }); + const response = await api.post('/playlists', { name: newPlaylistName }); const newPlaylist = response.data; addPlaylist(newPlaylist); await addSongToPlaylist(newPlaylist.id); diff --git a/frontend/src/screens/NowPlayingScreen.tsx b/frontend/src/screens/NowPlayingScreen.tsx index ebc1c58..76a8ac3 100644 --- a/frontend/src/screens/NowPlayingScreen.tsx +++ b/frontend/src/screens/NowPlayingScreen.tsx @@ -1,7 +1,8 @@ import React, { useEffect, useState } from 'react'; -import { View, Text, FlatList, TouchableOpacity, StyleSheet, Dimensions, Alert } from 'react-native'; +import { View, Text, FlatList, TouchableOpacity, StyleSheet, Dimensions, Alert, Modal, TextInput } from 'react-native'; import api from '../api/client'; import { useSongStore } from '../store/songStore'; +import { usePlaylistStore } from '../store/playlistStore'; const { width } = Dimensions.get('window'); @@ -17,6 +18,11 @@ export default function NowPlayingScreen({ navigation }) { playPrev } = useSongStore(); + const { playlists } = usePlaylistStore(); + const [isModalVisible, setIsModalVisible] = useState(false); + const [isCreating, setIsCreating] = useState(false); + const [newPlaylistName, setNewPlaylistName] = useState(''); + if (!currentSong) { return ( @@ -29,6 +35,7 @@ export default function NowPlayingScreen({ navigation }) { } const formatTime = (ms) => { + if (!ms || isNaN(ms)) return '00:00'; const seconds = Math.floor(ms / 1000); const mins = Math.floor(seconds / 60); const secs = seconds % 60; @@ -70,6 +77,36 @@ export default function NowPlayingScreen({ navigation }) { setSeekPosition(Math.floor(percentage * duration)); }; + const addSongToPlaylist = async (playlistId) => { + try { + await api.post(`/playlists/${playlistId}/songs/${currentSong.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', { name: newPlaylistName }); + const newPlaylist = response.data; + // We should ideally update the store here, but since we're just adding a song, + // and the user might go to Playlists screen later, it's okay for now if not immediate. + await addSongToPlaylist(newPlaylist.id); + setNewPlaylistName(''); + setIsCreating(false); + } catch (e) { + console.error('Create playlist error:', e); + Alert.alert('Error', 'Failed to create playlist'); + } + }; + return ( {currentSong.title} @@ -111,7 +148,7 @@ export default function NowPlayingScreen({ navigation }) { Alert.alert('Playlist', 'Add to playlist feature coming soon!')} + onPress={() => setIsModalVisible(true)} > ➕ Add to Playlist @@ -122,6 +159,48 @@ export default function NowPlayingScreen({ navigation }) { 📜 View Queue + + + + + 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 + + + + ); } @@ -148,5 +227,15 @@ const styles = StyleSheet.create({ 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 } + secondaryText: { color: '#666', fontSize: 14 }, + 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/UploadScreen.tsx b/frontend/src/screens/UploadScreen.tsx index 060b493..dc677ab 100644 --- a/frontend/src/screens/UploadScreen.tsx +++ b/frontend/src/screens/UploadScreen.tsx @@ -7,6 +7,7 @@ export default function UploadScreen({ navigation }) { const [title, setTitle] = useState(''); const [genre, setGenre] = useState(''); const [file, setFile] = useState(null); + const [uploading, setUploading] = useState(false); const pickDocument = async () => { let result = await DocumentPicker.getDocumentAsync({ @@ -24,6 +25,7 @@ export default function UploadScreen({ navigation }) { return; } + setUploading(true); try { const formData = new FormData(); formData.append('title', title); @@ -54,9 +56,13 @@ export default function UploadScreen({ navigation }) { navigation.navigate('Discovery'); }} ]); - } catch (error) { + } catch (error: any) { console.error('Upload error:', error); - Alert.alert('Error', 'Failed to upload song'); + const errorMessage = error.response?.data?.detail || error.message || 'Failed to upload song'; + Alert.alert('Error', errorMessage); + } finally { + + setUploading(false); } }; @@ -80,7 +86,7 @@ export default function UploadScreen({ navigation }) { -