Fix Expo Go compatibility (ExponentAV) and implement dynamic API URL
This commit is contained in:
@@ -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()
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
16
backend/check_users.py
Normal file
16
backend/check_users.py
Normal file
@@ -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()
|
||||
@@ -37,4 +37,4 @@ zipp==3.20.2
|
||||
psycopg2-binary
|
||||
email-validator
|
||||
python-multipart
|
||||
requests
|
||||
mutagen
|
||||
43
backend/temp_seed.py
Normal file
43
backend/temp_seed.py
Normal file
@@ -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()
|
||||
12
backend/test_login.py
Normal file
12
backend/test_login.py
Normal file
@@ -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}")
|
||||
46
backend/tests/seed_db.py
Normal file
46
backend/tests/seed_db.py
Normal file
@@ -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()
|
||||
104
backend/tests/test_comprehensive_e2e.py
Normal file
104
backend/tests/test_comprehensive_e2e.py
Normal file
@@ -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()
|
||||
19
backend/verify_pass.py
Normal file
19
backend/verify_pass.py
Normal file
@@ -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()
|
||||
@@ -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"]
|
||||
|
||||
20
frontend/package-lock.json
generated
20
frontend/package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 }
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 (
|
||||
<View style={styles.container}>
|
||||
@@ -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 (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.title}>{currentSong.title}</Text>
|
||||
@@ -111,7 +148,7 @@ export default function NowPlayingScreen({ navigation }) {
|
||||
<View style={styles.footerRow}>
|
||||
<TouchableOpacity
|
||||
style={styles.secondaryButton}
|
||||
onPress={() => Alert.alert('Playlist', 'Add to playlist feature coming soon!')}
|
||||
onPress={() => setIsModalVisible(true)}
|
||||
>
|
||||
<Text style={styles.secondaryText}>➕ Add to Playlist</Text>
|
||||
</TouchableOpacity>
|
||||
@@ -122,6 +159,48 @@ export default function NowPlayingScreen({ navigation }) {
|
||||
<Text style={styles.secondaryText}>📜 View Queue</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -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%' },
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ export default function UploadScreen({ navigation }) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [genre, setGenre] = useState('');
|
||||
const [file, setFile] = useState<DocumentPicker.DocumentPickerItem | null>(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 }) {
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<View style={{ marginTop: 20 }}>
|
||||
<Button title="Upload Song" onPress={handleUpload} />
|
||||
<Button title={uploading ? "Uploading..." : "Upload Song"} onPress={handleUpload} disabled={uploading} />
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
interface AuthState {
|
||||
user: any | null;
|
||||
@@ -8,17 +9,10 @@ interface AuthState {
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
setAuth: (user, token) => set({ user, token }),
|
||||
logout: () => set({ user: null, token: null }),
|
||||
}),
|
||||
{
|
||||
name: 'auth-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
)
|
||||
);
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
setAuth: (user, token) => set({ user, token }),
|
||||
logout: () => set({ user: null, token: null }),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware/persist';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
interface Song {
|
||||
id: number;
|
||||
@@ -34,9 +35,7 @@ interface SongState {
|
||||
playPrev: () => void;
|
||||
}
|
||||
|
||||
export const useSongStore = create<SongState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
export const useSongStore = create<SongState>((set, get) => ({
|
||||
allSongs: [],
|
||||
currentSong: null,
|
||||
queue: [],
|
||||
@@ -61,6 +60,7 @@ export const useSongStore = create<SongState>()(
|
||||
}
|
||||
|
||||
set({
|
||||
queue: queue,
|
||||
currentSong: song,
|
||||
currentIndex: index,
|
||||
position: 0
|
||||
@@ -93,10 +93,4 @@ export const useSongStore = create<SongState>()(
|
||||
set({ currentSong: prevSong, currentIndex: currentIndex - 1 });
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'song-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
)
|
||||
);
|
||||
}));
|
||||
Reference in New Issue
Block a user