Compare commits

3 Commits
main ... master

36 changed files with 1259 additions and 324 deletions

View File

@@ -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(

View File

@@ -77,7 +77,10 @@ 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")
return {"access_token": create_access_token({"sub": user.username}), "token_type": "bearer"}
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")
async def change_password(data: PasswordChange, user=Depends(get_current_user), session: Session = Depends(get_session)):

View File

@@ -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

View File

@@ -1,12 +1,35 @@
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
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(select(UserLike).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,

View File

@@ -5,13 +5,27 @@ 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
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,
@@ -52,19 +74,20 @@ 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
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}
if user:
unapproved_own = session.exec(select(Song).where((Song.artist_id == user.id) & (Song.is_approved == False))).all()
songs.extend(unapproved_own)
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:
@@ -87,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)

View File

@@ -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"})

16
backend/check_users.py Normal file
View 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()

View File

@@ -37,4 +37,4 @@ zipp==3.20.2
psycopg2-binary
email-validator
python-multipart
requests
mutagen

43
backend/temp_seed.py Normal file
View 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
View 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
View 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()

View File

@@ -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():

View File

@@ -0,0 +1,107 @@
import requests
import json
BASE_URL = "http://localhost:8000"
def test_flow():
print("--- Starting Full System Test Flow ---")
uploaded_song_id = None
listener_username = "listener"
author_username = "author"
admin_username = "admin"
password = "password123"
# 1. Author Flow: Upload a song
print("\n--- Testing Author Flow ---")
login_author = {"username": author_username, "password": password}
r = requests.post(f"{BASE_URL}/auth/login", json=login_author)
if r.status_code != 200:
print(f"Author Login failed: {r.status_code} - {r.text}")
return
token_author = r.json().get("access_token")
headers_author = {"Authorization": f"Bearer {token_author}"}
# Upload a song
files = {'file': ('test_song.mp3', b'fake audio content', 'audio/mpeg')}
data = {'title': 'E2E Test Song', 'genre': 'Pop'}
r = requests.post(f"{BASE_URL}/songs/upload", headers=headers_author, files=files, data=data)
print(f"Upload: {r.status_code} - {r.text}")
if r.status_code == 200 or r.status_code == 201:
try:
uploaded_song_id = r.json().get("song_id")
print(f"Uploaded Song ID: {uploaded_song_id}")
except Exception as e:
print(f"Failed to get song id from response: {e}")
# 2. Admin Flow: Approve the uploaded song AND ensure listener is active
print("\n--- Testing Admin Moderation & User Mgmt ---")
login_admin = {"username": admin_username, "password": password}
r = requests.post(f"{BASE_URL}/auth/login", json=login_admin)
if r.status_code != 200:
print(f"Admin Login failed: {r.status_code} - {r.text}")
return
token_admin = r.json().get("access_token")
headers_admin = {"Authorization": f"Bearer {token_admin}"}
# Activate listener if deactivated
r = requests.get(f"{BASE_URL}/admin/users", headers=headers_admin)
if r.status_code == 200:
users = r.json()
target_user = next((u for u in users if u['username'] == listener_username), None)
if target_user and not target_user['is_active']:
r = requests.post(f"{BASE_URL}/admin/users/{target_user['id']}/toggle-status", headers=headers_admin)
print(f"Admin Reactivated Listener: {r.status_code}")
if uploaded_song_id:
r = requests.post(f"{BASE_URL}/admin/moderation/{uploaded_song_id}/approve", headers=headers_admin)
print(f"Approve Song {uploaded_song_id}: {r.status_code} - {r.text}")
else:
print("No uploaded song ID available to approve.")
# 3. Listener Flow: Discover, Like, and Stream the approved song
print("\n--- Testing Listener Flow ---")
login_listener = {"username": listener_username, "password": password}
r = requests.post(f"{BASE_URL}/auth/login", json=login_listener)
if r.status_code != 200:
print(f"Listener Login failed: {r.status_code} - {r.text}")
return
token_listener = r.json().get("access_token")
headers_listener = {"Authorization": f"Bearer {token_listener}"}
# Discover songs
r = requests.get(f"{BASE_URL}/songs/", headers=headers_listener)
print(f"Discover: {r.status_code} - {r.text}")
if uploaded_song_id:
# Like the specific song we uploaded (which adds it to Liked Songs)
r = requests.post(f"{BASE_URL}/songs/{uploaded_song_id}/like", headers=headers_listener)
print(f"Like Song {uploaded_song_id}: {r.status_code} - {r.text}")
# Stream the specific song we uploaded
r = requests.get(f"{BASE_URL}/songs/{uploaded_song_id}/stream")
print(f"Stream Song {uploaded_song_id}: {r.status_code}")
else:
print("No uploaded song ID available to test saving/streaming.")
# 4. Admin Flow: List users and toggle status of listener (instead of deleting, for repeatable tests)
print("\n--- Testing Admin User Management ---")
# List users
r = requests.get(f"{BASE_URL}/admin/users", headers=headers_admin)
print(f"List Users: {r.status_code} - {r.text}")
if r.status_code == 200:
users = r.json()
target_user = next((u for u in users if u['username'] == listener_username), None)
if target_user:
user_id = target_user['id']
r = requests.post(f"{BASE_URL}/admin/users/{user_id}/toggle-status", headers=headers_admin)
print(f"Admin Toggle Status User {user_id}: {r.status_code} - {r.text}")
else:
print("Target listener user not found.")
else:
print("Could not list users.")
if __name__ == "__main__":
test_flow()

