settings-testing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import os
  2. import sys
  3. from pathlib import Path
  4. import dj_database_url
  5. from dotenv import load_dotenv
  6. TRUTHY = ("true", "1", "t")
  7. PROJECT_ROOT = Path(__file__).resolve().parent
  8. BASE_DIR = Path(__file__).resolve().parent.parent
  9. sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))
  10. load_dotenv("vrobbler.conf.test")
  11. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  12. # Quick-start development settings - unsuitable for production
  13. # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
  14. # SECURITY WARNING: keep the secret key used in production secret!
  15. SECRET_KEY = os.getenv("VROBBLER_SECRET_KEY", "not-a-secret-234lkjasdflj132")
  16. # SECURITY WARNING: don't run with debug turned on in production!
  17. DEBUG = os.getenv("VROBBLER_DEBUG", "false").lower() in TRUTHY
  18. TAGGIT_CASE_INSENSITIVE = True
  19. KEEP_DETAILED_SCROBBLE_LOGS = os.getenv(
  20. "VROBBLER_KEEP_DETAILED_SCROBBLE_LOGS", False
  21. )
  22. # Key must be 16, 24 or 32 bytes long and will be converted to a byte stream
  23. ENCRYPTED_FIELD_KEY = os.getenv(
  24. "VROBBLER_ENCRYPTED_FIELD_KEY", "12345678901234567890123456789012"
  25. )
  26. DJANGO_ENCRYPTED_FIELD_KEY = bytes(ENCRYPTED_FIELD_KEY, "utf-8")
  27. # Should we cull old in-progress scrobbles that are beyond the wait period for resuming?
  28. DELETE_STALE_SCROBBLES = (
  29. os.getenv("VROBBLER_DELETE_STALE_SCROBBLES", "true").lower() in TRUTHY
  30. )
  31. # Used to dump data coming from srobbling sources, helpful for building new inputs
  32. DUMP_REQUEST_DATA = (
  33. os.getenv("VROBBLER_DUMP_REQUEST_DATA", "false").lower() in TRUTHY
  34. )
  35. THESPORTSDB_API_KEY = os.getenv("VROBBLER_THESPORTSDB_API_KEY", "2")
  36. THEAUDIODB_API_KEY = os.getenv("VROBBLER_THEAUDIODB_API_KEY", "2")
  37. TMDB_API_KEY = os.getenv("VROBBLER_TMDB_API_KEY", "")
  38. LASTFM_API_KEY = os.getenv("VROBBLER_LASTFM_API_KEY")
  39. LASTFM_SECRET_KEY = os.getenv("VROBBLER_LASTFM_SECRET_KEY")
  40. IGDB_CLIENT_ID = os.getenv("VROBBLER_IGDB_CLIENT_ID")
  41. IGDB_CLIENT_SECRET = os.getenv("VROBBLER_IGDB_CLIENT_SECRET")
  42. DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
  43. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "US/Eastern")
  44. ALLOWED_HOSTS = ["*"]
  45. CSRF_TRUSTED_ORIGINS = [
  46. os.getenv("VROBBLER_TRUSTED_ORIGINS", "http://localhost:8000")
  47. ]
  48. X_FRAME_OPTIONS = "SAMEORIGIN"
  49. REDIS_URL = os.getenv("VROBBLER_REDIS_URL", None)
  50. if REDIS_URL:
  51. print(f"Sending tasks to redis@{REDIS_URL.split('@')[-1]}")
  52. else:
  53. print("Eagerly running all tasks")
  54. CELERY_TASK_ALWAYS_EAGER = (
  55. os.getenv("VROBBLER_SKIP_CELERY", "false").lower() in TRUTHY
  56. )
  57. CELERY_BROKER_URL = REDIS_URL if REDIS_URL else "memory://localhost/"
  58. CELERY_RESULT_BACKEND = "django-db"
  59. CELERY_TIMEZONE = os.getenv("VROBBLER_TIME_ZONE", "US/Eastern")
  60. CELERY_TASK_TRACK_STARTED = True
  61. INSTALLED_APPS = [
  62. "django.contrib.admin",
  63. "django.contrib.auth",
  64. "django.contrib.contenttypes",
  65. "django.contrib.sessions",
  66. "django.contrib.messages",
  67. "django.contrib.staticfiles",
  68. "django.contrib.sites",
  69. "django.contrib.humanize",
  70. "django_filters",
  71. "django_extensions",
  72. "storages",
  73. "taggit",
  74. "rest_framework.authtoken",
  75. "encrypted_field",
  76. "profiles",
  77. "scrobbles",
  78. "videos",
  79. "music",
  80. "podcasts",
  81. "sports",
  82. "books",
  83. "boardgames",
  84. "videogames",
  85. "mathfilters",
  86. "rest_framework",
  87. "allauth",
  88. "allauth.account",
  89. "allauth.socialaccount",
  90. "django_celery_results",
  91. ]
  92. SITE_ID = 1
  93. MIDDLEWARE = [
  94. "django.middleware.security.SecurityMiddleware",
  95. "django.contrib.sessions.middleware.SessionMiddleware",
  96. "django.middleware.common.CommonMiddleware",
  97. "django.middleware.csrf.CsrfViewMiddleware",
  98. "django.contrib.auth.middleware.AuthenticationMiddleware",
  99. "django.contrib.messages.middleware.MessageMiddleware",
  100. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  101. "django.middleware.gzip.GZipMiddleware",
  102. ]
  103. ROOT_URLCONF = "vrobbler.urls"
  104. TEMPLATES = [
  105. {
  106. "BACKEND": "django.template.backends.django.DjangoTemplates",
  107. "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
  108. "APP_DIRS": True,
  109. "OPTIONS": {
  110. "context_processors": [
  111. "django.template.context_processors.debug",
  112. "django.template.context_processors.request",
  113. "django.contrib.auth.context_processors.auth",
  114. "django.contrib.messages.context_processors.messages",
  115. "videos.context_processors.video_lists",
  116. "music.context_processors.music_lists",
  117. "scrobbles.context_processors.now_playing",
  118. ],
  119. },
  120. },
  121. ]
  122. MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
  123. WSGI_APPLICATION = "vrobbler.wsgi.application"
  124. DATABASES = {
  125. "default": dj_database_url.config(
  126. default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
  127. conn_max_age=600,
  128. ),
  129. }
  130. db_str = ""
  131. if "sqlite" in DATABASES["default"]["ENGINE"]:
  132. db_str = f"Connected to sqlite@{DATABASES['default']['NAME']}"
  133. if "postgresql" in DATABASES["default"]["ENGINE"]:
  134. db_str = f"Connected to postgres@{DATABASES['default']['HOST']}/{DATABASES['default']['NAME']}"
  135. if db_str:
  136. print(db_str)
  137. CACHES = {
  138. "default": {
  139. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  140. "LOCATION": "unique-snowflake",
  141. }
  142. }
  143. if REDIS_URL:
  144. CACHES["default"]["BACKEND"] = "django_redis.cache.RedisCache"
  145. CACHES["default"]["LOCATION"] = REDIS_URL
  146. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  147. AUTHENTICATION_BACKENDS = [
  148. "django.contrib.auth.backends.ModelBackend",
  149. "allauth.account.auth_backends.AuthenticationBackend",
  150. ]
  151. # We have to ignore content negotiation because Jellyfin is a bad actor
  152. REST_FRAMEWORK = {
  153. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  154. "DEFAULT_AUTHENTICATION_CLASSES": [
  155. "rest_framework.authentication.TokenAuthentication",
  156. "rest_framework.authentication.SessionAuthentication",
  157. ],
  158. "DEFAULT_CONTENT_NEGOTIATION_CLASS": "vrobbler.negotiation.IgnoreClientContentNegotiation",
  159. "DEFAULT_FILTER_BACKENDS": [
  160. "django_filters.rest_framework.DjangoFilterBackend"
  161. ],
  162. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  163. "PAGE_SIZE": 200,
  164. }
  165. LOGIN_REDIRECT_URL = "/"
  166. AUTH_PASSWORD_VALIDATORS = [
  167. {
  168. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  169. },
  170. {
  171. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  172. },
  173. {
  174. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  175. },
  176. {
  177. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  178. },
  179. ]
  180. # Internationalization
  181. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  182. LANGUAGE_CODE = "en-us"
  183. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")
  184. USE_I18N = True
  185. USE_TZ = True
  186. # Static files (CSS, JavaScript, Images)
  187. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  188. #
  189. from storages.backends import s3boto3
  190. USE_S3_STORAGE = os.getenv("VROBBLER_USE_S3", "False").lower() in TRUTHY
  191. if USE_S3_STORAGE:
  192. AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL", "")
  193. AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME", "")
  194. AWS_S3_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
  195. AWS_S3_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
  196. S3_ROOT = "/".join([AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME])
  197. print(f"Storing media on S3 at {S3_ROOT}")
  198. DEFAULT_FILE_STORAGE = "vrobbler.storages.MediaStorage"
  199. STATICFILES_STORAGE = "vrobbler.storages.StaticStorage"
  200. STATIC_URL = S3_ROOT + "/static/"
  201. MEDIA_URL = S3_ROOT + "/media/"
  202. else:
  203. STATIC_ROOT = os.getenv(
  204. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  205. )
  206. MEDIA_ROOT = os.getenv(
  207. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  208. )
  209. STATIC_URL = os.getenv("VROBBLER_STATIC_URL", "/static/")
  210. MEDIA_URL = os.getenv("VROBBLER_MEDIA_URL", "/media/")
  211. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", "false").lower() in TRUTHY
  212. LOG_TYPE = "json" if JSON_LOGGING else "log"
  213. default_level = "INFO"
  214. if DEBUG:
  215. default_level = "DEBUG"
  216. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  217. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  218. LOGGING = {
  219. "version": 1,
  220. "disable_existing_loggers": False,
  221. "root": {
  222. "handlers": ["console", "file"],
  223. "level": LOG_LEVEL,
  224. "propagate": True,
  225. },
  226. "formatters": {
  227. "color": {
  228. "()": "colorlog.ColoredFormatter",
  229. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  230. # the beautiful alignment produced below
  231. "format": "\r"
  232. "{log_color}{levelname:8s}{reset} "
  233. "{bold_cyan}{name}{reset}:"
  234. "{fg_bold_red}{lineno}{reset} "
  235. "{thin_yellow}{funcName} "
  236. "{thin_white}{message}"
  237. "{reset}",
  238. "style": "{",
  239. },
  240. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  241. "json": {
  242. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  243. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  244. },
  245. },
  246. "handlers": {
  247. "console": {
  248. "class": "logging.StreamHandler",
  249. "formatter": "color",
  250. "level": LOG_LEVEL,
  251. },
  252. "null": {
  253. "class": "logging.NullHandler",
  254. "level": LOG_LEVEL,
  255. },
  256. "sql": {
  257. "class": "logging.handlers.RotatingFileHandler",
  258. "filename": "".join([LOG_FILE_PATH, "vrobbler_sql.", LOG_TYPE]),
  259. "formatter": LOG_TYPE,
  260. "level": LOG_LEVEL,
  261. },
  262. "file": {
  263. "class": "logging.handlers.RotatingFileHandler",
  264. "filename": "".join([LOG_FILE_PATH, "vrobbler.", LOG_TYPE]),
  265. "formatter": LOG_TYPE,
  266. "level": LOG_LEVEL,
  267. },
  268. },
  269. "loggers": {
  270. # Quiet down our console a little
  271. "django": {
  272. "handlers": ["null"],
  273. "propagate": True,
  274. },
  275. "django.db.backends": {"handlers": ["null"]},
  276. "django.server": {"handlers": ["null"]},
  277. "pylast": {"handlers": ["null"], "propagate": False},
  278. "musicbrainzngs": {"handlers": ["null"], "propagate": False},
  279. "httpx": {"handlers": ["null"], "propagate": False},
  280. "vrobbler": {
  281. "handlers": ["console"],
  282. "propagate": False,
  283. },
  284. },
  285. }
  286. LOG_TO_CONSOLE = (
  287. os.getenv("VROBBLER_LOG_TO_CONSOLE", "false").lower() in TRUTHY
  288. )
  289. if LOG_TO_CONSOLE:
  290. LOGGING["loggers"]["django"]["handlers"] = ["console"]
  291. LOGGING["loggers"]["vrobbler"]["handlers"] = ["console"]