config.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import logging
  2. import os
  3. import re as _re
  4. from pathlib import Path
  5. from pydantic_settings import BaseSettings
  6. # Application version - single source of truth
  7. APP_VERSION = "0.2.4.3"
  8. GITHUB_REPO = "maziggy/bambuddy"
  9. BUG_REPORT_RELAY_URL = os.environ.get("BUG_REPORT_RELAY_URL", "https://bambuddy.cool/api/bug-report")
  10. # App directory - where the application is installed (for static files)
  11. _app_dir = Path(__file__).resolve().parent.parent.parent.parent
  12. # Data directory - for persistent data (database, archives)
  13. # Use DATA_DIR env var if set (Docker), otherwise use project root (local dev)
  14. _data_dir_env = os.environ.get("DATA_DIR")
  15. _data_dir = Path(_data_dir_env) if _data_dir_env else _app_dir
  16. # Plate calibration directory - special handling to maintain backwards compatibility
  17. # Docker: DATA_DIR/plate_calibration (e.g., /data/plate_calibration)
  18. # Local dev: project_root/data/plate_calibration (original location)
  19. _plate_cal_dir = Path(_data_dir_env) / "plate_calibration" if _data_dir_env else _app_dir / "data" / "plate_calibration"
  20. # Log directory - use LOG_DIR env var if set, otherwise use app_dir/logs
  21. _log_dir_env = os.environ.get("LOG_DIR")
  22. _log_dir = Path(_log_dir_env) if _log_dir_env else _app_dir / "logs"
  23. def _migrate_database() -> Path:
  24. """Migrate database from old name to new name if needed."""
  25. old_db = _data_dir / "bambutrack.db"
  26. new_db = _data_dir / "bambuddy.db"
  27. # If old database exists and new one doesn't, rename it
  28. if old_db.exists() and not new_db.exists():
  29. try:
  30. old_db.rename(new_db)
  31. logging.info("Migrated database: %s -> %s", old_db, new_db)
  32. except Exception as e:
  33. logging.warning("Could not migrate database: %s. Using old location.", e)
  34. return old_db
  35. # If old database exists (and new one now exists too), it was migrated
  36. # If only new exists, use new
  37. # If neither exists, use new (will be created)
  38. return new_db if new_db.exists() or not old_db.exists() else old_db
  39. # External DATABASE_URL takes priority (PostgreSQL support)
  40. _external_db_url = os.environ.get("DATABASE_URL")
  41. # Determine database path (handles migration) — only used for SQLite
  42. _db_path = _migrate_database() if not _external_db_url else None
  43. class Settings(BaseSettings):
  44. app_name: str = "Bambuddy"
  45. debug: bool = False # Default to production mode
  46. # Paths
  47. base_dir: Path = _data_dir # For backwards compatibility
  48. # `app_dir` is where the source code is checked out — distinct from `base_dir`
  49. # on native installs where DATA_DIR is set to a sibling like INSTALL_PATH/data.
  50. # Use this when you need the working tree (requirements.txt, frontend/, etc.)
  51. # rather than the data dir. On Docker / local dev where DATA_DIR is unset,
  52. # app_dir == base_dir.
  53. app_dir: Path = _app_dir
  54. archive_dir: Path = _data_dir / "archive"
  55. plate_calibration_dir: Path = _plate_cal_dir # Plate detection references
  56. static_dir: Path = _app_dir / "static" # Static files are part of app, not data
  57. log_dir: Path = _log_dir
  58. database_url: str = _external_db_url or f"sqlite+aiosqlite:///{_db_path}"
  59. # Logging
  60. log_level: str = "INFO" # Override with LOG_LEVEL env var or DEBUG=true
  61. log_to_file: bool = True # Set to false to disable file logging
  62. # API
  63. api_prefix: str = "/api/v1"
  64. # Slicer API sidecars. Defaults match the docker-compose.yml ports in the
  65. # orca-slicer-api fork (https://github.com/maziggy/orca-slicer-api):
  66. # OrcaSlicer → port 3003 (default profile)
  67. # BambuStudio → port 3001 (built locally via Dockerfile.bambu-studio)
  68. # The slice route picks which one based on the user's preferred_slicer
  69. # setting.
  70. slicer_api_url: str = "http://localhost:3003"
  71. bambu_studio_api_url: str = "http://localhost:3001"
  72. class Config:
  73. env_file = ".env"
  74. env_file_encoding = "utf-8"
  75. # Don't reject unknown env vars — MFA_ENCRYPTION_KEY (#1219) and other
  76. # operational env vars are read directly by their owning modules and
  77. # never declared as Settings fields.
  78. extra = "ignore"
  79. settings = Settings()
  80. # S6: Warn on unknown MFA_*/BAMBUDDY_* env vars so typos like MFA_ENCYPTION_KEY
  81. # are not silently swallowed by ``extra = "ignore"``. The original Pydantic
  82. # behaviour rejected them outright and broke startup (#1219); we now accept
  83. # them but log every unrecognised one at INFO so operators can spot mistakes.
  84. _INTENTIONAL_UNSETTINGS = {
  85. "MFA_ENCRYPTION_KEY", # encryption.py reads this directly
  86. "DATA_DIR", # paths.py / config.py
  87. "DATABASE_URL", # config.py (above)
  88. "LOG_DIR", # config.py (above)
  89. "LOG_LEVEL", # main.py logging setup
  90. "BUG_REPORT_RELAY_URL", # config.py (above)
  91. }
  92. _known_settings_fields = {f.upper() for f in settings.model_fields}
  93. for _env_key in os.environ:
  94. if _re.match(r"^(MFA_|BAMBUDDY_)", _env_key, _re.IGNORECASE):
  95. _norm = _env_key.upper()
  96. if _norm not in _known_settings_fields and _norm not in _INTENTIONAL_UNSETTINGS:
  97. logging.info(
  98. "Unknown env var %r — not a declared Settings field. Possible typo? Recognised operational vars: %s",
  99. _env_key,
  100. sorted(_INTENTIONAL_UNSETTINGS),
  101. )
  102. # Ensure directories exist
  103. settings.archive_dir.mkdir(parents=True, exist_ok=True)
  104. settings.plate_calibration_dir.mkdir(parents=True, exist_ok=True)
  105. settings.static_dir.mkdir(exist_ok=True)
  106. if settings.log_to_file:
  107. settings.log_dir.mkdir(exist_ok=True)