first commit

This commit is contained in:
vanalmsick 2025-09-27 18:19:06 +01:00
commit e7f627801f
152 changed files with 35352 additions and 0 deletions

View file

@ -0,0 +1,3 @@
from .celery import app as celery_app
__all__ = ("celery_app",)

View file

@ -0,0 +1,16 @@
"""
ASGI config for workout_challenge project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'workout_challenge.settings')
application = get_asgi_application()

View file

@ -0,0 +1,77 @@
"""Celery task config"""
import os
from celery import Celery
from celery.schedules import crontab
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_challenge.settings")
app = Celery("workout_challenge")
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
app.conf.beat_schedule = {
# every morning import users strava workouts
"strava_sync": {
"task": "custom_user.strava.daily_strava_sync",
"schedule": crontab(minute="44", hour="4"),
"args": (),
},
# not needed - just fallback - do all pending point recalc tasks in the morning
"point_recal": {
"task": "custom_user.point_recalc.recalc_points",
"schedule": crontab(minute="55", hour="5"),
"args": (),
},
# every Monday morning ask people who didn't connect Strava to please log their workouts
"send_all_log_workouts_email": {
"task": "custom_user.emails.celery_emails.send_all_log_workouts_email",
"schedule": crontab(day_of_week="1", minute="5", hour="9"),
"args": (),
},
# every Monday afternoon send competition leaderboards out
"send_all_leaderboard_emails": {
"task": "custom_user.emails.celery_emails.send_all_leaderboard_emails",
"schedule": crontab(day_of_week="1", minute="5", hour="15"),
"args": (),
},
# every Thursday afternoon send weekly check-ins out
"send_all_weekly_emails": {
"task": "custom_user.emails.celery_emails.send_all_weekly_emails",
"schedule": crontab(day_of_week="4", minute="5", hour="15"),
"args": (),
},
# every day at noon send start competition email
"send_all_competition_start_email": {
"task": "custom_user.emails.celery_emails.send_all_competition_start_email",
"schedule": crontab(minute="5", hour="12"),
"args": (),
},
}
def is_task_already_executing(task_name: str) -> bool:
"""Returns whether the task with given task_name is already being executed.
Args:
task_name: Name of the task to check if it is running currently.
Returns: A boolean indicating whether the task with the given task name is
running currently.
"""
active_tasks = app.control.inspect().active()
task_count = 0
for worker, running_tasks in active_tasks.items():
for task in running_tasks:
if task["name"] == task_name:
task_count += 1
return task_count > 1

View file

@ -0,0 +1,261 @@
"""
Django settings for workout_challenge project.
Generated by 'django-admin startproject' using Django 4.2.20.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
import datetime, pytz
from pathlib import Path
from urllib.parse import urlparse
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.celery import CeleryIntegration
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = BASE_DIR / "data"
QR_CODE_PATH = BASE_DIR.parent / "src-frontend" / "public"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", 'django-insecure-y4cob-qij5d!!h6^oy8bt_xqtuo%3s$w(^=7wq%9w%ckd(--9t')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
print(f'Debug modus is turned {"on" if DEBUG else "off"}')
MAIN_HOST = os.environ.get("MAIN_HOST", "http://localhost")
HOSTS = os.environ.get("HOSTS", "http://localhost,http://127.0.0.1").split(",")
CSRF_TRUSTED_ORIGINS = HOSTS
ALLOWED_HOSTS = [urlparse(url).netloc for url in HOSTS]
CORS_ALLOWED_ORIGINS = HOSTS
CORS_ALLOW_ALL_ORIGINS = True if DEBUG else False
CORS_ALLOW_CREDENTIALS = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'django_filters',
'celery',
'django_celery_beat',
'competition',
'workouts',
'custom_user',
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
'django.middleware.security.SecurityMiddleware',
'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',
]
AUTH_USER_MODEL = "custom_user.CustomUser"
ROOT_URLCONF = 'workout_challenge.urls'
MIGRATION_MODULES = {
"competition": "data.db_migrations.competition",
"workouts": "data.db_migrations.workouts",
"custom_user": "data.db_migrations.custom_user",
# "django_celery_beat": "data.db_migrations.django_celery_beat",
# "django_celery_beat_periodictask": "data.db_migrations.django_celery_beat_periodictask",
# "sessions": "data.db_migrations.sessions",
# "auth": "data.db_migrations.auth",
# "authtoken": "data.db_migrations.authtoken",
# "admin": "data.db_migrations.admin",
# "contenttypes": "data.db_migrations.contenttypes",
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'workout_challenge.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": DATA_DIR / 'db.sqlite3',
"OPTIONS": {
"timeout": 20, # seconds
},
}
if os.environ.get("POSTGRES_HOST", None) is None
else {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("POSTGRES_DB", "postgres"),
"USER": os.environ.get("POSTGRES_USER", "postgres"),
"PASSWORD": os.environ.get("POSTGRES_PASSWORD", ""),
"HOST": os.environ.get("POSTGRES_HOST", "localhost"),
"PORT": "",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
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',
},
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=5),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
}
PASSWORD_RESET_TIMEOUT = 600 # seconds = 10 minutes
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = CELERY_TIMEZONE = os.environ.get("TIME_ZONE", "Europe/London")
TIME_ZONE_OBJ = pytz.timezone(TIME_ZONE)
USE_I18N = True
USE_TZ = True
# Celery
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CACHES = {
'default': ({
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
} if DEBUG else {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://0.0.0.0:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {
"max_connections": 100,
"retry_on_timeout": True
},
"SOCKET_CONNECT_TIMEOUT": 5,
"SOCKET_TIMEOUT": 5,
}
})
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'apistatic/'
STATIC_ROOT = BASE_DIR / 'static'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Strava API
STRAVA_CLIENT_ID = int(os.environ.get("STRAVA_CLIENT_ID", 1234321))
STRAVA_CLIENT_SECRET = os.environ.get("STRAVA_CLIENT_SECRET", "ReplaceWithClientSecret")
STRAVA_LIMIT_15MIN = int(os.environ.get("STRAVA_LIMIT_15MIN", 100))
STRAVA_LIMIT_DAY = int(os.environ.get("STRAVA_LIMIT_DAY", 1000))
# Sentry
if (sentry_sdk_url := os.environ.get("REACT_APP_SENTRY_DSN", None)) is not None:
sentry_sdk.init(
dsn=sentry_sdk_url,
environment="backend",
send_default_pii=False,
enable_tracing=True,
traces_sample_rate=0.25,
profiles_sample_rate=1.0,
integrations=[
DjangoIntegration(),
CeleryIntegration(monitor_beat_tasks=True),
],
)
# Emails
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = os.environ.get("EMAIL_HOST", None)
EMAIL_PORT = int(os.environ.get("EMAIL_PORT", 25))
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", None)
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", None)
EMAIL_USE_TLS = None if (use_ssl := os.environ.get("EMAIL_USE_TLS", None)) is None else bool(use_ssl)
EMAIL_USE_SSL = None if (use_ssl := os.environ.get("EMAIL_USE_SSL", None)) is None else bool(use_ssl)
EMAIL_FROM = DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_FROM", None)
EMAIL_REPLY_TO = None if (reply_email := os.environ.get("EMAIL_REPLY_TO", None)) is None else reply_email.split(",")
# OpenAI for AI quotes
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", None)

