Skip to content

Home Information - Your home, your data, organized.

Python
13.3 KB
Raw Blame
"""
Django settings for hi project.

Generated by 'django-admin startproject' using Django 4.2.15.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os
import sys

from hi.environment.server import EnvironmentSettings

ENV = EnvironmentSettings.get()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = ENV.SECRET_KEY

DJANGO_SUPERUSER_EMAIL = ENV.DJANGO_SUPERUSER_EMAIL
DJANGO_SUPERUSER_PASSWORD = ENV.DJANGO_SUPERUSER_PASSWORD

SITE_ID = ENV.SITE_ID
SITE_DOMAIN = ENV.SITE_DOMAIN
SITE_NAME = ENV.SITE_NAME

ALLOWED_HOSTS = ENV.ALLOWED_HOSTS

CORS_ALLOWED_ORIGINS = ENV.CORS_ALLOWED_ORIGINS

# django-csp 4.x dict-based config. Directive keys are kebab-case
# without the ``CSP_`` prefix (see django-csp migration guide). Each
# value concatenates with ENV.EXTRA_CSP_URLS so deployments can extend
# the allow-lists without editing source.
CONTENT_SECURITY_POLICY = {
    'DIRECTIVES': {
        'default-src': (
            "'self'",
            'data:',
        ) + ENV.EXTRA_CSP_URLS,
        'connect-src': (
            "'self'",
        ) + ENV.EXTRA_CSP_URLS,
        'frame-src': (
            "'self'",
        ) + ENV.EXTRA_CSP_URLS,
        'script-src': (
            "'self'",
            "'unsafe-inline'",
            "'unsafe-eval'",
        ) + ENV.EXTRA_CSP_URLS,
        'style-src': (
            "'self'",
            "'unsafe-inline'",
            "'unsafe-eval'",
        ) + ENV.EXTRA_CSP_URLS,
        'media-src': (
            "'self'",
            "'unsafe-inline'",
            "'unsafe-eval'",
            'data:',
        ) + ENV.EXTRA_CSP_URLS,
        'img-src': (
            "'self'",
            'data:',
        ) + ENV.EXTRA_CSP_URLS,
        'child-src': (
            "'self'",
        ) + ENV.EXTRA_CSP_URLS,
        'font-src': (
            "'self'",
            'data:',
        ) + ENV.EXTRA_CSP_URLS,
        'worker-src': (
            "'self'",
        ) + ENV.EXTRA_CSP_URLS,
    },
}

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pipeline',
    'django.contrib.humanize',
    'constance',
    'custom',
    'hi.environment',
    'hi.apps.common',
    'hi.apps.user',
    'hi.apps.config',
    'hi.apps.console',
    'hi.apps.attribute',
    'hi.apps.location',
    'hi.apps.entity',
    'hi.apps.collection',
    'hi.apps.sense',
    'hi.apps.control',
    'hi.apps.event',
    'hi.apps.notify',
    'hi.apps.alert',
    'hi.apps.audio',
    'hi.apps.security',
    'hi.apps.edit',
    'hi.apps.api',
    'hi.apps.system',
    'hi.apps.monitor',
    'hi.apps.weather',
    'hi.integrations',
    'hi.services.zoneminder',
    'hi.services.hass',
    'hi.services.homebox',
    'hi.services.frigate',
    'hi.services.paperless',
    'hi.services.immich',
    'hi.apps.profiles',
]

MIDDLEWARE = [
    'csp.middleware.CSPMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'hi.middleware.NoStoreMiddleware',
    'hi.middleware.ExceptionMiddleware',
    'hi.middleware.ViewMiddleware',
    'hi.apps.console.middleware.ConsoleLockMiddleware',
    'hi.apps.user.middleware.AuthenticationMiddleware',
]

ROOT_URLCONF = 'hi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ os.path.join(BASE_DIR, "templates") ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'hi.context_processors.constants_context',
                'hi.environment.context_processors.client_config',
                'hi.apps.console.context_processors.settings_context',
                'hi.apps.audio.context_processors.audio_context',
                'hi.apps.profiles.context_processors.profiles_context',
            ],
        },
    },
]

WSGI_APPLICATION = 'hi.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join( ENV.DATABASES_NAME_PATH, 'hi.sqlite3' ),
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# True when invoked as ``manage.py test`` (WSGI / gunicorn / runserver /
# migrate / shell do not match, so production processes are unaffected).
# Drives test-only behavior: the fast password hasher below, plus the
# synchronous-in-test guards in email_utils, metrics, and
# DelayedSignalProcessor.
UNIT_TESTING = ( sys.argv[1:2] == ['test'] )

# Default PBKDF2 hashing is hundreds of ms per call by design; for tests
# (where many setUps create a user) it dominates wall time. Swap to a
# fast hasher under test.
if UNIT_TESTING:
    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.MD5PasswordHasher',
    ]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_ROOT = ENV.MEDIA_ROOT
MEDIA_URL = '/media/'

PIPELINE = {
    'DISABLE_WRAPPER': True,  # Important since some scripts assume global scope

    'CSS_COMPRESSOR': None,  # Removed django-pipeline-csscompressor (unmaintained since 2016)
    'JS_COMPRESSOR': None,
    
    'STYLESHEETS': {
        'css_head': {
            'source_filenames': (
                'bootstrap/css/bootstrap.css',
                'css/main.css',
                'css/icons.css',
                'css/attribute.css',
                'css/stream-browser.css',
                'css/control.css',
                'state_panels/fallback/fallback.css',
                'state_panels/smoke_detector/smoke_detector.css',
                'state_panels/camera/camera.css',
                'state_panels/thermostat/thermostat.css',
            ),
            'output_filename': 'css/css_head.css',
        },
        'css_location_svg_edit': {
            'source_filenames': (
                'css/location-svg-edit.css',
            ),
            'output_filename': 'css/css_location_svg_edit.css',
        },
    },
    'JAVASCRIPT': {
        'js_before_content': {
            'source_filenames': (
                'js/jquery-3.7.0.min.js',
                'js/cookie.js',
                'js/antinode.js',
                'js/autosize.min.js',
                'js/main.js',
                'js/entity_state_status.js',
                'state_panels/fallback/fallback.js',
            ),
            'output_filename': 'js/js_before_content.js',
        },
        'js_hi_grid_header_content': {
            'source_filenames': (
                'js/watchdog.js',
                'js/settings.js',
                'js/audio.js',
                'js/video-timeline.js',
                'js/attr.js',
                'js/attr-dirty-tracking.js',
                'js/external-reference-picker.js',
                'js/external-references.js',
            ),
            'output_filename': 'js/js_hi_grid_header_content.js',
        },
        'js_after_content': {
            'source_filenames': (
                'js/popper.min.js',
                'bootstrap/js/bootstrap.js',
                'js/entity-picker.js',
            ),
            'output_filename': 'js/js_after_content.js',
        },
        'js_hi_grid_content': {
            'source_filenames': (
                'js/svg-utils.js',
                'state_panels/thermostat/thermostat.js',
                'js/status.js',
                'js/auto-view.js',
                'js/edit-dragdrop.js',
                'js/svg-icon-core.js',
                'js/svg-path-core.js',
                'js/svg-pan-zoom-core.js',
                'js/svg-entity-edit.js',
                'js/svg-entity-event-listeners.js',
            ),
            'output_filename': 'js/js_hi_grid_content.js',
        },
        'js_location_svg_edit': {
            'source_filenames': (
                'js/svg-utils.js',
                'js/svg-pan-zoom-core.js',
                'js/svg-icon-core.js',
                'js/svg-path-core.js',
                'js/svg-bg-edit.js',
                'js/svg-bg-event-listeners.js',
            ),
            'output_filename': 'js/js_location_svg_edit.js',
        },
    }
}

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_COOKIE_AGE = 60 * 60 * 24 * 365  # in seconds
AUTO_LOGOUT = 60 * 24 * 365 * 100  # in minutes

CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
CONSTANCE_DATABASE_CACHE_BACKEND = 'default'
CONSTANCE_DATABASE_PREFIX = 'constance:hi:'

CONSTANCE_CONFIG = {
    'DOWN_FOR_MAINTENANCE': ( False, 'Should we force the down for maintenance page to show?' ),
}

REDIS_HOST = ENV.REDIS_HOST
REDIS_PORT = ENV.REDIS_PORT

CACHES = {
    'default': {
        # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': [
            f'redis://{REDIS_HOST}:{REDIS_PORT}',
        ],
        "KEY_PREFIX": 'main:',
    }
}

TEST_RUNNER = 'hi.testing.runner.HiTestRunner'


AUTH_USER_MODEL = "custom.CustomUser"
SUPPRESS_AUTHENTICATION = ENV.SUPPRESS_AUTHENTICATION

# ====================
# Transactional Emails

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_SUBJECT_PREFIX = "%s " % ENV.EMAIL_SUBJECT_PREFIX
DEFAULT_FROM_EMAIL = ENV.DEFAULT_FROM_EMAIL
SERVER_EMAIL = ENV.SERVER_EMAIL
FROM_EMAIL_NAME = "Home Information"

# Normal Settings
EMAIL_HOST = ENV.EMAIL_HOST
try:
    EMAIL_PORT = ENV.EMAIL_PORT
except (TypeError, ValueError):
    EMAIL_PORT = 587
    
EMAIL_HOST_USER = ENV.EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = ENV.EMAIL_HOST_PASSWORD
EMAIL_TIMEOUT = 10  # In seconds

EMAIL_USE_TLS = ENV.EMAIL_USE_TLS
EMAIL_USE_SSL = ENV.EMAIL_USE_SSL
    
# Needed when sending emails in background tasks since HttpRequest not
# available. Override this for development/testing/staging.
#
BASE_URL_FOR_EMAIL_LINKS = f'http://{SITE_DOMAIN}'


# ====================
# Development-related Settings
# (override in development.py, not here)


# In development and debugging, because the background javascript is
# polling frequently, this clutters up the console with log messages which
# makes it hard to sort through the other things logging.  This allows
# suppressing those via a logging filter.  This only applies if the logging
# configuration is using that special filter (in hi.log_filters".
#
SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING = True

# In development and debugging, the debug noise and interference from the
# background periodic monitoring tasks can be a problem. This gives a way
# to turn them off with one setting.
#
SUPPRESS_MONITORS = False

# ====================
# Development Testing Injection Points
# (enabled/disabled in environment-specific settings)

# When enabled in DEBUG mode, allows injecting test data into API responses
# for frontend testing without changing backend state. Never enabled in production.
DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False

# For testing UI error display of the various attribute editing form errors.
DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False

# Per-state tracing for debugging value flow across any
# integration (HA, ZM, etc.) and the simulator. The master switch
# is ``DEBUG_TRACE_STATE``; main-code call sites short-circuit on
# it for zero overhead when off. When on, the trace dispatcher
# consults ``DEBUG_TRACE_INTEGRATION_NAMES`` (matched against
# the integration_name with any ``~suffix`` stripped, so a single
# entry like ``cover.x`` catches its substate variants) and
# ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs) for
# granularity. ``settings.DEBUG`` must also be True. See
# ``hi.testing.dev_overrides.StateTraceManager``.
DEBUG_TRACE_STATE = False
DEBUG_TRACE_INTEGRATION_NAMES = [ ]  # strings / integration_key.name
DEBUG_TRACE_HI_ENTITY_STATE_IDS = [ ]  # ints / EntityState database ids