settings.py 10.0 KB

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