settings.py 12 KB

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