View 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
View 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()

View File

@@ -19,5 +19,17 @@ services:
depends_on:
- db
frontend:
build: ./frontend
ports:
- "8081:8081"
volumes:
- ./frontend:/app
- /app/node_modules
environment:
- EXPO_PUBLIC_API_URL=http://localhost:8000
depends_on:
- backend
volumes:
postgres_data:

7
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --legacy-peer-deps
COPY . .
EXPOSE 8081
CMD ["npx", "expo", "start", "--web", "--clear"]

View File

@@ -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",

View File

@@ -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",

View File

@@ -2,8 +2,10 @@ import axios from 'axios';
import { Platform } from 'react-native';
import { useAuthStore } from '../store/authStore';
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: 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;

View File

@@ -1,8 +1,9 @@
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';
import { BASE_URL } from '../api/client';
export default function AudioPlayer() {
const navigation = useNavigation();
@@ -23,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(
`http://localhost:8000/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);
}
}
@@ -66,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]);
@@ -76,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);
}
@@ -124,4 +151,4 @@ const styles = StyleSheet.create({
songTitle: { color: 'white', fontSize: 14, fontWeight: 'bold', flex: 1 },
controls: { marginLeft: 20 },
playButtonText: { color: 'white', fontSize: 16 }
});
});

View File

@@ -0,0 +1,268 @@
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert, Modal, FlatList, TextInput } from 'react-native';
import api from '../api/client';
import { useSongStore } from '../store/songStore';
import { usePlaylistStore } from '../store/playlistStore';
export default function SongListItem({ song, index, onPress }) {
const { toggleSave, savedSongs, setSongs, allSongs } = useSongStore();
const { playlists, setPlaylists, addPlaylist } = usePlaylistStore();
const [isModalVisible, setIsModalVisible] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [newPlaylistName, setNewPlaylistName] = useState('');
const handleAddToPlaylist = () => {
setIsModalVisible(true);
setIsCreating(false);
};
const isSaved = savedSongs.includes(song.id);
const handleLike = async () => {
try {
let newLikeType;
if (song.likeType === 'like') {
await api.delete(`/songs/${song.id}/unlike`);
newLikeType = undefined;
} else if (song.likeType === 'dislike') {
await api.post(`/songs/${song.id}/like`);
newLikeType = 'like';
} else {
await api.post(`/songs/${song.id}/like`);
newLikeType = 'like';
}
const updatedSongs = allSongs.map(s => s.id === song.id ? { ...s, likeType: newLikeType } : s);
setSongs(updatedSongs);
} catch (e) {
console.error('Like error:', e);
Alert.alert('Error', 'Could not update like status');
}
};
const handleSave = async () => {
try {
if (!isSaved) {
const response = await api.get(`/songs/${song.id}/stream`, { responseType: 'blob' });
if (typeof window !== 'undefined') {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `${song.title}.mp3`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} else {
Alert.alert('Save Offline', 'Offline saving is currently only supported on web.');
}
}
toggleSave(song.id);
} catch (e) {
console.error('Save error:', e);
Alert.alert('Error', 'Failed to save song for offline use');
}
};
const addSongToPlaylist = async (playlistId) => {
try {
await api.post(`/playlists/${playlistId}/songs/${song.id}`);
Alert.alert('Success', 'Song added to playlist');
setIsModalVisible(false);
} catch (e) {
console.error('Add to playlist error:', e);
Alert.alert('Error', 'Failed to add song to playlist');
}
};
const handleCreatePlaylist = async () => {
if (!newPlaylistName.trim()) {
Alert.alert('Error', 'Please enter a playlist name');
return;
}
try {
const response = await api.post('/playlists', { name: newPlaylistName });
const newPlaylist = response.data;
addPlaylist(newPlaylist);
await addSongToPlaylist(newPlaylist.id);
setNewPlaylistName('');
setIsCreating(false);
} catch (e) {
console.error('Create playlist error:', e);
Alert.alert('Error', 'Failed to create playlist');
}
};
// Format time in seconds to mm:ss
const formatTime = (seconds) => {
if (!seconds && seconds !== 0) return '00:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
};
return (
<View>
<TouchableOpacity style={styles.container} onPress={() => onPress(song)}>
<View style={styles.info}>
<Text style={styles.text}>{index + 1}. {song.title}</Text>
<Text style={styles.artist}> — {song.artist}</Text>
<Text style={styles.duration}> {formatTime(song.duration)}</Text>
</View>
<View style={styles.actions}>
<TouchableOpacity onPress={handleLike} style={styles.actionBtn}>
<Text style={{ fontSize: 16 }}>{song.likeType === 'like' ? '❤️' : '♡'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={handleAddToPlaylist} style={styles.actionBtn}>
<Text style={{ fontSize: 18, fontWeight: 'bold' }}>+</Text>
</TouchableOpacity>
<TouchableOpacity onPress={handleSave} style={styles.actionBtn}>
<Text style={{ color: isSaved ? '#ff6347' : '#ccc', fontSize: 16 }}>■</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
<Modal visible={isModalVisible} transparent={true} animationType="fade">
<View style={styles.modalOverlay}>
<View style={styles.modalContent}>
<Text style={styles.modalTitle}>Add to Playlist</Text>
{isCreating ? (
<View style={styles.createPlaylistContainer}>
<TextInput
style={styles.playlistInput}
placeholder="Enter playlist name..."
value={newPlaylistName}
onChangeText={setNewPlaylistName}
/>
<TouchableOpacity style={styles.confirmBtn} onPress={handleCreatePlaylist}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>Confirm</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.cancelBtn} onPress={() => setIsCreating(false)}>
<Text style={{ color: 'gray' }}>Cancel</Text>
</TouchableOpacity>
</View>
) : (
<>
<FlatList
data={playlists}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<TouchableOpacity style={styles.playlistOption} onPress={() => addSongToPlaylist(item.id)}>
<Text>{item.name}</Text>
</TouchableOpacity>
)}
/>
<TouchableOpacity style={styles.createBtn} onPress={() => setIsCreating(true)}>
<Text style={{ color: '#ff6347', fontWeight: 'bold' }}>+ Create New Playlist</Text>
</TouchableOpacity>
</>
)}>
<TouchableOpacity style={styles.closeBtn} onPress={() => setIsModalVisible(false)}>
<Text style={{ color: 'gray' }}>Cancel</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
padding: 12,
backgroundColor: 'white',
borderBottomWidth: 1,
borderBottomColor: '#eee',
},
info: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
text: {
fontSize: 16,
fontWeight: '500',
color: '#333',
},
artist: {
fontSize: 14,
color: '#888',
},
duration: {
fontSize: 12,
color: '#aaa',
marginLeft: 5,
},
actions: {
flexDirection: 'row',
alignItems: 'center',
},
actionBtn: {
width: 30,
alignItems: 'center',
paddingHorizontal: 5,
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
alignItems: 'center',
},
modalContent: {
backgroundColor: 'white',
width: '80%',
borderRadius: 20,
padding: 20,
maxHeight: '60%',
},
modalTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 15,
textAlign: 'center',
},
playlistOption: {
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: '#eee',
alignItems: 'center',
},
createBtn: {
marginTop: 15,
alignItems: 'center',
padding: 10,
},
closeBtn: {
marginTop: 10,
alignItems: 'center',
padding: 10,
},
createPlaylistContainer: {
width: '100%',
alignItems: 'center',
},
playlistInput: {
width: '100%',
borderBottomWidth: 1,
borderBottomColor: '#ccc',
paddingVertical: 10,
fontSize: 16,
marginBottom: 20,
textAlign: 'center',
},
confirmBtn: {
backgroundColor: '#ff6347',
padding: 10,
borderRadius: 10,
width: '100%',
alignItems: 'center',
marginBottom: 10,
},
cancelBtn: {
padding: 10,
alignItems: 'center',
width: '100%',
}
});

View File

@@ -23,7 +23,7 @@ export default function AppNavigator() {
const token = useAuthStore((state) => state.token);
const linking = {
prefixes: ['http://localhost:8081'],
prefixes: ['http://localhost:8081', 'http://127.0.0.1:8081'],
config: {
screens: {
Login: '',

View File

@@ -1,19 +1,20 @@
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert, ScrollView } from 'react-native';
import api from '../api/client';
import { useAuthStore } from '../store/authStore';
export default function AdminPanelScreen() {
const user = useAuthStore((state) => state.user);
const [users, setUsers] = useState([]);
const [pendingSongs, setPendingSongs] = useState([]);
useEffect(() => {
fetchUsers();
fetchPendingSongs();
}, []);
const fetchUsers = async () => {
try {
// Assuming there's an endpoint /admin/users as per plan
const response = await api.get('/admin/users');
setUsers(response.data);
} catch (error) {
@@ -21,6 +22,15 @@ export default function AdminPanelScreen() {
}
};
const fetchPendingSongs = async () => {
try {
const response = await api.get('/admin/moderation');
setPendingSongs(response.data);
} catch (error) {
console.error('Error fetching pending songs:', error);
}
};
const deleteUser = async (userId: number) => {
Alert.alert('Confirm', 'Are you sure you want to delete this user?', [
{ text: 'Cancel', style: 'cancel' },
@@ -40,6 +50,21 @@ export default function AdminPanelScreen() {
]);
};
const handleSongAction = async (songId: number, action: 'approve' | 'reject') => {
try {
if (action === 'approve') {
await api.post(`/admin/moderation/${songId}/approve`);
Alert.alert('Success', 'Song approved');
} else {
await api.delete(`/admin/moderation/${songId}/reject`);
Alert.alert('Success', 'Song rejected');
}
fetchPendingSongs();
} catch (error) {
Alert.alert('Error', `Failed to ${action} song`);
}
};
if (user?.role !== 'admin') {
return (
<View style={styles.container}>
@@ -48,34 +73,65 @@ export default function AdminPanelScreen() {
);
}
const renderItem = ({ item }) => (
<View style={styles.userItem}>
const renderUserItem = ({ item }) => (
<View style={styles.item}>
<View>
<Text style={styles.userName}>{item.username}</Text>
<Text style={styles.itemName}>{item.username}</Text>
<Text>{item.email} - {item.role}</Text>
</View>
<TouchableOpacity onPress={() => deleteUser(item.id)} style={styles.deleteButton}>
<TouchableOpacity onPress={() => deleteUser(item.id)} style={[styles.actionButton, styles.deleteButton]}>
<Text style={{ color: 'white' }}>Delete</Text>
</TouchableOpacity>
</View>
);
const renderSongItem = ({ item }) => (
<View style={styles.item}>
<View>
<Text style={styles.itemName}>{item.title}</Text>
<Text>{item.genre} | Author: {item.author_id}</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={() => handleSongAction(item.id, 'approve')} style={[styles.actionButton, styles.approveButton]}>
<Text style={{ color: 'white' }}>Approve</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => handleSongAction(item.id, 'reject')} style={[styles.actionButton, styles.deleteButton]}>
<Text style={{ color: 'white' }}>Reject</Text>
</TouchableOpacity>
</View>
</View>
);
return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>Admin Moderation</Text>
<Text style={styles.sectionTitle}>Pending Songs ({pendingSongs.length})</Text>
<FlatList
data={pendingSongs}
keyExtractor={(item) => item.id.toString()}
renderItem={renderSongItem}
scrollEnabled={false}
/>
<View style={{ height: 30 }} />
<Text style={styles.sectionTitle}>User Management</Text>
<FlatList
data={users}
keyExtractor={(item) => item.id.toString()}
renderItem={renderItem}
renderItem={renderUserItem}
scrollEnabled={false}
/>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#f5f5f5', padding: 20 },
container: { flexGrow: 1, backgroundColor: '#f5f5f5', padding: 20 },
title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, textAlign: 'center' },
userItem: {
sectionTitle: { fontSize: 20, fontWeight: 'bold', marginTop: 20, marginBottom: 10 },
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
@@ -86,7 +142,9 @@ const styles = StyleSheet.create({
borderWidth: 1,
borderColor: '#ddd'
},
userName: { fontSize: 16, fontWeight: 'bold' },
deleteButton: { backgroundColor: 'red', padding: 8, borderRadius: 5 },
errorText: { textAlign: 'center', marginTop: 50, color: 'red', fontSize: 18 }
itemName: { fontSize: 16, fontWeight: 'bold' },
actionButton: { padding: 8, borderRadius: 5, marginLeft: 5 },
approveButton: { backgroundColor: 'green' },
deleteButton: { backgroundColor: 'red' },
errorText: { textAlign: 'center', marginTop: 50, color: 'red', fontSize: 18 },
});

View File

@@ -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');
}

View File

@@ -1,8 +1,9 @@
import React, { useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
import api from '../api/client';
import { useSongStore } from '../store/songStore';
import { useAuthStore } from '../store/authStore';
import SongListItem from '../components/SongListItem';
export default function DiscoveryScreen({ navigation }) {
const { allSongs, setSongs, setCurrentSong } = useSongStore();
@@ -21,63 +22,6 @@ export default function DiscoveryScreen({ navigation }) {
}
};
const renderItem = ({ item }) => {
const likeType = item.likeType; // 'like', 'dislike' or undefined
const handleLikeAction = async (type) => {
try {
if (type === 'like') {
await api.post(`/songs/${item.id}/like`);
} else if (type === 'dislike') {
await api.post(`/songs/${item.id}/dislike`);
} else {
await api.delete(`/songs/${item.id}/unlike`);
}
setSongs(useSongStore.getState().allSongs.map(s => s.id === item.id ? { ...s, likeType: type === 'unlike' ? undefined : type } : s));
} catch (error) {
console.error('Error updating like:', error);
}
};
const downloadForOffline = async () => {
try {
const response = await api.get(`/songs/${item.id}/stream`, { responseType: 'blob' });
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `${item.title}.mp3`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (error) {
console.error('Error downloading song:', error);
}
};
return (
<TouchableOpacity style={styles.songItem} onPress={() => setCurrentSong(item)}>
<View style={styles.songInfo}>
<Text style={styles.songTitle}>{item.title}</Text>
<Text style={styles.songArtist}>{item.artist}</Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<TouchableOpacity onPress={() => handleLikeAction('like')} style={{ marginRight: 10 }}>
<Text style={{ fontSize: 20, color: likeType === 'like' ? 'red' : 'gray' }}>❤️</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => handleLikeAction('dislike')} style={{ marginRight: 10 }}>
<Text style={{ fontSize: 20, color: likeType === 'dislike' ? 'blue' : 'gray' }}>👎</Text>
</TouchableOpacity>
<TouchableOpacity onPress={downloadForOffline} style={{ marginRight: 10 }}>
<Text style={{ fontSize: 20 }}>💾</Text>
</TouchableOpacity>
</View>
<TouchableOpacity style={styles.playButton} onPress={() => setCurrentSong(item)}>
<Text style={{ color: 'white' }}>Play</Text>
</TouchableOpacity>
</TouchableOpacity>
);
};
return (
<View style={styles.container}>
<View style={styles.menuBar}>
@@ -113,7 +57,9 @@ export default function DiscoveryScreen({ navigation }) {
<FlatList
data={allSongs}
keyExtractor={(item) => item.id.toString()}
renderItem={renderItem}
renderItem={({ item, index }) => (
<SongListItem song={item} index={index} onPress={() => setCurrentSong(item)} />
)}
ListEmptyComponent={<Text style={styles.emptyText}>No songs found.</Text>}
/>
</View>
@@ -129,23 +75,5 @@ const styles = StyleSheet.create({
justifyContent: 'space-around'
},
menuItem: { padding: 8 },
songItem: {
flexDirection: 'row',
padding: 15,
backgroundColor: 'white',
borderBottomWidth: 1,
borderColor: '#eee',
alignItems: 'center',
justifyContent: 'space-between'
},
songInfo: { flex: 1 },
songTitle: { fontSize: 16, fontWeight: 'bold' },
songArtist: { fontSize: 14, color: '#666' },
playButton: {
backgroundColor: '#ff6347',
padding: 8,
borderRadius: 20,
marginLeft: 10
},
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
});

View File

@@ -16,8 +16,19 @@ export default function LoginScreen({ navigation }) {
password,
});
setAuth({ username }, response.data.access_token);
Alert.alert('Success', 'Logged in successfully!');
setAuth({ username, role: response.data.role }, response.data.access_token);
console.log('User role from API:', response.data.role);
// Small delay to allow AppNavigator to switch stacks based on the new token
setTimeout(() => {
if (response.data.role === 'admin') {
navigation.navigate('AdminPanel');
} else if (response.data.role === 'author') {
navigation.navigate('Upload');
} else {
navigation.navigate('Discovery');
}
}, 100);
} catch (error) {
Alert.alert('Error', 'Login failed');
}
@@ -51,4 +62,4 @@ const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginBottom: 20 },
input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 10, borderRadius: 5 },
});
});

View File

@@ -1,7 +1,8 @@
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, 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,12 +35,33 @@ 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;
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`);
@@ -50,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>
@@ -60,8 +117,7 @@ export default function NowPlayingScreen({ navigation }) {
<View style={[styles.progress, { width: `${(position / duration) * 100}%` }]} />
</TouchableOpacity>
<View style={styles.timeRow}>
<Text style={styles.time}>{formatTime(position)}</Text>
<Text style={styles.time}>{formatTime(duration)}</Text>
<Text style={styles.time}>{formatTime(position)} / {formatTime(duration)}</Text>
</View>
</View>
@@ -84,12 +140,15 @@ export default function NowPlayingScreen({ navigation }) {
<TouchableOpacity onPress={() => handleLikeAction('dislike')} style={styles.actionButton}>
<Text style={styles.actionText}>👎 Dislike</Text>
</TouchableOpacity>
<TouchableOpacity onPress={handleSaveForOffline} style={styles.actionButton}>
<Text style={styles.actionText}>💾 Save</Text>
</TouchableOpacity>
</View>
<View style={styles.footerRow}>
<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>
@@ -100,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>
);
}
@@ -114,7 +215,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 +223,19 @@ 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 }
});
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%' },
});

