tl/server/settings.py

204 lines
7 KiB
Python
Raw Normal View History

"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 6.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
def _env(key, default=""):
return os.environ.get(key, default)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# Real key from the environment in prod; the insecure literal is a dev fallback
# so `runserver` works out of the box.
SECRET_KEY = _env("DJANGO_SECRET_KEY") or 'django-insecure-it#u2wp)_qjx@cq61o*thw#*4_1*hk!%%lz#d+fww6^*l3j+zj'
# DEBUG off in prod (DJANGO_DEBUG=0); on by default for local dev.
DEBUG = _env("DJANGO_DEBUG", "1") == "1"
# '.ts.net' matches any Tailscale MagicDNS name; the literal is the tailnet IP.
# DJANGO_ALLOWED_HOSTS (comma-separated, e.g. ".fly.dev") adds prod hosts.
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'testserver', '.ts.net', '100.82.84.50']
ALLOWED_HOSTS += [h for h in _env("DJANGO_ALLOWED_HOSTS").split(",") if h]
# Application definition
INSTALLED_APPS = [
'daphne', # ASGI server; must precede staticfiles so runserver uses it
'channels',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'scenes',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # serves static + the SPA in prod
'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',
]
ROOT_URLCONF = 'server.urls'
# Realtime: push scene deltas to peers over websockets. In-memory layer is fine
# for a single process; swap to channels_redis when you run more than one worker.
ASGI_APPLICATION = 'server.asgi.application'
CHANNEL_LAYERS = {'default': {'BACKEND': 'channels.layers.InMemoryChannelLayer'}}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# DJANGO_DB_PATH points at the Fly volume (/data/db.sqlite3) in prod.
'NAME': _env("DJANGO_DB_PATH") or (BASE_DIR / 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/6.0/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/6.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = 'static/'
# Uploaded OTIO + clip files
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Django's own static (admin) is collected here; WhiteNoise serves it and also
# serves the compiled frontend (resources/public — index.html, app.js, css,
# fonts, icons) at the site root. It's a hash-routed SPA, so '/' is all we need.
STATIC_ROOT = BASE_DIR / 'staticfiles'
WHITENOISE_ROOT = BASE_DIR / 'tl' / 'resources' / 'public'
WHITENOISE_INDEX_FILE = True
STORAGES = {
'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
'staticfiles': {'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage'},
}
# Production media (clips/otio/thumbnails) → Cloudflare R2 (S3-compatible, free
# egress). FileField.url then returns the public CDN URL automatically. Set the
# R2_* env vars to switch it on; without them dev stays on local disk.
# R2_PUBLIC_DOMAIN = a Cloudflare-fronted custom domain on the bucket (no scheme).
if _env("R2_BUCKET"):
STORAGES['default'] = {
'BACKEND': 'storages.backends.s3.S3Storage',
'OPTIONS': {
'bucket_name': _env("R2_BUCKET"),
'endpoint_url': _env("R2_ENDPOINT"),
'access_key': _env("R2_ACCESS_KEY_ID"),
'secret_key': _env("R2_SECRET_ACCESS_KEY"),
'region_name': 'auto',
'signature_version': 's3v4',
'custom_domain': _env("R2_PUBLIC_DOMAIN") or None,
'querystring_auth': not bool(_env("R2_PUBLIC_DOMAIN")),
'file_overwrite': False,
},
}
# Allow clip uploads up to ~100 MB (files stream to a temp file past 2.5 MB).
DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * 1024 * 1024
# The shadow-cljs dev frontend talks to this API cross-origin, with the session
# cookie, so allow its origin + credentials. Over Tailscale the frontend may be
# reached either by MagicDNS name (*.ts.net) or by the raw tailnet IP
# (100.64.0.0/10), both on :8280 — match both forms.
CORS_ALLOWED_ORIGINS = ['http://localhost:8280', 'http://127.0.0.1:8280']
CORS_ALLOWED_ORIGIN_REGEXES = [r'^http://[\w.-]+\.ts\.net:8280$',
r'^http://100\.\d{1,3}\.\d{1,3}\.\d{1,3}:8280$']
CORS_ALLOW_CREDENTIALS = True
# Cross-origin POSTs carry the session cookie, so Django's CSRF check needs the
# frontend origins trusted (Origin header must match for unsafe methods).
CSRF_TRUSTED_ORIGINS = ['http://localhost:8280', 'http://127.0.0.1:8280',
'https://*.ts.net', 'http://*.ts.net',
'http://100.*']
# DJANGO_CSRF_TRUSTED (comma-separated, e.g. "https://my-app.fly.dev") for prod.
CSRF_TRUSTED_ORIGINS += [o for o in _env("DJANGO_CSRF_TRUSTED").split(",") if o]
# Behind Fly's edge TLS: trust the forwarded-proto header and mark cookies secure.
if not DEBUG:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'