Initial commit - SoundWave v1.0

- Full PWA support with offline capabilities
- Comprehensive search across songs, playlists, and channels
- Offline playlist manager with download tracking
- Pre-built frontend for zero-build deployment
- Docker-based deployment with docker compose
- Material-UI dark theme interface
- YouTube audio download and management
- Multi-user authentication support
This commit is contained in:
Iulian 2025-12-16 23:43:07 +00:00
commit 51679d1943
254 changed files with 37281 additions and 0 deletions

View file

@ -0,0 +1,6 @@
# Config app
# This will make sure the Celery app is always imported when Django starts
from .celery import app as celery_app
__all__ = ('celery_app',)

11
backend/config/asgi.py Normal file
View file

@ -0,0 +1,11 @@
"""
ASGI config for SoundWave project.
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()

50
backend/config/celery.py Normal file
View file

@ -0,0 +1,50 @@
"""Celery configuration for SoundWave"""
import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
app = Celery('soundwave')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
# Periodic task schedule
app.conf.beat_schedule = {
# SMART SYNC: Check for new content in subscriptions every 15 minutes
'sync-subscriptions': {
'task': 'update_subscriptions',
'schedule': crontab(minute='*/15'), # Every 15 minutes for faster sync
},
# Auto-fetch lyrics every hour
'auto-fetch-lyrics': {
'task': 'audio.auto_fetch_lyrics',
'schedule': crontab(minute=0), # Every hour
'kwargs': {'limit': 50, 'max_attempts': 3},
},
# Clean up lyrics cache weekly
'cleanup-lyrics-cache': {
'task': 'audio.cleanup_lyrics_cache',
'schedule': crontab(hour=3, minute=0, day_of_week=0), # Sunday at 3 AM
'kwargs': {'days_old': 30},
},
# Retry failed lyrics weekly
'refetch-failed-lyrics': {
'task': 'audio.refetch_failed_lyrics',
'schedule': crontab(hour=4, minute=0, day_of_week=0), # Sunday at 4 AM
'kwargs': {'days_old': 7, 'limit': 20},
},
# Auto-fetch artwork every 2 hours
'auto-fetch-artwork': {
'task': 'audio.auto_fetch_artwork_batch',
'schedule': crontab(minute=0, hour='*/2'), # Every 2 hours
'kwargs': {'limit': 50},
},
# Auto-fetch artist info daily
'auto-fetch-artist-info': {
'task': 'audio.auto_fetch_artist_info_batch',
'schedule': crontab(hour=2, minute=0), # Daily at 2 AM
'kwargs': {'limit': 20},
},
}

View file

@ -0,0 +1,41 @@
"""Middleware for user isolation and multi-tenancy"""
from django.utils.deprecation import MiddlewareMixin
from django.db.models import Q
class UserIsolationMiddleware(MiddlewareMixin):
"""
Middleware to ensure users can only access their own data
Admins can access all data
"""
def process_request(self, request):
"""Add user isolation context to request"""
if hasattr(request, 'user') and request.user.is_authenticated:
# Add helper method to filter queryset by user
def filter_by_user(queryset):
"""Filter queryset to show only user's data or all if admin"""
if request.user.is_admin or request.user.is_superuser:
# Admins can see all data
return queryset
# Regular users see only their own data
if hasattr(queryset.model, 'owner'):
return queryset.filter(owner=request.user)
elif hasattr(queryset.model, 'user'):
return queryset.filter(user=request.user)
return queryset
request.filter_by_user = filter_by_user
request.is_admin_user = request.user.is_admin or request.user.is_superuser
return None
class StorageQuotaMiddleware(MiddlewareMixin):
"""Middleware to track storage usage"""
def process_response(self, request, response):
"""Update storage usage after file operations"""
# This can be expanded to track file uploads/deletions
# For now, it's a placeholder for future implementation
return response

201
backend/config/settings.py Normal file
View file