View File

@@ -1,10 +1,13 @@
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import api from '../api/client';
import SongListItem from '../components/SongListItem';
import { useSongStore } from '../store/songStore';
export default function PlaylistDetailScreen({ route }) {
const { playlistId } = route.params;
const [songs, setSongs] = useState([]);
const { setCurrentSong } = useSongStore();
useEffect(() => {
fetchSongs();
@@ -12,39 +15,22 @@ export default function PlaylistDetailScreen({ route }) {
const fetchSongs = async () => {
try {
const response = await api.get(`/playlists/${playlistId}/songs`);
// The backend returns PlaylistSong objects which contain song_id.
// We need to resolve these to Song objects or just show the ID for now.
const endpoint = playlistId === 'liked' ? '/playlists/liked' : `/playlists/${playlistId}/songs`;
const response = await api.get(endpoint);
setSongs(response.data);
} catch (error) {
console.error('Error fetching playlist songs:', error);
}
};
const renderItem = ({ item }) => (
<View style={styles.songItem}>
<Text>{item.title} - {item.artist}</Text>
<TouchableOpacity onPress={() => removeSong(item.id)}>
<Text style={{ color: 'red' }}>Remove</Text>
</TouchableOpacity>
</View>
);
const removeSong = async (songId) => {
try {
// Backend doesn't have a delete endpoint for playlist songs yet!
Alert.alert('Not Implemented', 'Removing songs from playlists is not yet implemented in backend.');
} catch (error) {
Alert.alert('Error', 'Failed to remove song');
}
};
return (
<View style={styles.container}>
<FlatList
data={songs}
keyExtractor={(item, index) => index.toString()}
renderItem={renderItem}
keyExtractor={(item, index) => (item.id || index).toString()}
renderItem={({ item, index }) => (
<SongListItem song={item} index={index} onPress={() => setCurrentSong(item)} />
)}
ListEmptyComponent={<Text style={styles.emptyText}>This playlist is empty.</Text>}
/>
</View>
@@ -53,13 +39,5 @@ export default function PlaylistDetailScreen({ route }) {
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#f5f5f5' },
songItem: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 15,
backgroundColor: 'white',
borderBottomWidth: 1,
borderColor: '#eee'
},
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
});

View File

@@ -1,15 +1,28 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
import api from '../api/client';
import { usePlaylistStore } from '../store/playlistStore';
import { useSongStore } from '../store/songStore';
export default function PlaylistsScreen({ navigation }) {
const { playlists, setPlaylists } = usePlaylistStore();
const { savedSongs } = useSongStore();
const [hasLikedSongs, setHasLikedSongs] = useState(false);
useEffect(() => {
fetchPlaylists();
checkLikedSongs();
}, []);
const checkLikedSongs = async () => {
try {
const response = await api.get('/playlists/liked');
setHasLikedSongs(response.data.length > 0);
} catch (error) {
console.error('Error checking liked songs:', error);
}
};
const fetchPlaylists = async () => {
try {
const response = await api.get('/playlists/');
@@ -35,7 +48,31 @@ export default function PlaylistsScreen({ navigation }) {
data={playlists}
keyExtractor={(item) => item.id.toString()}
renderItem={renderItem}
ListEmptyComponent={<Text style={styles.emptyText}>No playlists yet.</Text>}
ListHeaderComponent={() => (
<>
{hasLikedSongs && (
<TouchableOpacity
style={[styles.playlistItem, { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1 }]}
onPress={() => navigation.navigate('PlaylistDetail', { playlistId: 'liked' })}
>
<Text style={[styles.playlistName, { color: '#ff6347' }]}>❤️ Liked Songs</Text>
<Text style={styles.playlistDesc}>All your liked tracks</Text>
</TouchableOpacity>
)}
{savedSongs.length > 0 && (
<TouchableOpacity
style={[styles.playlistItem, { backgroundColor: '#eef9ff', borderColor: '#4682b4', borderWidth: 1 }]}
onPress={() => navigation.navigate('PlaylistDetail', { playlistId: 'saved' })}
>
<Text style={[styles.playlistName, { color: '#4682b4' }]}>💾 Saved Songs</Text>
<Text style={styles.playlistDesc}>Downloaded for offline use</Text>
</TouchableOpacity>
)}
</>
)}
ListEmptyComponent={playlists.length === 0 && !hasLikedSongs && savedSongs.length === 0 ? (
<View><Text style={styles.emptyText}>No playlists yet.</Text></View>
) : null}
/>
<TouchableOpacity
style={styles.fab}

View File

@@ -1,30 +1,27 @@
import React from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import { useSongStore } from '../store/songStore';
import SongListItem from '../components/SongListItem';
export default function QueueScreen({ navigation }) {
const { queue, setCurrentSong, currentIndex } = useSongStore();
const renderItem = ({ item, index }) => (
<TouchableOpacity
style={[styles.item, index === currentIndex && styles.activeItem]}
onPress={() => setCurrentSong(item)}
>
<View style={styles.info}>
<Text style={[styles.title, index === currentIndex && styles.activeTitle]}>{item.title}</Text>
<Text style={[styles.artist, index === currentIndex && styles.activeArtist]}>{item.artist}</Text>
</View>
{index === currentIndex && <Text style={styles.nowPlaying}>Now Playing</Text>}
</TouchableOpacity>
);
return (
<View style={styles.container}>
<Text style={styles.header}>Up Next</Text>
<FlatList
data={queue}
keyExtractor={(item) => item.id.toString()}
renderItem={renderItem}
renderItem={({ item, index }) => (
<View style={[index === currentIndex && styles.activeWrapper]}>
<SongListItem
song={item}
index={index}
onPress={() => setCurrentSong(item)}
/>
{index === currentIndex && <Text style={styles.nowPlaying}>Now Playing</Text>}
</View>
)}
ListEmptyComponent={<Text style={styles.emptyText}>Queue is empty.</Text>}
/>
</View>
@@ -34,21 +31,7 @@ export default function QueueScreen({ navigation }) {
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#f5f5f5', padding: 20 },
header: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, color: '#333' },
item: {
flexDirection: 'row',
padding: 15,
backgroundColor: 'white',
borderRadius: 10,
marginBottom: 10,
alignItems: 'center',
justifyContent: 'space-between'
},
activeItem: { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1 },
info: { flex: 1 },
title: { fontSize: 16, fontWeight: 'bold' },
artist: { fontSize: 14, color: '#666' },
activeTitle: { color: '#ff6347', fontWeight: 'bold' },
activeArtist: { color: '#ff6347' },
nowPlaying: { fontSize: 12, color: '#ff6347', fontWeight: 'bold' },
activeWrapper: { backgroundColor: '#ffe4e1', borderColor: '#ff6347', borderWidth: 1, borderRadius: 5 },
nowPlaying: { fontSize: 12, color: '#ff6347', fontWeight: 'bold', textAlign: 'center', paddingBottom: 5 },
emptyText: { textAlign: 'center', marginTop: 50, color: '#999' }
});

View File

@@ -7,8 +7,15 @@ export default function RegisterScreen({ navigation }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isAuthor, setIsAuthor] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const handleRegister = async () => {
if (!username || !email || !password) {
Alert.alert('Error', 'Please fill in all fields');
return;
}
setIsLoading(true);
try {
const endpoint = isAuthor ? '/auth/register-author' : '/auth/register';
await api.post(endpoint, {
@@ -22,6 +29,8 @@ export default function RegisterScreen({ navigation }) {
} catch (error) {
const message = error.response?.data?.detail || 'Registration failed';
Alert.alert('Error', message);
} finally {
setIsLoading(false);
}
};
@@ -29,45 +38,56 @@ export default function RegisterScreen({ navigation }) {
<View style={styles.container}>
<Text style={styles.title}>Create Account</Text>
<TextInput
style={styles.input}
style={[styles.input, isLoading && { opacity: 0.5 }]}
placeholder="Username"
value={username}
onChangeText={setUsername}
editable={!isLoading}
/>
<TextInput
style={styles.input}
style={[styles.input, isLoading && { opacity: 0.5 }]}
placeholder="Email"
keyboardType="email-address"
value={email}
onChangeText={setEmail}
editable={!isLoading}
/>
<TextInput
style={styles.input}
style={[styles.input, isLoading && { opacity: 0.5 }]}
placeholder="Password"
secureTextEntry
value={password}
onChangeText={setPassword}
editable={!isLoading}
/>
<View style={styles.roleContainer}>
<TouchableOpacity
style={[styles.roleButton, !isAuthor && styles.activeRole]}
onPress={() => setIsAuthor(false)}
disabled={isLoading}
>
<Text style={[styles.roleText, !isAuthor && styles.activeRoleText]}>Listener</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.roleButton, isAuthor && styles.activeRole]}
onPress={() => setIsAuthor(true)}
disabled={isLoading}
>
<Text style={[styles.roleText, isAuthor && styles.activeRoleText]}>Author</Text>
</TouchableOpacity>
</View>
<Button title="Register" onPress={handleRegister} />
<View style={{ marginTop: 20, alignItems: 'center' }}>
<Button title="Already have an account? Login" onPress={() => navigation.navigate('Login')} />
</View>
{isLoading ? (
<Text style={{ textAlign: 'center', marginBottom: 20 }}>Registering...</Text>
) : (
<>
<Button title="Register" onPress={handleRegister} />
<View style={{ marginTop: 20, alignItems: 'center' }}>
<Button title="Already have an account? Login" onPress={() => navigation.navigate('Login')} />
</View>
</>
)}
</View>
);
}

View File

@@ -5,15 +5,22 @@ import { useAuthStore } from '../store/authStore';
export default function SettingsScreen({ navigation }) {
const [oldPassword, setOldPassword] = useState('');
const { user } = useAuthStore();
const [newPassword, setNewPassword] = useState('');
const { user, logout } = useAuthStore();
const handlePasswordChange = async () => {
if (!oldPassword || !newPassword) {
Alert.alert('Error', 'Please provide both old and new passwords');
return;
}
try {
await api.put('/auth/change-password', {
old_password: oldPassword,
new_password: 'newpassword123', // In real UI this would be an input
new_password: newPassword,
});
Alert.alert('Success', 'Password changed successfully!');
setOldPassword('');
setNewPassword('');
} catch (error) {
Alert.alert('Error', 'Failed to change password');
}
@@ -35,8 +42,21 @@ export default function SettingsScreen({ navigation }) {
onChangeText={setOldPassword}
secureTextEntry
/>
{/* New password input would go here */}
<TextInput
style={styles.input}
placeholder="New Password"
value={newPassword}
onChangeText={setNewPassword}
secureTextEntry
/>
<Button title="Update Password" onPress={handlePasswordChange} />
<View style={{ marginTop: 30 }}>
<Button title="Logout" color="red" onPress={() => {
logout();
navigation.navigate('Login');
}} />
</View>
</View>
);
}

View File

@@ -3,10 +3,11 @@ import { View, TextInput, Button, StyleSheet, Alert, ScrollView, TouchableOpacit
import * as DocumentPicker from 'expo-document-picker';
import api from '../api/client';
export default function UploadScreen() {
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,31 +25,44 @@ export default function UploadScreen() {
return;
}
setUploading(true);
try {
const formData = new FormData();
formData.append('title', title);
formData.append('genre', genre);
// In Expo, we need to construct the file object correctly for FormData
const uploadFile = {
uri: file.uri,
name: file.name,
type: file.mimeType || 'audio/mpeg',
} as any;
if (typeof window !== 'undefined') {
// Web implementation: fetch the file from URI and convert to Blob
const response = await fetch(file.uri);
const blob = await response.blob();
formData.append('file', blob, file.name);
} else {
// Mobile implementation (Expo)
const uploadFile = {
uri: file.uri,
name: file.name,
type: file.mimeType || 'audio/mpeg',
} as any;
formData.append('file', uploadFile);
}
formData.append('file', uploadFile);
await api.post('/songs/upload', formData);
await api.post('/songs/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
Alert.alert('Success', 'Song uploaded successfully!');
setTitle('');
setGenre('');
setFile(null);
} catch (error) {
Alert.alert('Success', 'Song uploaded successfully!', [
{ text: 'OK', onPress: () => {
setTitle('');
setGenre('');
setFile(null);
navigation.navigate('Discovery');
}}
]);
} 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);
}
};
@@ -72,7 +86,7 @@ export default function UploadScreen() {
</Text>
</TouchableOpacity>
<View style={{ marginTop: 20 }}>
<Button title="Upload Song" onPress={handleUpload} />
<Button title={uploading ? "Uploading..." : "Upload Song"} onPress={handleUpload} disabled={uploading} />
</View>
</ScrollView>
);
@@ -88,4 +102,4 @@ const styles = StyleSheet.create({
alignItems: 'center',
marginBottom: 20
},
});
});

View File

@@ -1,4 +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;
@@ -13,3 +15,4 @@ export const useAuthStore = create<AuthState>((set) => ({
setAuth: (user, token) => set({ user, token }),
logout: () => set({ user: null, token: null }),
}));

View File

@@ -1,4 +1,6 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
interface Song {
id: number;
@@ -19,12 +21,14 @@ interface SongState {
position: number; // current playback position in ms
duration: number; // total song duration in ms
seekPosition: number | null; // target position to seek to
savedSongs: number[]; // IDs of saved songs
setSongs: (songs: Song[]) => void;
setCurrentSong: (song: Song | null) => void;
setIsPlaying: (playing: boolean) => void;
setPosition: (pos: number) => void;
setDuration: (dur: number) => void;
setSeekPosition: (pos: number | null) => void;
toggleSave: (songId: number) => void;
addToQueue: (song: Song) => void;
setQueue: (songs: Song[]) => void;
playNext: () => void;
@@ -32,48 +36,61 @@ interface SongState {
}
export const useSongStore = create<SongState>((set, get) => ({
allSongs: [],
currentSong: null,
queue: [],
currentIndex: -1,
isPlaying: false,
position: 0,
duration: 0,
seekPosition: null,
setSongs: (songs) => set({ allSongs: songs }),
setCurrentSong: (song) => {
if (!song) {
set({ currentSong: null, position: 0 });
return;
}
const queue = get().queue;
const index = queue.findIndex(s => s.id === song.id);
set({
currentSong: song,
currentIndex: index !== -1 ? index : queue.length,
position: 0
});
},
setIsPlaying: (playing) => set({ isPlaying: playing }),
setPosition: (pos) => set({ position: pos }),
setDuration: (dur) => set({ duration: dur }),
setSeekPosition: (pos) => set({ seekPosition: pos }),
addToQueue: (song) => set((state) => ({
queue: [...state.queue, song]
})),
setQueue: (songs) => set({ queue: songs, currentIndex: -1 }),
playNext: () => {
const { queue, currentIndex } = get();
if (currentIndex < queue.length - 1) {
const nextSong = queue[currentIndex + 1];
set({ currentSong: nextSong, currentIndex: currentIndex + 1 });
}
},
playPrev: () => {
const { queue, currentIndex } = get();
if (currentIndex > 0) {
const prevSong = queue[currentIndex - 1];
set({ currentSong: prevSong, currentIndex: currentIndex - 1 });
}
},
}));
allSongs: [],
currentSong: null,
queue: [],
currentIndex: -1,
isPlaying: false,
position: 0,
duration: 0,
seekPosition: null,
savedSongs: [],
setSongs: (songs) => set({ allSongs: songs }),
setCurrentSong: (song) => {
if (!song) {
set({ currentSong: null, position: 0 });
return;
}
let queue = get().queue;
let index = queue.findIndex(s => s.id === song.id);
if (index === -1) {
queue = [...queue, song];
index = queue.length - 1;
}
set({
queue: queue,
currentSong: song,
currentIndex: index,
position: 0
});
},
setIsPlaying: (playing) => set({ isPlaying: playing }),
setPosition: (pos) => set({ position: pos }),
setDuration: (dur) => set({ duration: dur }),
setSeekPosition: (pos) => set({ seekPosition: pos }),
toggleSave: (songId) => set((state) => ({
savedSongs: state.savedSongs.includes(songId)
? state.savedSongs.filter(id => id !== songId)
: [...state.savedSongs, songId]
})),
addToQueue: (song) => set((state) => ({
queue: [...state.queue, song]
})),
setQueue: (songs) => set({ queue: songs, currentIndex: -1 }),
playNext: () => {
const { queue, currentIndex } = get();
if (currentIndex < queue.length - 1) {
const nextSong = queue[currentIndex + 1];
set({ currentSong: nextSong, currentIndex: currentIndex + 1 });
}
},
playPrev: () => {
const { queue, currentIndex } = get();
if (currentIndex > 0) {
const prevSong = queue[currentIndex - 1];
set({ currentSong: prevSong, currentIndex: currentIndex - 1 });
}
},
}));