settings-testing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "lifeevents",
  91. "moods",
  92. "mathfilters",
  93. "rest_framework",
  94. "allauth",
  95. "allauth.account",
  96. "allauth.socialaccount",
  97. "django_celery_results",
  98. ]
  99. SITE_ID = 1
  100. MIDDLEWARE = [
  101. "django.middleware.security.SecurityMiddleware",
  102. "django.contrib.sessions.middleware.SessionMiddleware",
  103. "django.middleware.common.CommonMiddleware",
  104. "django.middleware.csrf.CsrfViewMiddleware",
  105. "django.contrib.auth.middleware.AuthenticationMiddleware",
  106. "django.contrib.messages.middleware.MessageMiddleware",
  107. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  108. "django.middleware.gzip.GZipMiddleware",
  109. ]
  110. ROOT_URLCONF = "vrobbler.urls"
  111. TEMPLATES = [
  112. {
  113. "BACKEND": "django.template.backends.django.DjangoTemplates",
  114. "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
  115. "APP_DIRS": True,
  116. "OPTIONS": {
  117. "context_processors": [
  118. "django.template.context_processors.debug",
  119. "django.template.context_processors.request",
  120. "django.contrib.auth.context_processors.auth",
  121. "django.contrib.messages.context_processors.messages",
  122. "videos.context_processors.video_lists",
  123. "music.context_processors.music_lists",
  124. "scrobbles.context_processors.now_playing",
  125. ],
  126. },
  127. },
  128. ]
  129. MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
  130. WSGI_APPLICATION = "vrobbler.wsgi.application"
  131. DATABASES = {
  132. "default": dj_database_url.config(
  133. default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
  134. conn_max_age=600,
  135. ),
  136. }
  137. db_str = ""
  138. if "sqlite" in DATABASES["default"]["ENGINE"]:
  139. db_str = f"Connected to sqlite@{DATABASES['default']['NAME']}"
  140. if "postgresql" in DATABASES["default"]["ENGINE"]:
  141. db_str = f"Connected to postgres@{DATABASES['default']['HOST']}/{DATABASES['default']['NAME']}"
  142. if db_str:
  143. print(db_str)
  144. CACHES = {
  145. "default": {
  146. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  147. "LOCATION": "unique-snowflake",
  148. }
  149. }
  150. if REDIS_URL:
  151. CACHES["default"]["BACKEND"] = "django_redis.cache.RedisCache"
  152. CACHES["default"]["LOCATION"] = REDIS_URL
  153. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  154. AUTHENTICATION_BACKENDS = [
  155. "django.contrib.auth.backends.ModelBackend",
  156. "allauth.account.auth_backends.AuthenticationBackend",
  157. ]
  158. # We have to ignore content negotiation because Jellyfin is a bad actor
  159. REST_FRAMEWORK = {
  160. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  161. "DEFAULT_AUTHENTICATION_CLASSES": [
  162. "rest_framework.authentication.TokenAuthentication",
  163. "rest_framework.authentication.SessionAuthentication",
  164. ],
  165. "DEFAULT_CONTENT_NEGOTIATION_CLASS": "vrobbler.negotiation.IgnoreClientContentNegotiation",
  166. "DEFAULT_FILTER_BACKENDS": [
  167. "django_filters.rest_framework.DjangoFilterBackend"
  168. ],
  169. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  170. "PAGE_SIZE": 200,
  171. }
  172. LOGIN_REDIRECT_URL = "/"
  173. AUTH_PASSWORD_VALIDATORS = [
  174. {
  175. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  176. },
  177. {
  178. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  179. },
  180. {
  181. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  182. },
  183. {
  184. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  185. },
  186. ]
  187. # Internationalization
  188. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  189. LANGUAGE_CODE = "en-us"
  190. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")
  191. USE_I18N = True
  192. USE_TZ = True
  193. # Static files (CSS, JavaScript, Images)
  194. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  195. #
  196. from storages.backends import s3boto3
  197. USE_S3_STORAGE = os.getenv("VROBBLER_USE_S3", "False").lower() in TRUTHY
  198. if USE_S3_STORAGE:
  199. AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL", "")
  200. AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME", "")
  201. AWS_S3_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
  202. AWS_S3_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
  203. S3_ROOT = "/".join([AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME])
  204. print(f"Storing media on S3 at {S3_ROOT}")
  205. DEFAULT_FILE_STORAGE = "vrobbler.storages.MediaStorage"
  206. STATICFILES_STORAGE = "vrobbler.storages.StaticStorage"
  207. STATIC_URL = S3_ROOT + "/static/"
  208. MEDIA_URL = S3_ROOT + "/media/"
  209. else:
  210. STATIC_ROOT = os.getenv(
  211. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  212. )
  213. MEDIA_ROOT = os.getenv(
  214. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  215. )
  216. STATIC_URL = os.getenv("VROBBLER_STATIC_URL", "/static/")
  217. MEDIA_URL = os.getenv("VROBBLER_MEDIA_URL", "/media/")
  218. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", "false").lower() in TRUTHY
  219. LOG_TYPE = "json" if JSON_LOGGING else "log"
  220. default_level = "INFO"
  221. if DEBUG:
  222. default_level = "DEBUG"
  223. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  224. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  225. LOGGING = {
  226. "version": 1,
  227. "disable_existing_loggers": False,
  228. "root": {
  229. "handlers": ["console", "file"],
  230. "level": LOG_LEVEL,
  231. "propagate": True,
  232. },
  233. "formatters": {
  234. "color": {
  235. "()": "colorlog.ColoredFormatter",
  236. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  237. # the beautiful alignment produced below
  238. "format": "\r"
  239. "{log_color}{levelname:8s}{reset} "
  240. "{bold_cyan}{name}{reset}:"
  241. "{fg_bold_red}{lineno}{reset} "
  242. "{thin_yellow}{funcName} "
  243. "{thin_white}{message}"
  244. "{reset}",
  245. "style": "{",
  246. },
  247. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  248. "json": {
  249. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  250. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  251. },
  252. },
  253. "handlers": {
  254. "console": {
  255. "class": "logging.StreamHandler",
  256. "formatter": "color",
  257. "level": LOG_LEVEL,
  258. },
  259. "null": {
  260. "class": "logging.NullHandler",
  261. "level": LOG_LEVEL,
  262. },
  263. "sql": {
  264. "class": "logging.handlers.RotatingFileHandler",
  265. "filename": "".join([LOG_FILE_PATH, "vrobbler_sql.", LOG_TYPE]),
  266. "formatter": LOG_TYPE,
  267. "level": LOG_LEVEL,
  268. },
  269. "file": {
  270. "class": "logging.handlers.RotatingFileHandler",
  271. "filename": "".join([LOG_FILE_PATH, "vrobbler.", LOG_TYPE]),
  272. "formatter": LOG_TYPE,
  273. "level": LOG_LEVEL,
  274. },
  275. },
  276. "loggers": {
  277. # Quiet down our console a little
  278. "django": {
  279. "handlers": ["null"],
  280. "propagate": True,
  281. },
  282. "django.db.backends": {"handlers": ["null"]},
  283. "django.server": {"handlers": ["null"]},
  284. "pylast": {"handlers": ["null"], "propagate": False},
  285. "musicbrainzngs": {"handlers": ["null"], "propagate": False},
  286. "httpx": {"handlers": ["null"], "propagate": False},
  287. "vrobbler": {
  288. "handlers": ["console"],
  289. "propagate": False,
  290. },
  291. },
  292. }
  293. LOG_TO_CONSOLE = (
  294. os.getenv("VROBBLER_LOG_TO_CONSOLE", "false").lower() in TRUTHY
  295. )
  296. if LOG_TO_CONSOLE:
  297. LOGGING["loggers"]["django"]["handlers"] = ["console"]
  298. LOGGING["loggers"]["vrobbler"]["handlers"] = ["console"]