@ -0,0 +1,201 @@
"""
Django settings for SoundWave project.
"""
import os
from pathlib import Path
# Build paths inside the project
BASE_DIR = Path(__file__).resolve().parent.parent
# Security settings
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'dev-secret-key-change-in-production')
DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'drf_spectacular',
'django_celery_beat',
# SoundWave apps
'user',
'common',
'audio',
'channel',
'playlist',
'download',
'task',
'appsettings',
'stats',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Custom middleware for multi-tenancy
'config.middleware.UserIsolationMiddleware',
'config.middleware.StorageQuotaMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR.parent / 'frontend' / 'dist', BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# Use /app/data for persistent storage across container rebuilds
import os
DATA_DIR = os.environ.get('DATA_DIR', '/app/data')
if not os.path.exists(DATA_DIR):
os.makedirs(DATA_DIR, exist_ok=True)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DATA_DIR, 'db.sqlite3'),
}
}
# Custom user model
AUTH_USER_MODEL = 'user.Account'
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = os.environ.get('TZ', 'UTC')
USE_I18N = True
USE_TZ = True
# Static files
STATIC_URL = '/assets/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR.parent / 'frontend' / 'dist' / 'assets',
BASE_DIR.parent / 'frontend' / 'dist', # For manifest.json, service-worker.js, etc.
]
# WhiteNoise configuration
WHITENOISE_USE_FINDERS = True
WHITENOISE_AUTOREFRESH = True
WHITENOISE_INDEX_FILE = False # Don't serve index.html for directories
WHITENOISE_MIMETYPES = {
'.js': 'application/javascript',
'.css': 'text/css',
}
# Media files
MEDIA_URL = '/media/'
# Ensure MEDIA_ROOT exists and is writable
MEDIA_ROOT = os.environ.get('MEDIA_ROOT', '/app/audio')
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT, exist_ok=True)
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# REST Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 50,
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
# CORS settings
CORS_ALLOWED_ORIGINS = [
"http://localhost:8889",
"http://127.0.0.1:8889",
"http://192.168.50.71:8889",
]
CORS_ALLOW_CREDENTIALS = True
# CSRF settings for development cross-origin access
CSRF_TRUSTED_ORIGINS = [
"http://localhost:8889",
"http://127.0.0.1:8889",
"http://192.168.50.71:8889",
]
CSRF_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SECURE = False
# Security headers for development
SECURE_CROSS_ORIGIN_OPENER_POLICY = None # Disable COOP header for development
# Spectacular settings
SPECTACULAR_SETTINGS = {
'TITLE': 'SoundWave API',
'DESCRIPTION': 'Audio archiving and streaming platform',
'VERSION': '1.0.0',
}
# Celery settings
CELERY_BROKER_URL = f"redis://{os.environ.get('REDIS_HOST', 'localhost')}:6379/0"
CELERY_RESULT_BACKEND = f"redis://{os.environ.get('REDIS_HOST', 'localhost')}:6379/0"
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = TIME_ZONE
# ElasticSearch settings
ES_URL = os.environ.get('ES_URL', 'http://localhost:92000')
ES_USER = os.environ.get('ELASTIC_USER', 'elastic')
ES_PASSWORD = os.environ.get('ELASTIC_PASSWORD', 'soundwave')
# SoundWave settings
SW_HOST = os.environ.get('SW_HOST', 'http://localhost:123456')
SW_AUTO_UPDATE_YTDLP = os.environ.get('SW_AUTO_UPDATE_YTDLP', 'false') == 'true'
# Last.fm API settings
# Register for API keys at: https://www.last.fm/api/account/create
LASTFM_API_KEY = os.environ.get('LASTFM_API_KEY', '')
LASTFM_API_SECRET = os.environ.get('LASTFM_API_SECRET', '')
# Fanart.tv API settings
# Register for API key at: https://fanart.tv/get-an-api-key/
FANART_API_KEY = os.environ.get('FANART_API_KEY', '')

59
backend/config/urls.py Normal file
View file

@ -0,0 +1,59 @@
"""URL Configuration for SoundWave"""
from django.contrib import admin
from django.urls import include, path, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.views.static import serve
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from common.streaming import serve_media_with_range
import os
urlpatterns = [
path("api/", include("common.urls")),
path("api/audio/", include("audio.urls")),
path("api/channel/", include("channel.urls")),
path("api/playlist/", include("playlist.urls")),
path("api/download/", include("download.urls")),
path("api/task/", include("task.urls")),
path("api/appsettings/", include("appsettings.urls")),
path("api/stats/", include("stats.urls")),
path("api/user/", include("user.urls")),
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
path(
"api/docs/",
SpectacularSwaggerView.as_view(url_name="schema"),
name="swagger-ui",
),
path("admin/", admin.site.urls),
]
# Serve static files
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# Serve media files (audio files) with Range request support for seeking
if settings.MEDIA_URL and settings.MEDIA_ROOT:
urlpatterns += [
re_path(
r'^media/(?P<path>.*)$',
serve_media_with_range,
{'document_root': settings.MEDIA_ROOT},
),
]
# Serve PWA files from frontend/dist
frontend_dist = settings.BASE_DIR.parent / 'frontend' / 'dist'
urlpatterns += [
path('manifest.json', serve, {'path': 'manifest.json', 'document_root': frontend_dist}),
path('service-worker.js', serve, {'path': 'service-worker.js', 'document_root': frontend_dist}),
re_path(r'^img/(?P<path>.*)$', serve, {'document_root': frontend_dist / 'img'}),
re_path(r'^avatars/(?P<path>.*)$', serve, {'document_root': frontend_dist / 'avatars'}),
]
# Serve React frontend - catch all routes (must be LAST)
urlpatterns += [
re_path(r'^(?!api/|admin/|static/|media/|assets/).*$',
TemplateView.as_view(template_name='index.html'),
name='frontend'),
]

View file

@ -0,0 +1,19 @@
"""Settings for user registration and authentication"""
# Public registration disabled - only admins can create users
ALLOW_PUBLIC_REGISTRATION = False
# Require admin approval for new users (future feature)
REQUIRE_ADMIN_APPROVAL = False
# Minimum password requirements
PASSWORD_MIN_LENGTH = 8
PASSWORD_REQUIRE_UPPERCASE = True
PASSWORD_REQUIRE_LOWERCASE = True
PASSWORD_REQUIRE_NUMBERS = True
PASSWORD_REQUIRE_SPECIAL = False
# Account security
ENABLE_2FA = True
MAX_LOGIN_ATTEMPTS = 5
LOCKOUT_DURATION_MINUTES = 15

11
backend/config/wsgi.py Normal file
View file

@ -0,0 +1,11 @@
"""
WSGI config for SoundWave project.
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()