settings.py 11 KB

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