View file

@ -0,0 +1,60 @@
"""
URL configuration for workout_challenge project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from rest_framework.routers import DefaultRouter
from competition.views import CompetitionViewSet, TeamViewSet, ActivityGoalViewSet, PointsViewSet, CompetitionStatsQueryView, FeedQueryView, JoinCompetitionView, JoinTeamView, CeleryQueryView
from workouts.views import WorkoutViewSet
from custom_user.views import CustomUserViewSet, LinkStravaView, UnlinkStravaView, SyncStravaView, PasswordResetView, PasswordResetConfirmView
router = DefaultRouter()
router.register(r'competition', CompetitionViewSet, basename='competition')
router.register(r'team', TeamViewSet, basename='teams')
router.register(r'goal', ActivityGoalViewSet, basename='goal')
router.register(r'workout', WorkoutViewSet, basename='workout')
router.register(r'point', PointsViewSet, basename='points')
router.register(r'user', CustomUserViewSet, basename='cutomuser')
urlpatterns = [
path('api/', include([
path('', include(router.urls)),
path('stats/<int:competition>/', CompetitionStatsQueryView.as_view(), name='competition-stats'),
path('feed/<int:competition>/', FeedQueryView.as_view(), name='competition-feed'),
path('join/competition/<str:join_code>/', JoinCompetitionView.as_view(), name='join-competition'),
path('join/team/', JoinTeamView.as_view(), name='join-team'),
path('strava/link/<str:code>/', LinkStravaView.as_view(), name='strava-link'),
path('strava/unlink/', UnlinkStravaView.as_view(), name='strava-unlink'),
path('strava/sync/', SyncStravaView.as_view(), name='strava-sync'),
path('celery/tasks/', CeleryQueryView.as_view(), name='celery-task-list'),
path('celery/tasks/<str:task_id>/', CeleryQueryView.as_view(), name='celery-task-status'),
path('celery/', CeleryQueryView.as_view(), name='celery-task-run'),
path('token/', TokenObtainPairView.as_view(), name='token-initial'),
path('token/refresh/', TokenRefreshView.as_view(), name='token-refresh'),
path('password-reset/request/', PasswordResetView.as_view(), name='password-reset'),
path('password-reset/confirm/', PasswordResetConfirmView.as_view(), name='password-reset-confirm'),
])),
path('admin/', admin.site.urls),
]
admin.site.site_header = 'Backend Admin Panel'
admin.site.site_title = 'Workout Challenge Backend'
admin.site.index_title = 'Welcome to the Workout Challenge Backend'

View file

@ -0,0 +1,16 @@
"""
WSGI config for workout_challenge project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'workout_challenge.settings')
application = get_wsgi_application()