settings-testing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. "markdownify",
  73. "imagekit",
  74. "storages",
  75. "taggit",
  76. "rest_framework.authtoken",
  77. "encrypted_field",
  78. "profiles",
  79. "scrobbles",
  80. "videos",
  81. "music",
  82. "podcasts",
  83. "sports",
  84. "books",
  85. "boardgames",
  86. "bricksets",
  87. "videogames",
  88. "locations",
  89. "webpages",
  90. "tasks",
  91. "trails",
  92. "beers",
  93. "lifeevents",
  94. "moods",
  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. db_str = ""
  141. if "sqlite" in DATABASES["default"]["ENGINE"]:
  142. db_str = f"Connected to sqlite@{DATABASES['default']['NAME']}"
  143. if "postgresql" in DATABASES["default"]["ENGINE"]:
  144. db_str = f"Connected to postgres@{DATABASES['default']['HOST']}/{DATABASES['default']['NAME']}"
  145. if db_str:
  146. print(db_str)
  147. CACHES = {
  148. "default": {
  149. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  150. "LOCATION": "unique-snowflake",
  151. }
  152. }
  153. if REDIS_URL:
  154. CACHES["default"]["BACKEND"] = "django_redis.cache.RedisCache"
  155. CACHES["default"]["LOCATION"] = REDIS_URL
  156. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  157. AUTHENTICATION_BACKENDS = [
  158. "django.contrib.auth.backends.ModelBackend",
  159. "allauth.account.auth_backends.AuthenticationBackend",
  160. ]
  161. # We have to ignore content negotiation because Jellyfin is a bad actor
  162. REST_FRAMEWORK = {
  163. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  164. "DEFAULT_AUTHENTICATION_CLASSES": [
  165. "rest_framework.authentication.TokenAuthentication",
  166. "rest_framework.authentication.SessionAuthentication",
  167. ],
  168. "DEFAULT_CONTENT_NEGOTIATION_CLASS": "vrobbler.negotiation.IgnoreClientContentNegotiation",
  169. "DEFAULT_FILTER_BACKENDS": [
  170. "django_filters.rest_framework.DjangoFilterBackend"
  171. ],
  172. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  173. "PAGE_SIZE": 200,
  174. }
  175. LOGIN_REDIRECT_URL = "/"
  176. AUTH_PASSWORD_VALIDATORS = [
  177. {
  178. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  179. },
  180. {
  181. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  182. },
  183. {
  184. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  185. },
  186. {
  187. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  188. },
  189. ]
  190. # Internationalization
  191. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  192. LANGUAGE_CODE = "en-us"
  193. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")
  194. USE_I18N = True
  195. USE_TZ = True
  196. # Static files (CSS, JavaScript, Images)
  197. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  198. #
  199. from storages.backends import s3boto3
  200. USE_S3_STORAGE = os.getenv("VROBBLER_USE_S3", "False").lower() in TRUTHY
  201. if USE_S3_STORAGE:
  202. AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL", "")
  203. AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME", "")
  204. AWS_S3_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
  205. AWS_S3_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
  206. S3_ROOT = "/".join([AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME])
  207. print(f"Storing media on S3 at {S3_ROOT}")
  208. DEFAULT_FILE_STORAGE = "vrobbler.storages.MediaStorage"
  209. STATICFILES_STORAGE = "vrobbler.storages.StaticStorage"
  210. STATIC_URL = S3_ROOT + "/static/"
  211. MEDIA_URL = S3_ROOT + "/media/"
  212. else:
  213. STATIC_ROOT = os.getenv(
  214. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  215. )
  216. MEDIA_ROOT = os.getenv(
  217. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  218. )
  219. STATIC_URL = os.getenv("VROBBLER_STATIC_URL", "/static/")
  220. MEDIA_URL = os.getenv("VROBBLER_MEDIA_URL", "/media/")
  221. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", "false").lower() in TRUTHY
  222. LOG_TYPE = "json" if JSON_LOGGING else "log"
  223. default_level = "INFO"
  224. if DEBUG:
  225. default_level = "DEBUG"
  226. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  227. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  228. LOGGING = {
  229. "version": 1,
  230. "disable_existing_loggers": False,
  231. "root": {
  232. "handlers": ["console", "file"],
  233. "level": LOG_LEVEL,
  234. "propagate": True,
  235. },
  236. "formatters": {
  237. "color": {
  238. "()": "colorlog.ColoredFormatter",
  239. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  240. # the beautiful alignment produced below
  241. "format": "\r"
  242. "{log_color}{levelname:8s}{reset} "
  243. "{bold_cyan}{name}{reset}:"
  244. "{fg_bold_red}{lineno}{reset} "
  245. "{thin_yellow}{funcName} "
  246. "{thin_white}{message}"
  247. "{reset}",
  248. "style": "{",
  249. },
  250. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  251. "json": {
  252. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  253. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  254. },
  255. },
  256. "handlers": {
  257. "console": {
  258. "class": "logging.StreamHandler",
  259. "formatter": "color",
  260. "level": LOG_LEVEL,
  261. },
  262. "null": {
  263. "class": "logging.NullHandler",
  264. "level": LOG_LEVEL,
  265. },
  266. "sql": {
  267. "class": "logging.handlers.RotatingFileHandler",
  268. "filename": "".join([LOG_FILE_PATH, "vrobbler_sql.", LOG_TYPE]),
  269. "formatter": LOG_TYPE,
  270. "level": LOG_LEVEL,
  271. },
  272. "file": {
  273. "class": "logging.handlers.RotatingFileHandler",
  274. "filename": "".join([LOG_FILE_PATH, "vrobbler.", LOG_TYPE]),
  275. "formatter": LOG_TYPE,
  276. "level": LOG_LEVEL,
  277. },
  278. },
  279. "loggers": {
  280. # Quiet down our console a little
  281. "django": {
  282. "handlers": ["null"],
  283. "propagate": True,
  284. },
  285. "django.db.backends": {"handlers": ["null"]},
  286. "django.server": {"handlers": ["null"]},
  287. "pylast": {"handlers": ["null"], "propagate": False},
  288. "musicbrainzngs": {"handlers": ["null"], "propagate": False},
  289. "httpx": {"handlers": ["null"], "propagate": False},
  290. "vrobbler": {
  291. "handlers": ["console"],
  292. "propagate": False,
  293. },
  294. },
  295. }
  296. LOG_TO_CONSOLE = (
  297. os.getenv("VROBBLER_LOG_TO_CONSOLE", "false").lower() in TRUTHY
  298. )
  299. if LOG_TO_CONSOLE:
  300. LOGGING["loggers"]["django"]["handlers"] = ["console"]
  301. LOGGING["loggers"]["vrobbler"]["handlers"] = ["console"]