settings.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. PODCAST_COMPLETION_PERCENT = os.getenv(
  29. "VROBBLER_PODCAST_COMPLETION_PERCENT", 25
  30. )
  31. MUSIC_COMPLETION_PERCENT = os.getenv("VROBBLER_MUSIC_COMPLETION_PERCENT", 90)
  32. # Should we cull old in-progress scrobbles that are beyond the wait period for resuming?
  33. DELETE_STALE_SCROBBLES = os.getenv("VROBBLER_DELETE_STALE_SCROBBLES", True)
  34. # Used to dump data coming from srobbling sources, helpful for building new inputs
  35. DUMP_REQUEST_DATA = os.getenv("VROBBLER_DUMP_REQUEST_DATA", False)
  36. VIDEO_BACKOFF_MINUTES = os.getenv("VROBBLER_VIDEO_BACKOFF_MINUTES", 15)
  37. MUSIC_BACKOFF_SECONDS = os.getenv("VROBBLER_VIDEO_BACKOFF_SECONDS", 1)
  38. # If you stop waching or listening to a track, how long should we wait before we
  39. # give up on the old scrobble and start a new one? This could also be considered
  40. # a "continue in progress scrobble" time period. So if you pause the media and
  41. # start again, should it be a new scrobble.
  42. VIDEO_WAIT_PERIOD_DAYS = os.getenv("VROBBLER_VIDEO_WAIT_PERIOD_DAYS", 1)
  43. MUSIC_WAIT_PERIOD_MINUTES = os.getenv("VROBBLER_VIDEO_BACKOFF_MINUTES", 1)
  44. TMDB_API_KEY = os.getenv("VROBBLER_TMDB_API_KEY", "")
  45. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  46. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "EST")
  47. ALLOWED_HOSTS = ["*"]
  48. CSRF_TRUSTED_ORIGINS = [
  49. os.getenv("VROBBLER_TRUSTED_ORIGINS", "http://localhost:8000")
  50. ]
  51. X_FRAME_OPTIONS = "SAMEORIGIN"
  52. REDIS_URL = os.getenv("VROBBLER_REDIS_URL", None)
  53. CELERY_TASK_ALWAYS_EAGER = os.getenv("VROBBLER_SKIP_CELERY", False)
  54. CELERY_BROKER_URL = REDIS_URL if REDIS_URL else "memory://localhost/"
  55. CELERY_RESULT_BACKEND = "django-db"
  56. CELERY_TIMEZONE = os.getenv("VROBBLER_TIME_ZONE", "EST")
  57. CELERY_TASK_TRACK_STARTED = True
  58. INSTALLED_APPS = [
  59. "django.contrib.admin",
  60. "django.contrib.auth",
  61. "django.contrib.contenttypes",
  62. "django.contrib.sessions",
  63. "django.contrib.messages",
  64. "django.contrib.staticfiles",
  65. "django.contrib.sites",
  66. "django.contrib.humanize",
  67. "django_filters",
  68. "django_extensions",
  69. 'rest_framework.authtoken',
  70. "scrobbles",
  71. "videos",
  72. "music",
  73. "podcasts",
  74. "rest_framework",
  75. "allauth",
  76. "allauth.account",
  77. "allauth.socialaccount",
  78. "django_celery_results",
  79. ]
  80. SITE_ID = 1
  81. MIDDLEWARE = [
  82. "django.middleware.security.SecurityMiddleware",
  83. "whitenoise.middleware.WhiteNoiseMiddleware",
  84. "django.contrib.sessions.middleware.SessionMiddleware",
  85. "django.middleware.common.CommonMiddleware",
  86. "django.middleware.csrf.CsrfViewMiddleware",
  87. "django.contrib.auth.middleware.AuthenticationMiddleware",
  88. "django.contrib.messages.middleware.MessageMiddleware",
  89. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  90. "django.middleware.gzip.GZipMiddleware",
  91. ]
  92. ROOT_URLCONF = "vrobbler.urls"
  93. TEMPLATES = [
  94. {
  95. "BACKEND": "django.template.backends.django.DjangoTemplates",
  96. "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
  97. "APP_DIRS": True,
  98. "OPTIONS": {
  99. "context_processors": [
  100. "django.template.context_processors.debug",
  101. "django.template.context_processors.request",
  102. "django.contrib.auth.context_processors.auth",
  103. "django.contrib.messages.context_processors.messages",
  104. "videos.context_processors.video_lists",
  105. "music.context_processors.music_lists",
  106. ],
  107. },
  108. },
  109. ]
  110. WSGI_APPLICATION = "vrobbler.wsgi.application"
  111. DATABASES = {
  112. "default": dj_database_url.config(
  113. default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
  114. conn_max_age=600,
  115. ),
  116. }
  117. if TESTING:
  118. DATABASES = {
  119. "default": dj_database_url.config(default="sqlite:///testdb.sqlite3")
  120. }
  121. CACHES = {
  122. "default": {
  123. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  124. "LOCATION": "unique-snowflake",
  125. }
  126. }
  127. if REDIS_URL:
  128. CACHES["default"][
  129. "BACKEND"
  130. ] = "django.core.cache.backends.redis.RedisCache"
  131. CACHES["default"]["LOCATION"] = REDIS_URL
  132. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  133. AUTHENTICATION_BACKENDS = [
  134. "django.contrib.auth.backends.ModelBackend",
  135. "allauth.account.auth_backends.AuthenticationBackend",
  136. ]
  137. REST_FRAMEWORK = {
  138. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  139. 'DEFAULT_AUTHENTICATION_CLASSES': [
  140. #'rest_framework.authentication.BasicAuthentication',
  141. #'rest_framework.authentication.TokenAuthentication',
  142. 'rest_framework.authentication.SessionAuthentication',
  143. ],
  144. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  145. "DEFAULT_FILTER_BACKENDS": [
  146. "django_filters.rest_framework.DjangoFilterBackend"
  147. ],
  148. 'DEFAULT_PARSER_CLASSES': [
  149. 'rest_framework.parsers.JSONParser',
  150. ],
  151. 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'vrobbler.negotiation.IgnoreClientContentNegotiation',
  152. "PAGE_SIZE": 100,
  153. }
  154. LOGIN_REDIRECT_URL = "/"
  155. AUTH_PASSWORD_VALIDATORS = [
  156. {
  157. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  158. },
  159. {
  160. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  161. },
  162. {
  163. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  164. },
  165. {
  166. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  167. },
  168. ]
  169. # Internationalization
  170. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  171. LANGUAGE_CODE = "en-us"
  172. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "EST")
  173. USE_I18N = True
  174. USE_L10N = True
  175. USE_TZ = True
  176. # Static files (CSS, JavaScript, Images)
  177. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  178. STATIC_URL = "static/"
  179. STATIC_ROOT = os.getenv(
  180. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  181. )
  182. if not DEBUG:
  183. STATICFILES_STORAGE = (
  184. "whitenoise.storage.CompressedManifestStaticFilesStorage"
  185. )
  186. MEDIA_URL = "/media/"
  187. MEDIA_ROOT = os.getenv(
  188. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  189. )
  190. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", False)
  191. LOG_TYPE = "json" if JSON_LOGGING else "log"
  192. default_level = "INFO"
  193. if DEBUG:
  194. default_level = "DEBUG"
  195. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  196. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  197. LOGGING = {
  198. "version": 1,
  199. "disable_existing_loggers": False,
  200. "root": {
  201. "handlers": ["console", "file"],
  202. "level": LOG_LEVEL,
  203. "propagate": True,
  204. },
  205. "formatters": {
  206. "color": {
  207. "()": "colorlog.ColoredFormatter",
  208. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  209. # the beautiful alignment produced below
  210. "format": "\r"
  211. "{log_color}{levelname:8s}{reset} "
  212. "{bold_cyan}{name}{reset}:"
  213. "{fg_bold_red}{lineno}{reset} "
  214. "{thin_yellow}{funcName} "
  215. "{thin_white}{message}"
  216. "{reset}",
  217. "style": "{",
  218. },
  219. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  220. "json": {
  221. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  222. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  223. },
  224. },
  225. "handlers": {
  226. "console": {
  227. "class": "logging.StreamHandler",
  228. "formatter": "color",
  229. "level": LOG_LEVEL,
  230. },
  231. "null": {
  232. "class": "logging.NullHandler",
  233. "level": LOG_LEVEL,
  234. },
  235. "file": {
  236. "class": "logging.handlers.RotatingFileHandler",
  237. "filename": "".join([LOG_FILE_PATH, "vrobbler.log"]),
  238. "formatter": LOG_TYPE,
  239. "level": LOG_LEVEL,
  240. },
  241. "requests_file": {
  242. "class": "logging.handlers.RotatingFileHandler",
  243. "filename": "".join([LOG_FILE_PATH, "vrobbler_requests.log"]),
  244. "formatter": LOG_TYPE,
  245. "level": LOG_LEVEL,
  246. },
  247. },
  248. "loggers": {
  249. # Quiet down our console a little
  250. "django": {
  251. "handlers": ["file"],
  252. "propagate": True,
  253. },
  254. "django.db.backends": {"handlers": ["null"]},
  255. "vrobbler": {
  256. "handlers": ["console", "file"],
  257. "propagate": True,
  258. },
  259. },
  260. }
  261. if DEBUG:
  262. # We clear out a db with lots of games all the time in dev
  263. DATA_UPLOAD_MAX_NUMBER_FIELDS = 3000