settings.py 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. import io
  2. import json
  3. import logging
  4. import zipfile
  5. from datetime import datetime
  6. from pathlib import Path
  7. from fastapi import APIRouter, Depends, File, Query, UploadFile
  8. from fastapi.responses import JSONResponse, StreamingResponse
  9. from sqlalchemy import select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.config import settings as app_settings
  12. from backend.app.core.database import get_db
  13. from backend.app.models.api_key import APIKey
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.external_link import ExternalLink
  16. from backend.app.models.filament import Filament
  17. from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
  18. from backend.app.models.notification import NotificationProvider
  19. from backend.app.models.notification_template import NotificationTemplate
  20. from backend.app.models.pending_upload import PendingUpload
  21. from backend.app.models.print_queue import PrintQueueItem
  22. from backend.app.models.printer import Printer
  23. from backend.app.models.project import Project
  24. from backend.app.models.project_bom import ProjectBOMItem
  25. from backend.app.models.settings import Settings
  26. from backend.app.models.smart_plug import SmartPlug
  27. from backend.app.models.user import User
  28. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  29. from backend.app.services.printer_manager import printer_manager
  30. from backend.app.services.spoolman import init_spoolman_client
  31. logger = logging.getLogger(__name__)
  32. router = APIRouter(prefix="/settings", tags=["settings"])
  33. # Default settings
  34. DEFAULT_SETTINGS = AppSettings()
  35. async def get_setting(db: AsyncSession, key: str) -> str | None:
  36. """Get a single setting value by key."""
  37. result = await db.execute(select(Settings).where(Settings.key == key))
  38. setting = result.scalar_one_or_none()
  39. return setting.value if setting else None
  40. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  41. """Set a single setting value."""
  42. from sqlalchemy import func
  43. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  44. # Use upsert (INSERT ... ON CONFLICT UPDATE) for reliability
  45. stmt = sqlite_insert(Settings).values(key=key, value=value)
  46. stmt = stmt.on_conflict_do_update(index_elements=["key"], set_={"value": value, "updated_at": func.now()})
  47. await db.execute(stmt)
  48. @router.get("", response_model=AppSettings)
  49. @router.get("/", response_model=AppSettings)
  50. async def get_settings(db: AsyncSession = Depends(get_db)):
  51. """Get all application settings."""
  52. settings_dict = DEFAULT_SETTINGS.model_dump()
  53. # Load saved settings from database
  54. result = await db.execute(select(Settings))
  55. db_settings = result.scalars().all()
  56. for setting in db_settings:
  57. if setting.key in settings_dict:
  58. # Parse the value based on the expected type
  59. if setting.key in [
  60. "auto_archive",
  61. "save_thumbnails",
  62. "capture_finish_photo",
  63. "spoolman_enabled",
  64. "check_updates",
  65. "virtual_printer_enabled",
  66. "ftp_retry_enabled",
  67. "mqtt_enabled",
  68. "mqtt_use_tls",
  69. "ha_enabled",
  70. "per_printer_mapping_expanded",
  71. ]:
  72. settings_dict[setting.key] = setting.value.lower() == "true"
  73. elif setting.key in [
  74. "default_filament_cost",
  75. "energy_cost_per_kwh",
  76. "ams_temp_good",
  77. "ams_temp_fair",
  78. "library_disk_warning_gb",
  79. ]:
  80. settings_dict[setting.key] = float(setting.value)
  81. elif setting.key in [
  82. "ams_humidity_good",
  83. "ams_humidity_fair",
  84. "ams_history_retention_days",
  85. "ftp_retry_count",
  86. "ftp_retry_delay",
  87. "mqtt_port",
  88. ]:
  89. settings_dict[setting.key] = int(setting.value)
  90. elif setting.key == "default_printer_id":
  91. # Handle nullable integer
  92. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  93. else:
  94. settings_dict[setting.key] = setting.value
  95. return AppSettings(**settings_dict)
  96. @router.put("/", response_model=AppSettings)
  97. async def update_settings(
  98. settings_update: AppSettingsUpdate,
  99. db: AsyncSession = Depends(get_db),
  100. ):
  101. """Update application settings."""
  102. update_data = settings_update.model_dump(exclude_unset=True)
  103. # Check if any MQTT settings are being updated
  104. mqtt_keys = {
  105. "mqtt_enabled",
  106. "mqtt_broker",
  107. "mqtt_port",
  108. "mqtt_username",
  109. "mqtt_password",
  110. "mqtt_topic_prefix",
  111. "mqtt_use_tls",
  112. }
  113. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  114. for key, value in update_data.items():
  115. # Convert value to string for storage
  116. if isinstance(value, bool):
  117. str_value = "true" if value else "false"
  118. elif value is None:
  119. str_value = "None"
  120. else:
  121. str_value = str(value)
  122. await set_setting(db, key, str_value)
  123. await db.commit()
  124. # Expire all objects to ensure fresh reads after commit
  125. db.expire_all()
  126. # Reconfigure MQTT relay if any MQTT settings changed
  127. if mqtt_updated:
  128. try:
  129. from backend.app.services.mqtt_relay import mqtt_relay
  130. mqtt_settings = {
  131. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  132. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  133. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  134. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  135. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  136. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  137. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  138. }
  139. await mqtt_relay.configure(mqtt_settings)
  140. except Exception:
  141. pass # Don't fail the settings update if MQTT reconfiguration fails
  142. # Return updated settings
  143. return await get_settings(db)
  144. @router.patch("/", response_model=AppSettings)
  145. @router.patch("", response_model=AppSettings)
  146. async def patch_settings(
  147. settings_update: AppSettingsUpdate,
  148. db: AsyncSession = Depends(get_db),
  149. ):
  150. """Partially update application settings (same as PUT, for REST compatibility)."""
  151. return await update_settings(settings_update, db)
  152. @router.post("/reset", response_model=AppSettings)
  153. async def reset_settings(db: AsyncSession = Depends(get_db)):
  154. """Reset all settings to defaults."""
  155. # Delete all settings
  156. result = await db.execute(select(Settings))
  157. for setting in result.scalars().all():
  158. await db.delete(setting)
  159. await db.commit()
  160. return DEFAULT_SETTINGS
  161. @router.get("/check-ffmpeg")
  162. async def check_ffmpeg():
  163. """Check if ffmpeg is installed and available."""
  164. from backend.app.services.camera import get_ffmpeg_path
  165. ffmpeg_path = get_ffmpeg_path()
  166. return {
  167. "installed": ffmpeg_path is not None,
  168. "path": ffmpeg_path,
  169. }
  170. @router.get("/spoolman")
  171. async def get_spoolman_settings(db: AsyncSession = Depends(get_db)):
  172. """Get Spoolman integration settings."""
  173. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  174. spoolman_url = await get_setting(db, "spoolman_url") or ""
  175. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  176. return {
  177. "spoolman_enabled": spoolman_enabled,
  178. "spoolman_url": spoolman_url,
  179. "spoolman_sync_mode": spoolman_sync_mode,
  180. }
  181. @router.put("/spoolman")
  182. async def update_spoolman_settings(
  183. settings: dict,
  184. db: AsyncSession = Depends(get_db),
  185. ):
  186. """Update Spoolman integration settings."""
  187. if "spoolman_enabled" in settings:
  188. await set_setting(db, "spoolman_enabled", settings["spoolman_enabled"])
  189. if "spoolman_url" in settings:
  190. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  191. if "spoolman_sync_mode" in settings:
  192. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  193. await db.commit()
  194. db.expire_all()
  195. # Return updated settings
  196. return await get_spoolman_settings(db)
  197. @router.get("/backup")
  198. async def export_backup(
  199. db: AsyncSession = Depends(get_db),
  200. include_settings: bool = Query(True, description="Include app settings"),
  201. include_notifications: bool = Query(True, description="Include notification providers"),
  202. include_templates: bool = Query(True, description="Include notification templates"),
  203. include_smart_plugs: bool = Query(True, description="Include smart plugs"),
  204. include_external_links: bool = Query(True, description="Include external sidebar links"),
  205. include_printers: bool = Query(False, description="Include printers (without access codes)"),
  206. include_plate_calibration: bool = Query(False, description="Include plate detection reference images"),
  207. include_filaments: bool = Query(False, description="Include filament inventory"),
  208. include_maintenance: bool = Query(
  209. False, description="Include maintenance types, per-printer settings, and history"
  210. ),
  211. include_print_queue: bool = Query(False, description="Include print queue items"),
  212. include_archives: bool = Query(False, description="Include print archive metadata"),
  213. include_projects: bool = Query(False, description="Include projects with BOM items"),
  214. include_pending_uploads: bool = Query(False, description="Include pending virtual printer uploads"),
  215. include_access_codes: bool = Query(False, description="Include printer access codes (security risk!)"),
  216. include_api_keys: bool = Query(False, description="Include API keys (keys will need to be regenerated on import)"),
  217. include_users: bool = Query(
  218. False, description="Include users (passwords not exported - users will need new passwords)"
  219. ),
  220. ):
  221. """Export selected data as JSON backup."""
  222. backup: dict = {
  223. "version": "2.0",
  224. "exported_at": datetime.utcnow().isoformat(),
  225. "included": [],
  226. }
  227. # Settings
  228. if include_settings:
  229. result = await db.execute(select(Settings))
  230. db_settings = result.scalars().all()
  231. backup["settings"] = {s.key: s.value for s in db_settings}
  232. backup["included"].append("settings")
  233. # Notification providers
  234. if include_notifications:
  235. # Build printer ID to serial lookup for cross-system backup
  236. printer_id_to_serial: dict[int, str] = {}
  237. pr_result = await db.execute(select(Printer))
  238. for pr in pr_result.scalars().all():
  239. printer_id_to_serial[pr.id] = pr.serial_number
  240. result = await db.execute(select(NotificationProvider))
  241. providers = result.scalars().all()
  242. backup["notification_providers"] = []
  243. for p in providers:
  244. # Use printer_serial for cross-system compatibility
  245. provider_printer_id = getattr(p, "printer_id", None)
  246. printer_serial = printer_id_to_serial.get(provider_printer_id) if provider_printer_id else None
  247. backup["notification_providers"].append(
  248. {
  249. "name": p.name,
  250. "provider_type": p.provider_type,
  251. "enabled": p.enabled,
  252. "config": json.loads(p.config) if isinstance(p.config, str) else p.config,
  253. "on_print_start": p.on_print_start,
  254. "on_print_complete": p.on_print_complete,
  255. "on_print_failed": p.on_print_failed,
  256. "on_print_stopped": p.on_print_stopped,
  257. "on_print_progress": p.on_print_progress,
  258. "on_printer_offline": p.on_printer_offline,
  259. "on_printer_error": p.on_printer_error,
  260. "on_filament_low": p.on_filament_low,
  261. "on_maintenance_due": p.on_maintenance_due,
  262. "on_ams_humidity_high": getattr(p, "on_ams_humidity_high", False),
  263. "on_ams_temperature_high": getattr(p, "on_ams_temperature_high", False),
  264. "on_ams_ht_humidity_high": getattr(p, "on_ams_ht_humidity_high", False),
  265. "on_ams_ht_temperature_high": getattr(p, "on_ams_ht_temperature_high", False),
  266. "on_plate_not_empty": getattr(p, "on_plate_not_empty", True),
  267. "quiet_hours_enabled": p.quiet_hours_enabled,
  268. "quiet_hours_start": p.quiet_hours_start,
  269. "quiet_hours_end": p.quiet_hours_end,
  270. "daily_digest_enabled": getattr(p, "daily_digest_enabled", False),
  271. "daily_digest_time": getattr(p, "daily_digest_time", None),
  272. "printer_serial": printer_serial,
  273. }
  274. )
  275. backup["included"].append("notification_providers")
  276. # Notification templates
  277. if include_templates:
  278. result = await db.execute(select(NotificationTemplate))
  279. templates = result.scalars().all()
  280. backup["notification_templates"] = []
  281. for t in templates:
  282. backup["notification_templates"].append(
  283. {
  284. "event_type": t.event_type,
  285. "name": t.name,
  286. "title_template": t.title_template,
  287. "body_template": t.body_template,
  288. "is_default": t.is_default,
  289. }
  290. )
  291. backup["included"].append("notification_templates")
  292. # Smart plugs
  293. if include_smart_plugs:
  294. result = await db.execute(select(SmartPlug))
  295. plugs = result.scalars().all()
  296. backup["smart_plugs"] = []
  297. # Build printer ID to serial mapping
  298. printer_id_to_serial: dict[int, str] = {}
  299. pr_result = await db.execute(select(Printer))
  300. for pr in pr_result.scalars().all():
  301. printer_id_to_serial[pr.id] = pr.serial_number
  302. for plug in plugs:
  303. backup["smart_plugs"].append(
  304. {
  305. "name": plug.name,
  306. "plug_type": plug.plug_type,
  307. "ip_address": plug.ip_address,
  308. "ha_entity_id": plug.ha_entity_id,
  309. "ha_power_entity": plug.ha_power_entity,
  310. "ha_energy_today_entity": plug.ha_energy_today_entity,
  311. "ha_energy_total_entity": plug.ha_energy_total_entity,
  312. "printer_serial": printer_id_to_serial.get(plug.printer_id) if plug.printer_id else None,
  313. "enabled": plug.enabled,
  314. "auto_on": plug.auto_on,
  315. "auto_off": plug.auto_off,
  316. "off_delay_mode": plug.off_delay_mode,
  317. "off_delay_minutes": plug.off_delay_minutes,
  318. "off_temp_threshold": plug.off_temp_threshold,
  319. "username": plug.username,
  320. "password": plug.password,
  321. "power_alert_enabled": plug.power_alert_enabled,
  322. "power_alert_high": plug.power_alert_high,
  323. "power_alert_low": plug.power_alert_low,
  324. "schedule_enabled": plug.schedule_enabled,
  325. "schedule_on_time": plug.schedule_on_time,
  326. "schedule_off_time": plug.schedule_off_time,
  327. "show_in_switchbar": plug.show_in_switchbar,
  328. }
  329. )
  330. backup["included"].append("smart_plugs")
  331. # External links
  332. if include_external_links:
  333. result = await db.execute(select(ExternalLink).order_by(ExternalLink.sort_order))
  334. links = result.scalars().all()
  335. backup["external_links"] = []
  336. icons_dir = app_settings.base_dir / "icons"
  337. for link in links:
  338. link_data = {
  339. "name": link.name,
  340. "url": link.url,
  341. "icon": link.icon,
  342. "sort_order": link.sort_order,
  343. }
  344. # Include custom icon file path if exists
  345. if link.custom_icon:
  346. link_data["custom_icon"] = link.custom_icon
  347. icon_path = icons_dir / link.custom_icon
  348. if icon_path.exists():
  349. link_data["custom_icon_path"] = f"icons/{link.custom_icon}"
  350. backup["external_links"].append(link_data)
  351. backup["included"].append("external_links")
  352. # Printers (access codes only included if explicitly requested)
  353. if include_printers:
  354. result = await db.execute(select(Printer))
  355. printers = result.scalars().all()
  356. backup["printers"] = []
  357. for printer in printers:
  358. printer_data = {
  359. "name": printer.name,
  360. "serial_number": printer.serial_number,
  361. "ip_address": printer.ip_address,
  362. "model": printer.model,
  363. "location": printer.location,
  364. "nozzle_count": printer.nozzle_count,
  365. "is_active": printer.is_active,
  366. "auto_archive": printer.auto_archive,
  367. "print_hours_offset": printer.print_hours_offset,
  368. "runtime_seconds": printer.runtime_seconds,
  369. "external_camera_url": printer.external_camera_url,
  370. "external_camera_type": printer.external_camera_type,
  371. "external_camera_enabled": printer.external_camera_enabled,
  372. "plate_detection_enabled": printer.plate_detection_enabled,
  373. "plate_detection_roi_x": printer.plate_detection_roi_x,
  374. "plate_detection_roi_y": printer.plate_detection_roi_y,
  375. "plate_detection_roi_w": printer.plate_detection_roi_w,
  376. "plate_detection_roi_h": printer.plate_detection_roi_h,
  377. }
  378. if include_access_codes:
  379. printer_data["access_code"] = printer.access_code
  380. backup["printers"].append(printer_data)
  381. backup["included"].append("printers")
  382. if include_access_codes:
  383. backup["included"].append("access_codes")
  384. # Plate calibration references (requires include_printers)
  385. if include_printers and include_plate_calibration:
  386. plate_cal_dir = app_settings.plate_calibration_dir
  387. if plate_cal_dir.exists():
  388. backup["plate_calibration"] = {
  389. "files": [],
  390. "printer_id_to_serial": {}, # Map old printer IDs to serial numbers for restore
  391. }
  392. for cal_file in plate_cal_dir.iterdir():
  393. if cal_file.is_file():
  394. backup["plate_calibration"]["files"].append(cal_file.name)
  395. # Extract printer ID from filename (e.g., "printer_1_ref_0.jpg" -> 1)
  396. if cal_file.name.startswith("printer_"):
  397. parts = cal_file.name.split("_")
  398. if len(parts) >= 2 and parts[1].isdigit():
  399. old_printer_id = int(parts[1])
  400. if old_printer_id not in backup["plate_calibration"]["printer_id_to_serial"]:
  401. # Look up serial number for this printer ID
  402. backup["plate_calibration"]["printer_id_to_serial"][old_printer_id] = (
  403. printer_id_to_serial.get(old_printer_id)
  404. )
  405. if backup["plate_calibration"]["files"]:
  406. backup["included"].append("plate_calibration")
  407. # Filaments
  408. if include_filaments:
  409. result = await db.execute(select(Filament))
  410. filaments = result.scalars().all()
  411. backup["filaments"] = []
  412. for f in filaments:
  413. backup["filaments"].append(
  414. {
  415. "name": f.name,
  416. "type": f.type,
  417. "brand": f.brand,
  418. "color": f.color,
  419. "color_hex": f.color_hex,
  420. "cost_per_kg": f.cost_per_kg,
  421. "spool_weight_g": f.spool_weight_g,
  422. "currency": f.currency,
  423. "density": f.density,
  424. "print_temp_min": f.print_temp_min,
  425. "print_temp_max": f.print_temp_max,
  426. "bed_temp_min": f.bed_temp_min,
  427. "bed_temp_max": f.bed_temp_max,
  428. }
  429. )
  430. backup["included"].append("filaments")
  431. # Maintenance types and records
  432. if include_maintenance:
  433. # Maintenance types
  434. result = await db.execute(select(MaintenanceType))
  435. types = result.scalars().all()
  436. backup["maintenance_types"] = []
  437. for mt in types:
  438. backup["maintenance_types"].append(
  439. {
  440. "name": mt.name,
  441. "description": mt.description,
  442. "default_interval_hours": mt.default_interval_hours,
  443. "interval_type": mt.interval_type,
  444. "icon": mt.icon,
  445. "is_system": mt.is_system,
  446. }
  447. )
  448. backup["included"].append("maintenance_types")
  449. # Printer maintenance settings (per-printer custom intervals, enabled status, last performed)
  450. result = await db.execute(select(PrinterMaintenance))
  451. printer_maint = result.scalars().all()
  452. backup["printer_maintenance"] = []
  453. # Build lookups for printer serial and maintenance type name
  454. printer_id_to_serial: dict[int, str] = {}
  455. maint_type_id_to_name: dict[int, str] = {}
  456. pr_result = await db.execute(select(Printer))
  457. for pr in pr_result.scalars().all():
  458. printer_id_to_serial[pr.id] = pr.serial_number
  459. for mt in types:
  460. maint_type_id_to_name[mt.id] = mt.name
  461. for pm in printer_maint:
  462. backup["printer_maintenance"].append(
  463. {
  464. "printer_serial": printer_id_to_serial.get(pm.printer_id),
  465. "maintenance_type_name": maint_type_id_to_name.get(pm.maintenance_type_id),
  466. "custom_interval_hours": pm.custom_interval_hours,
  467. "custom_interval_type": pm.custom_interval_type,
  468. "enabled": pm.enabled,
  469. "last_performed_at": pm.last_performed_at.isoformat() if pm.last_performed_at else None,
  470. "last_performed_hours": pm.last_performed_hours,
  471. }
  472. )
  473. backup["included"].append("printer_maintenance")
  474. # Maintenance history
  475. result = await db.execute(select(MaintenanceHistory))
  476. history = result.scalars().all()
  477. backup["maintenance_history"] = []
  478. # Build printer_maintenance ID to (printer_serial, maint_type_name) mapping
  479. pm_id_to_info: dict[int, tuple[str | None, str | None]] = {}
  480. for pm in printer_maint:
  481. pm_id_to_info[pm.id] = (
  482. printer_id_to_serial.get(pm.printer_id),
  483. maint_type_id_to_name.get(pm.maintenance_type_id),
  484. )
  485. for mh in history:
  486. info = pm_id_to_info.get(mh.printer_maintenance_id, (None, None))
  487. backup["maintenance_history"].append(
  488. {
  489. "printer_serial": info[0],
  490. "maintenance_type_name": info[1],
  491. "performed_at": mh.performed_at.isoformat() if mh.performed_at else None,
  492. "hours_at_maintenance": mh.hours_at_maintenance,
  493. "notes": mh.notes,
  494. }
  495. )
  496. backup["included"].append("maintenance_history")
  497. # Print queue
  498. if include_print_queue:
  499. result = await db.execute(select(PrintQueueItem))
  500. queue_items = result.scalars().all()
  501. backup["print_queue"] = []
  502. # Build lookups
  503. printer_id_to_serial: dict[int, str] = {}
  504. archive_id_to_hash: dict[int, str | None] = {}
  505. project_id_to_name: dict[int, str] = {}
  506. pr_result = await db.execute(select(Printer))
  507. for pr in pr_result.scalars().all():
  508. printer_id_to_serial[pr.id] = pr.serial_number
  509. ar_result = await db.execute(select(PrintArchive))
  510. for ar in ar_result.scalars().all():
  511. archive_id_to_hash[ar.id] = ar.content_hash
  512. proj_result = await db.execute(select(Project))
  513. for proj in proj_result.scalars().all():
  514. project_id_to_name[proj.id] = proj.name
  515. for qi in queue_items:
  516. backup["print_queue"].append(
  517. {
  518. "printer_serial": printer_id_to_serial.get(qi.printer_id) if qi.printer_id else None,
  519. "archive_hash": archive_id_to_hash.get(qi.archive_id),
  520. "project_name": project_id_to_name.get(qi.project_id) if qi.project_id else None,
  521. "position": qi.position,
  522. "scheduled_time": qi.scheduled_time.isoformat() if qi.scheduled_time else None,
  523. "require_previous_success": qi.require_previous_success,
  524. "auto_off_after": qi.auto_off_after,
  525. "manual_start": qi.manual_start,
  526. "ams_mapping": qi.ams_mapping,
  527. "plate_id": qi.plate_id,
  528. "bed_levelling": qi.bed_levelling,
  529. "flow_cali": qi.flow_cali,
  530. "vibration_cali": qi.vibration_cali,
  531. "layer_inspect": qi.layer_inspect,
  532. "timelapse": qi.timelapse,
  533. "use_ams": qi.use_ams,
  534. "status": qi.status,
  535. "started_at": qi.started_at.isoformat() if qi.started_at else None,
  536. "completed_at": qi.completed_at.isoformat() if qi.completed_at else None,
  537. "error_message": qi.error_message,
  538. }
  539. )
  540. backup["included"].append("print_queue")
  541. # Collect files for ZIP (icons + archives + project attachments)
  542. backup_files: list[tuple[str, Path]] = [] # (zip_path, local_path)
  543. base_dir = app_settings.base_dir
  544. # Add external link icon files
  545. if include_external_links and "external_links" in backup:
  546. icons_dir = base_dir / "icons"
  547. for link_data in backup["external_links"]:
  548. if "custom_icon_path" in link_data:
  549. icon_path = icons_dir / link_data["custom_icon"]
  550. if icon_path.exists():
  551. backup_files.append((link_data["custom_icon_path"], icon_path))
  552. # Add plate calibration reference images
  553. if "plate_calibration" in backup:
  554. plate_cal_dir = app_settings.plate_calibration_dir
  555. plate_cal_data = backup["plate_calibration"]
  556. # Support both old list format and new dict format
  557. filenames = plate_cal_data.get("files", []) if isinstance(plate_cal_data, dict) else plate_cal_data
  558. for filename in filenames:
  559. file_path = plate_cal_dir / filename
  560. if file_path.exists():
  561. backup_files.append((f"plate_calibration/{filename}", file_path))
  562. # Print archives with file paths for ZIP
  563. if include_archives:
  564. result = await db.execute(select(PrintArchive))
  565. archives = result.scalars().all()
  566. backup["archives"] = []
  567. # Build project ID to name mapping for archive export
  568. project_id_to_name: dict[int, str] = {}
  569. if include_projects:
  570. proj_result = await db.execute(select(Project))
  571. for proj in proj_result.scalars().all():
  572. project_id_to_name[proj.id] = proj.name
  573. # Build printer ID to serial mapping for archive export
  574. printer_id_to_serial: dict[int, str] = {}
  575. if include_printers:
  576. printer_result = await db.execute(select(Printer))
  577. for pr in printer_result.scalars().all():
  578. printer_id_to_serial[pr.id] = pr.serial_number
  579. for a in archives:
  580. archive_data = {
  581. "filename": a.filename,
  582. "project_name": project_id_to_name.get(a.project_id) if a.project_id else None,
  583. "printer_serial": printer_id_to_serial.get(a.printer_id) if a.printer_id else None,
  584. "file_size": a.file_size,
  585. "content_hash": a.content_hash,
  586. "print_name": a.print_name,
  587. "print_time_seconds": a.print_time_seconds,
  588. "filament_used_grams": a.filament_used_grams,
  589. "filament_type": a.filament_type,
  590. "filament_color": a.filament_color,
  591. "layer_height": a.layer_height,
  592. "total_layers": a.total_layers,
  593. "nozzle_diameter": a.nozzle_diameter,
  594. "bed_temperature": a.bed_temperature,
  595. "nozzle_temperature": a.nozzle_temperature,
  596. "status": a.status,
  597. "started_at": a.started_at.isoformat() if a.started_at else None,
  598. "completed_at": a.completed_at.isoformat() if a.completed_at else None,
  599. "makerworld_url": a.makerworld_url,
  600. "designer": a.designer,
  601. "external_url": a.external_url,
  602. "is_favorite": a.is_favorite,
  603. "tags": a.tags,
  604. "notes": a.notes,
  605. "cost": a.cost,
  606. "failure_reason": a.failure_reason,
  607. "quantity": a.quantity,
  608. "energy_kwh": a.energy_kwh,
  609. "energy_cost": a.energy_cost,
  610. "extra_data": a.extra_data,
  611. "photos": a.photos,
  612. }
  613. # Collect file paths for ZIP
  614. if a.file_path:
  615. file_path = base_dir / a.file_path
  616. if file_path.exists():
  617. archive_data["file_path"] = a.file_path
  618. backup_files.append((a.file_path, file_path))
  619. if a.thumbnail_path:
  620. thumb_path = base_dir / a.thumbnail_path
  621. if thumb_path.exists():
  622. archive_data["thumbnail_path"] = a.thumbnail_path
  623. backup_files.append((a.thumbnail_path, thumb_path))
  624. if a.timelapse_path:
  625. timelapse_path = base_dir / a.timelapse_path
  626. if timelapse_path.exists():
  627. archive_data["timelapse_path"] = a.timelapse_path
  628. backup_files.append((a.timelapse_path, timelapse_path))
  629. if a.source_3mf_path:
  630. source_path = base_dir / a.source_3mf_path
  631. if source_path.exists():
  632. archive_data["source_3mf_path"] = a.source_3mf_path
  633. backup_files.append((a.source_3mf_path, source_path))
  634. if a.f3d_path:
  635. f3d_path = base_dir / a.f3d_path
  636. if f3d_path.exists():
  637. archive_data["f3d_path"] = a.f3d_path
  638. backup_files.append((a.f3d_path, f3d_path))
  639. # Include photos
  640. if a.photos:
  641. for photo in a.photos:
  642. photo_path = base_dir / "archive" / "photos" / photo
  643. if photo_path.exists():
  644. zip_photo_path = f"archive/photos/{photo}"
  645. backup_files.append((zip_photo_path, photo_path))
  646. backup["archives"].append(archive_data)
  647. backup["included"].append("archives")
  648. # Projects with BOM items
  649. if include_projects:
  650. result = await db.execute(select(Project))
  651. projects = result.scalars().all()
  652. backup["projects"] = []
  653. for p in projects:
  654. # Get BOM items for this project
  655. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == p.id))
  656. bom_items = bom_result.scalars().all()
  657. project_data = {
  658. "name": p.name,
  659. "description": p.description,
  660. "color": p.color,
  661. "status": p.status,
  662. "target_count": p.target_count,
  663. "notes": p.notes,
  664. "tags": p.tags,
  665. "due_date": p.due_date.isoformat() if p.due_date else None,
  666. "priority": p.priority,
  667. "budget": p.budget,
  668. "is_template": p.is_template,
  669. "template_source_id": p.template_source_id,
  670. "parent_id": p.parent_id,
  671. "bom_items": [
  672. {
  673. "name": item.name,
  674. "quantity_needed": item.quantity_needed,
  675. "quantity_acquired": item.quantity_acquired,
  676. "unit_price": item.unit_price,
  677. "sourcing_url": item.sourcing_url,
  678. "stl_filename": item.stl_filename,
  679. "remarks": item.remarks,
  680. "sort_order": item.sort_order,
  681. }
  682. for item in bom_items
  683. ],
  684. }
  685. # Include attachment files for ZIP
  686. if p.attachments:
  687. project_data["attachments"] = p.attachments
  688. attachments_dir = base_dir / "projects" / str(p.id) / "attachments"
  689. for att in p.attachments:
  690. att_path = attachments_dir / att.get("filename", "")
  691. if att_path.exists():
  692. zip_path = f"projects/{p.id}/attachments/{att['filename']}"
  693. backup_files.append((zip_path, att_path))
  694. backup["projects"].append(project_data)
  695. backup["included"].append("projects")
  696. # Pending uploads (virtual printer queue mode)
  697. if include_pending_uploads:
  698. result = await db.execute(select(PendingUpload).where(PendingUpload.status == "pending"))
  699. pending_uploads = result.scalars().all()
  700. backup["pending_uploads"] = []
  701. for p in pending_uploads:
  702. upload_data = {
  703. "filename": p.filename,
  704. "file_size": p.file_size,
  705. "source_ip": p.source_ip,
  706. "status": p.status,
  707. "tags": p.tags,
  708. "notes": p.notes,
  709. "project_id": p.project_id,
  710. "uploaded_at": p.uploaded_at.isoformat() if p.uploaded_at else None,
  711. }
  712. # Include the actual file if it exists
  713. if p.file_path:
  714. file_path = Path(p.file_path)
  715. if file_path.exists():
  716. # Store relative path for ZIP
  717. rel_path = f"pending_uploads/{p.filename}"
  718. upload_data["file_path"] = rel_path
  719. backup_files.append((rel_path, file_path))
  720. backup["pending_uploads"].append(upload_data)
  721. backup["included"].append("pending_uploads")
  722. # API keys (note: key_hash cannot be restored, new keys must be generated)
  723. if include_api_keys:
  724. # Build printer ID to serial mapping for cross-system compatibility
  725. printer_id_to_serial: dict[int, str] = {}
  726. pr_result = await db.execute(select(Printer))
  727. for pr in pr_result.scalars().all():
  728. printer_id_to_serial[pr.id] = pr.serial_number
  729. result = await db.execute(select(APIKey))
  730. api_keys = result.scalars().all()
  731. backup["api_keys"] = []
  732. for key in api_keys:
  733. # Convert printer_ids from list of IDs to list of serials
  734. printer_serials = None
  735. if key.printer_ids:
  736. printer_serials = [
  737. printer_id_to_serial.get(pid) for pid in key.printer_ids if pid in printer_id_to_serial
  738. ]
  739. backup["api_keys"].append(
  740. {
  741. "name": key.name,
  742. "key_prefix": key.key_prefix, # For identification only
  743. "can_queue": key.can_queue,
  744. "can_control_printer": key.can_control_printer,
  745. "can_read_status": key.can_read_status,
  746. "printer_serials": printer_serials, # Use serials instead of IDs
  747. "enabled": key.enabled,
  748. "expires_at": key.expires_at.isoformat() if key.expires_at else None,
  749. }
  750. )
  751. backup["included"].append("api_keys")
  752. # Users (note: passwords not exported for security - users will need new passwords on import)
  753. if include_users:
  754. result = await db.execute(select(User))
  755. users = result.scalars().all()
  756. backup["users"] = []
  757. for user in users:
  758. backup["users"].append(
  759. {
  760. "username": user.username,
  761. "role": user.role,
  762. "is_active": user.is_active,
  763. # password_hash intentionally not exported for security
  764. }
  765. )
  766. backup["included"].append("users")
  767. # If there are files to include (icons or archives), create ZIP file
  768. if backup_files:
  769. zip_buffer = io.BytesIO()
  770. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  771. # Add backup.json
  772. zf.writestr("backup.json", json.dumps(backup, indent=2))
  773. # Add all backup files (icons, archives, etc.)
  774. added_files = set()
  775. for zip_path, local_path in backup_files:
  776. if zip_path not in added_files and local_path.exists():
  777. try:
  778. zf.write(local_path, zip_path)
  779. added_files.add(zip_path)
  780. except Exception:
  781. pass # Skip files that can't be read
  782. zip_buffer.seek(0)
  783. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  784. return StreamingResponse(
  785. zip_buffer,
  786. media_type="application/zip",
  787. headers={"Content-Disposition": f"attachment; filename={filename}"},
  788. )
  789. # Otherwise return JSON
  790. return JSONResponse(
  791. content=backup,
  792. headers={
  793. "Content-Disposition": f"attachment; filename=bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  794. },
  795. )
  796. @router.post("/restore")
  797. async def import_backup(
  798. file: UploadFile = File(...),
  799. overwrite: bool = Query(False, description="Overwrite existing data instead of skipping duplicates"),
  800. db: AsyncSession = Depends(get_db),
  801. ):
  802. """Restore data from JSON or ZIP backup. By default skips duplicates, set overwrite=true to replace existing."""
  803. try:
  804. content = await file.read()
  805. base_dir = app_settings.base_dir
  806. files_restored = 0
  807. # Store plate calibration files for later (need printer ID remapping after printers restored)
  808. plate_cal_files: dict[str, bytes] = {}
  809. # Check if it's a ZIP file
  810. if file.filename and file.filename.endswith(".zip"):
  811. try:
  812. zip_buffer = io.BytesIO(content)
  813. with zipfile.ZipFile(zip_buffer, "r") as zf:
  814. # Extract backup.json
  815. if "backup.json" not in zf.namelist():
  816. return {"success": False, "message": "Invalid ZIP: missing backup.json"}
  817. backup_content = zf.read("backup.json")
  818. backup = json.loads(backup_content.decode("utf-8"))
  819. # Extract all other files to base_dir
  820. for zip_path in zf.namelist():
  821. if zip_path == "backup.json":
  822. continue
  823. # Ensure path is safe (no path traversal)
  824. if ".." in zip_path or zip_path.startswith("/"):
  825. continue
  826. # Plate calibration files - store for later processing after printers are restored
  827. if zip_path.startswith("plate_calibration/"):
  828. filename = zip_path.replace("plate_calibration/", "", 1)
  829. if filename: # Skip directory entries
  830. plate_cal_files[filename] = zf.read(zip_path)
  831. logger.info(f"Stored plate calibration file for later: {filename}")
  832. continue
  833. target_path = base_dir / zip_path
  834. target_path.parent.mkdir(parents=True, exist_ok=True)
  835. with zf.open(zip_path) as src, open(target_path, "wb") as dst:
  836. dst.write(src.read())
  837. files_restored += 1
  838. except zipfile.BadZipFile:
  839. return {"success": False, "message": "Invalid ZIP file"}
  840. else:
  841. backup = json.loads(content.decode("utf-8"))
  842. except json.JSONDecodeError as e:
  843. return {"success": False, "message": f"Invalid JSON: {str(e)}"}
  844. except Exception as e:
  845. return {"success": False, "message": f"Invalid backup file: {str(e)}"}
  846. restored = {
  847. "settings": 0,
  848. "notification_providers": 0,
  849. "notification_templates": 0,
  850. "smart_plugs": 0,
  851. "external_links": 0,
  852. "printers": 0,
  853. "filaments": 0,
  854. "maintenance_types": 0,
  855. "projects": 0,
  856. "pending_uploads": 0,
  857. "users": 0,
  858. }
  859. skipped = {
  860. "settings": 0,
  861. "notification_providers": 0,
  862. "notification_templates": 0,
  863. "smart_plugs": 0,
  864. "external_links": 0,
  865. "printers": 0,
  866. "filaments": 0,
  867. "maintenance_types": 0,
  868. "archives": 0,
  869. "projects": 0,
  870. "pending_uploads": 0,
  871. "users": 0,
  872. }
  873. skipped_details = {
  874. "notification_providers": [],
  875. "smart_plugs": [],
  876. "external_links": [],
  877. "printers": [],
  878. "filaments": [],
  879. "maintenance_types": [],
  880. "archives": [],
  881. "projects": [],
  882. "pending_uploads": [],
  883. "users": [],
  884. }
  885. # Restore settings (always overwrites)
  886. if "settings" in backup:
  887. for key, value in backup["settings"].items():
  888. # Convert value to proper string format for storage
  889. if isinstance(value, bool):
  890. str_value = "true" if value else "false"
  891. elif value is None:
  892. str_value = "None"
  893. else:
  894. str_value = str(value)
  895. await set_setting(db, key, str_value)
  896. restored["settings"] += 1
  897. # Flush settings to ensure they're persisted before continuing
  898. await db.flush()
  899. # Restore printers FIRST (skip or overwrite duplicates by serial_number)
  900. # Nearly everything in the app references printers, so they must be imported first
  901. if "printers" in backup:
  902. for printer_data in backup["printers"]:
  903. result = await db.execute(select(Printer).where(Printer.serial_number == printer_data["serial_number"]))
  904. existing = result.scalar_one_or_none()
  905. if existing:
  906. if overwrite:
  907. existing.name = printer_data["name"]
  908. existing.ip_address = printer_data["ip_address"]
  909. existing.model = printer_data.get("model")
  910. existing.location = printer_data.get("location")
  911. existing.nozzle_count = printer_data.get("nozzle_count", 1)
  912. existing.auto_archive = printer_data.get("auto_archive", True)
  913. existing.print_hours_offset = printer_data.get("print_hours_offset", 0.0)
  914. existing.runtime_seconds = printer_data.get("runtime_seconds", 0)
  915. # If backup includes access_code, also update access_code and is_active
  916. backup_access_code = printer_data.get("access_code")
  917. if backup_access_code and backup_access_code != "CHANGE_ME":
  918. existing.access_code = backup_access_code
  919. is_active_val = printer_data.get("is_active", False)
  920. if isinstance(is_active_val, str):
  921. is_active_val = is_active_val.lower() == "true"
  922. existing.is_active = is_active_val
  923. # Restore external camera settings
  924. existing.external_camera_url = printer_data.get("external_camera_url")
  925. existing.external_camera_type = printer_data.get("external_camera_type")
  926. existing.external_camera_enabled = printer_data.get("external_camera_enabled", False)
  927. # Restore plate detection settings
  928. existing.plate_detection_enabled = printer_data.get("plate_detection_enabled", False)
  929. existing.plate_detection_roi_x = printer_data.get("plate_detection_roi_x")
  930. existing.plate_detection_roi_y = printer_data.get("plate_detection_roi_y")
  931. existing.plate_detection_roi_w = printer_data.get("plate_detection_roi_w")
  932. existing.plate_detection_roi_h = printer_data.get("plate_detection_roi_h")
  933. restored["printers"] += 1
  934. else:
  935. skipped["printers"] += 1
  936. skipped_details["printers"].append(f"{printer_data['name']} ({printer_data['serial_number']})")
  937. else:
  938. # Use access code from backup if provided, otherwise require manual setup
  939. access_code = printer_data.get("access_code")
  940. has_access_code = access_code and access_code != "CHANGE_ME"
  941. is_active_from_backup = printer_data.get("is_active", False)
  942. # Handle bool or string "true"/"false"
  943. if isinstance(is_active_from_backup, str):
  944. is_active_from_backup = is_active_from_backup.lower() == "true"
  945. printer = Printer(
  946. name=printer_data["name"],
  947. serial_number=printer_data["serial_number"],
  948. ip_address=printer_data["ip_address"],
  949. access_code=access_code if has_access_code else "CHANGE_ME",
  950. model=printer_data.get("model"),
  951. location=printer_data.get("location"),
  952. nozzle_count=printer_data.get("nozzle_count", 1),
  953. is_active=is_active_from_backup if has_access_code else False,
  954. auto_archive=printer_data.get("auto_archive", True),
  955. print_hours_offset=printer_data.get("print_hours_offset", 0.0),
  956. runtime_seconds=printer_data.get("runtime_seconds", 0),
  957. external_camera_url=printer_data.get("external_camera_url"),
  958. external_camera_type=printer_data.get("external_camera_type"),
  959. external_camera_enabled=printer_data.get("external_camera_enabled", False),
  960. plate_detection_enabled=printer_data.get("plate_detection_enabled", False),
  961. plate_detection_roi_x=printer_data.get("plate_detection_roi_x"),
  962. plate_detection_roi_y=printer_data.get("plate_detection_roi_y"),
  963. plate_detection_roi_w=printer_data.get("plate_detection_roi_w"),
  964. plate_detection_roi_h=printer_data.get("plate_detection_roi_h"),
  965. )
  966. db.add(printer)
  967. restored["printers"] += 1
  968. # Flush printers so other sections can look them up
  969. await db.flush()
  970. # Restore plate calibration files (remap printer IDs based on serial numbers)
  971. logger.info(f"Plate calibration files to restore: {len(plate_cal_files)} files: {list(plate_cal_files.keys())}")
  972. if plate_cal_files:
  973. # Build serial_number -> new_printer_id mapping
  974. serial_to_new_id: dict[str, int] = {}
  975. pr_result = await db.execute(select(Printer))
  976. for pr in pr_result.scalars().all():
  977. serial_to_new_id[pr.serial_number] = pr.id
  978. # Get old_id -> serial mapping from backup (supports both old list format and new dict format)
  979. plate_cal_data = backup.get("plate_calibration", {})
  980. if isinstance(plate_cal_data, dict):
  981. old_id_to_serial: dict[int, str | None] = {
  982. int(k): v for k, v in plate_cal_data.get("printer_id_to_serial", {}).items()
  983. }
  984. else:
  985. old_id_to_serial = {}
  986. # Build old_id -> new_id mapping
  987. old_id_to_new_id: dict[int, int] = {}
  988. for old_id, serial in old_id_to_serial.items():
  989. if serial and serial in serial_to_new_id:
  990. old_id_to_new_id[old_id] = serial_to_new_id[serial]
  991. logger.info(
  992. f"Plate calibration ID mapping: old_id_to_serial={old_id_to_serial}, serial_to_new_id={serial_to_new_id}, old_id_to_new_id={old_id_to_new_id}"
  993. )
  994. app_settings.plate_calibration_dir.mkdir(parents=True, exist_ok=True)
  995. for filename, file_data in plate_cal_files.items():
  996. # Parse old printer ID from filename (e.g., "printer_3_ref_0.jpg" -> 3)
  997. new_filename = filename
  998. if filename.startswith("printer_"):
  999. parts = filename.split("_")
  1000. if len(parts) >= 2 and parts[1].isdigit():
  1001. old_printer_id = int(parts[1])
  1002. if old_printer_id in old_id_to_new_id:
  1003. new_printer_id = old_id_to_new_id[old_printer_id]
  1004. # Replace old ID with new ID in filename
  1005. new_filename = filename.replace(f"printer_{old_printer_id}_", f"printer_{new_printer_id}_", 1)
  1006. target_path = app_settings.plate_calibration_dir / new_filename
  1007. logger.info(f"Writing plate calibration file: {filename} -> {target_path}")
  1008. with open(target_path, "wb") as f:
  1009. f.write(file_data)
  1010. files_restored += 1
  1011. # Restore notification providers (skip or overwrite duplicates by name)
  1012. # Build printer serial to ID lookup (printers were restored first)
  1013. if "notification_providers" in backup:
  1014. printer_serial_to_id: dict[str, int] = {}
  1015. pr_result = await db.execute(select(Printer))
  1016. for pr in pr_result.scalars().all():
  1017. printer_serial_to_id[pr.serial_number] = pr.id
  1018. for provider_data in backup["notification_providers"]:
  1019. # Look up printer_id from serial (supports both old printer_id and new printer_serial format)
  1020. printer_serial = provider_data.get("printer_serial")
  1021. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else provider_data.get("printer_id")
  1022. result = await db.execute(
  1023. select(NotificationProvider).where(NotificationProvider.name == provider_data["name"])
  1024. )
  1025. existing = result.scalar_one_or_none()
  1026. if existing:
  1027. if overwrite:
  1028. # Update existing provider
  1029. existing.provider_type = provider_data["provider_type"]
  1030. existing.enabled = provider_data.get("enabled", True)
  1031. existing.config = json.dumps(provider_data.get("config", {}))
  1032. existing.on_print_start = provider_data.get("on_print_start", False)
  1033. existing.on_print_complete = provider_data.get("on_print_complete", True)
  1034. existing.on_print_failed = provider_data.get("on_print_failed", True)
  1035. existing.on_print_stopped = provider_data.get("on_print_stopped", True)
  1036. existing.on_print_progress = provider_data.get("on_print_progress", False)
  1037. existing.on_printer_offline = provider_data.get("on_printer_offline", False)
  1038. existing.on_printer_error = provider_data.get("on_printer_error", False)
  1039. existing.on_filament_low = provider_data.get("on_filament_low", False)
  1040. existing.on_maintenance_due = provider_data.get("on_maintenance_due", False)
  1041. existing.on_ams_humidity_high = provider_data.get("on_ams_humidity_high", False)
  1042. existing.on_ams_temperature_high = provider_data.get("on_ams_temperature_high", False)
  1043. existing.on_ams_ht_humidity_high = provider_data.get("on_ams_ht_humidity_high", False)
  1044. existing.on_ams_ht_temperature_high = provider_data.get("on_ams_ht_temperature_high", False)
  1045. existing.on_plate_not_empty = provider_data.get("on_plate_not_empty", True)
  1046. existing.quiet_hours_enabled = provider_data.get("quiet_hours_enabled", False)
  1047. existing.quiet_hours_start = provider_data.get("quiet_hours_start")
  1048. existing.quiet_hours_end = provider_data.get("quiet_hours_end")
  1049. existing.daily_digest_enabled = provider_data.get("daily_digest_enabled", False)
  1050. existing.daily_digest_time = provider_data.get("daily_digest_time")
  1051. existing.printer_id = printer_id
  1052. restored["notification_providers"] += 1
  1053. else:
  1054. skipped["notification_providers"] += 1
  1055. skipped_details["notification_providers"].append(provider_data["name"])
  1056. else:
  1057. provider = NotificationProvider(
  1058. name=provider_data["name"],
  1059. provider_type=provider_data["provider_type"],
  1060. enabled=provider_data.get("enabled", True),
  1061. config=json.dumps(provider_data.get("config", {})),
  1062. on_print_start=provider_data.get("on_print_start", False),
  1063. on_print_complete=provider_data.get("on_print_complete", True),
  1064. on_print_failed=provider_data.get("on_print_failed", True),
  1065. on_print_stopped=provider_data.get("on_print_stopped", True),
  1066. on_print_progress=provider_data.get("on_print_progress", False),
  1067. on_printer_offline=provider_data.get("on_printer_offline", False),
  1068. on_printer_error=provider_data.get("on_printer_error", False),
  1069. on_filament_low=provider_data.get("on_filament_low", False),
  1070. on_maintenance_due=provider_data.get("on_maintenance_due", False),
  1071. on_ams_humidity_high=provider_data.get("on_ams_humidity_high", False),
  1072. on_ams_temperature_high=provider_data.get("on_ams_temperature_high", False),
  1073. on_ams_ht_humidity_high=provider_data.get("on_ams_ht_humidity_high", False),
  1074. on_ams_ht_temperature_high=provider_data.get("on_ams_ht_temperature_high", False),
  1075. on_plate_not_empty=provider_data.get("on_plate_not_empty", True),
  1076. quiet_hours_enabled=provider_data.get("quiet_hours_enabled", False),
  1077. quiet_hours_start=provider_data.get("quiet_hours_start"),
  1078. quiet_hours_end=provider_data.get("quiet_hours_end"),
  1079. daily_digest_enabled=provider_data.get("daily_digest_enabled", False),
  1080. daily_digest_time=provider_data.get("daily_digest_time"),
  1081. printer_id=printer_id,
  1082. )
  1083. db.add(provider)
  1084. restored["notification_providers"] += 1
  1085. # Restore notification templates (update existing by event_type)
  1086. if "notification_templates" in backup:
  1087. for template_data in backup["notification_templates"]:
  1088. result = await db.execute(
  1089. select(NotificationTemplate).where(NotificationTemplate.event_type == template_data["event_type"])
  1090. )
  1091. existing = result.scalar_one_or_none()
  1092. if existing:
  1093. # Update existing template
  1094. existing.name = template_data.get("name", existing.name)
  1095. existing.title_template = template_data.get("title_template", existing.title_template)
  1096. existing.body_template = template_data.get("body_template", existing.body_template)
  1097. existing.is_default = template_data.get("is_default", False)
  1098. else:
  1099. template = NotificationTemplate(
  1100. event_type=template_data["event_type"],
  1101. name=template_data["name"],
  1102. title_template=template_data["title_template"],
  1103. body_template=template_data["body_template"],
  1104. is_default=template_data.get("is_default", False),
  1105. )
  1106. db.add(template)
  1107. restored["notification_templates"] += 1
  1108. # Restore smart plugs (skip or overwrite duplicates by IP)
  1109. # Note: Smart plugs reference printers, so printers should be restored first
  1110. if "smart_plugs" in backup:
  1111. # Build printer serial to ID lookup
  1112. printer_serial_to_id: dict[str, int] = {}
  1113. pr_result = await db.execute(select(Printer))
  1114. for pr in pr_result.scalars().all():
  1115. printer_serial_to_id[pr.serial_number] = pr.id
  1116. for plug_data in backup["smart_plugs"]:
  1117. # Look up printer_id from serial (supports both old printer_id and new printer_serial format)
  1118. printer_serial = plug_data.get("printer_serial")
  1119. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else plug_data.get("printer_id")
  1120. # Determine plug type (default to tasmota for backwards compatibility)
  1121. plug_type = plug_data.get("plug_type", "tasmota")
  1122. # Find existing plug by IP (Tasmota) or entity_id (Home Assistant)
  1123. existing = None
  1124. if plug_type == "homeassistant" and plug_data.get("ha_entity_id"):
  1125. result = await db.execute(select(SmartPlug).where(SmartPlug.ha_entity_id == plug_data["ha_entity_id"]))
  1126. existing = result.scalar_one_or_none()
  1127. plug_identifier = plug_data["ha_entity_id"]
  1128. elif plug_data.get("ip_address"):
  1129. result = await db.execute(select(SmartPlug).where(SmartPlug.ip_address == plug_data["ip_address"]))
  1130. existing = result.scalar_one_or_none()
  1131. plug_identifier = plug_data["ip_address"]
  1132. else:
  1133. # Skip invalid plug data
  1134. continue
  1135. if existing:
  1136. if overwrite:
  1137. existing.name = plug_data["name"]
  1138. existing.plug_type = plug_type
  1139. existing.ha_entity_id = plug_data.get("ha_entity_id")
  1140. existing.ha_power_entity = plug_data.get("ha_power_entity")
  1141. existing.ha_energy_today_entity = plug_data.get("ha_energy_today_entity")
  1142. existing.ha_energy_total_entity = plug_data.get("ha_energy_total_entity")
  1143. existing.printer_id = printer_id
  1144. existing.enabled = plug_data.get("enabled", True)
  1145. existing.auto_on = plug_data.get("auto_on", True)
  1146. existing.auto_off = plug_data.get("auto_off", True)
  1147. existing.off_delay_mode = plug_data.get("off_delay_mode", "time")
  1148. existing.off_delay_minutes = plug_data.get("off_delay_minutes", 5)
  1149. existing.off_temp_threshold = plug_data.get("off_temp_threshold", 70)
  1150. existing.username = plug_data.get("username")
  1151. existing.password = plug_data.get("password")
  1152. existing.power_alert_enabled = plug_data.get("power_alert_enabled", False)
  1153. existing.power_alert_high = plug_data.get("power_alert_high")
  1154. existing.power_alert_low = plug_data.get("power_alert_low")
  1155. existing.schedule_enabled = plug_data.get("schedule_enabled", False)
  1156. existing.schedule_on_time = plug_data.get("schedule_on_time")
  1157. existing.schedule_off_time = plug_data.get("schedule_off_time")
  1158. existing.show_in_switchbar = plug_data.get("show_in_switchbar", False)
  1159. restored["smart_plugs"] += 1
  1160. else:
  1161. skipped["smart_plugs"] += 1
  1162. skipped_details["smart_plugs"].append(f"{plug_data['name']} ({plug_identifier})")
  1163. else:
  1164. plug = SmartPlug(
  1165. name=plug_data["name"],
  1166. plug_type=plug_type,
  1167. ip_address=plug_data.get("ip_address"),
  1168. ha_entity_id=plug_data.get("ha_entity_id"),
  1169. ha_power_entity=plug_data.get("ha_power_entity"),
  1170. ha_energy_today_entity=plug_data.get("ha_energy_today_entity"),
  1171. ha_energy_total_entity=plug_data.get("ha_energy_total_entity"),
  1172. printer_id=printer_id,
  1173. enabled=plug_data.get("enabled", True),
  1174. auto_on=plug_data.get("auto_on", True),
  1175. auto_off=plug_data.get("auto_off", True),
  1176. off_delay_mode=plug_data.get("off_delay_mode", "time"),
  1177. off_delay_minutes=plug_data.get("off_delay_minutes", 5),
  1178. off_temp_threshold=plug_data.get("off_temp_threshold", 70),
  1179. username=plug_data.get("username"),
  1180. password=plug_data.get("password"),
  1181. power_alert_enabled=plug_data.get("power_alert_enabled", False),
  1182. power_alert_high=plug_data.get("power_alert_high"),
  1183. power_alert_low=plug_data.get("power_alert_low"),
  1184. schedule_enabled=plug_data.get("schedule_enabled", False),
  1185. schedule_on_time=plug_data.get("schedule_on_time"),
  1186. schedule_off_time=plug_data.get("schedule_off_time"),
  1187. show_in_switchbar=plug_data.get("show_in_switchbar", False),
  1188. )
  1189. db.add(plug)
  1190. restored["smart_plugs"] += 1
  1191. # Restore external links (skip or overwrite duplicates by name+url)
  1192. if "external_links" in backup:
  1193. icons_dir = base_dir / "icons"
  1194. icons_dir.mkdir(parents=True, exist_ok=True)
  1195. for link_data in backup["external_links"]:
  1196. result = await db.execute(
  1197. select(ExternalLink).where(ExternalLink.name == link_data["name"], ExternalLink.url == link_data["url"])
  1198. )
  1199. existing = result.scalar_one_or_none()
  1200. if existing:
  1201. if overwrite:
  1202. existing.icon = link_data.get("icon", "link")
  1203. existing.sort_order = link_data.get("sort_order", 0)
  1204. # Handle custom icon
  1205. if link_data.get("custom_icon"):
  1206. existing.custom_icon = link_data["custom_icon"]
  1207. restored["external_links"] += 1
  1208. else:
  1209. skipped["external_links"] += 1
  1210. skipped_details["external_links"].append(link_data["name"])
  1211. else:
  1212. link = ExternalLink(
  1213. name=link_data["name"],
  1214. url=link_data["url"],
  1215. icon=link_data.get("icon", "link"),
  1216. custom_icon=link_data.get("custom_icon"),
  1217. sort_order=link_data.get("sort_order", 0),
  1218. )
  1219. db.add(link)
  1220. restored["external_links"] += 1
  1221. # Restore filaments (skip or overwrite duplicates by name+type+brand)
  1222. if "filaments" in backup:
  1223. for filament_data in backup["filaments"]:
  1224. result = await db.execute(
  1225. select(Filament).where(
  1226. Filament.name == filament_data["name"],
  1227. Filament.type == filament_data["type"],
  1228. Filament.brand == filament_data.get("brand"),
  1229. )
  1230. )
  1231. existing = result.scalar_one_or_none()
  1232. if existing:
  1233. if overwrite:
  1234. existing.color = filament_data.get("color")
  1235. existing.color_hex = filament_data.get("color_hex")
  1236. existing.cost_per_kg = filament_data.get("cost_per_kg", 25.0)
  1237. existing.spool_weight_g = filament_data.get("spool_weight_g", 1000.0)
  1238. existing.currency = filament_data.get("currency", "USD")
  1239. existing.density = filament_data.get("density")
  1240. existing.print_temp_min = filament_data.get("print_temp_min")
  1241. existing.print_temp_max = filament_data.get("print_temp_max")
  1242. existing.bed_temp_min = filament_data.get("bed_temp_min")
  1243. existing.bed_temp_max = filament_data.get("bed_temp_max")
  1244. restored["filaments"] += 1
  1245. else:
  1246. skipped["filaments"] += 1
  1247. skipped_details["filaments"].append(
  1248. f"{filament_data.get('brand', '')} {filament_data['name']} ({filament_data['type']})"
  1249. )
  1250. else:
  1251. filament = Filament(
  1252. name=filament_data["name"],
  1253. type=filament_data["type"],
  1254. brand=filament_data.get("brand"),
  1255. color=filament_data.get("color"),
  1256. color_hex=filament_data.get("color_hex"),
  1257. cost_per_kg=filament_data.get("cost_per_kg", 25.0),
  1258. spool_weight_g=filament_data.get("spool_weight_g", 1000.0),
  1259. currency=filament_data.get("currency", "USD"),
  1260. density=filament_data.get("density"),
  1261. print_temp_min=filament_data.get("print_temp_min"),
  1262. print_temp_max=filament_data.get("print_temp_max"),
  1263. bed_temp_min=filament_data.get("bed_temp_min"),
  1264. bed_temp_max=filament_data.get("bed_temp_max"),
  1265. )
  1266. db.add(filament)
  1267. restored["filaments"] += 1
  1268. # Restore maintenance types (skip or overwrite duplicates by name)
  1269. if "maintenance_types" in backup:
  1270. for mt_data in backup["maintenance_types"]:
  1271. result = await db.execute(select(MaintenanceType).where(MaintenanceType.name == mt_data["name"]))
  1272. existing = result.scalar_one_or_none()
  1273. if existing:
  1274. if overwrite:
  1275. existing.description = mt_data.get("description")
  1276. existing.default_interval_hours = mt_data.get("default_interval_hours", 100.0)
  1277. existing.interval_type = mt_data.get("interval_type", "hours")
  1278. existing.icon = mt_data.get("icon")
  1279. # Don't overwrite is_system
  1280. restored["maintenance_types"] += 1
  1281. else:
  1282. skipped["maintenance_types"] += 1
  1283. skipped_details["maintenance_types"].append(mt_data["name"])
  1284. else:
  1285. mt = MaintenanceType(
  1286. name=mt_data["name"],
  1287. description=mt_data.get("description"),
  1288. default_interval_hours=mt_data.get("default_interval_hours", 100.0),
  1289. interval_type=mt_data.get("interval_type", "hours"),
  1290. icon=mt_data.get("icon"),
  1291. is_system=mt_data.get("is_system", False),
  1292. )
  1293. db.add(mt)
  1294. restored["maintenance_types"] += 1
  1295. # Restore printer maintenance settings (per-printer)
  1296. if "printer_maintenance" in backup:
  1297. # Build lookups
  1298. printer_serial_to_id: dict[str, int] = {}
  1299. maint_type_name_to_id: dict[str, int] = {}
  1300. pr_result = await db.execute(select(Printer))
  1301. for pr in pr_result.scalars().all():
  1302. printer_serial_to_id[pr.serial_number] = pr.id
  1303. mt_result = await db.execute(select(MaintenanceType))
  1304. for mt in mt_result.scalars().all():
  1305. maint_type_name_to_id[mt.name] = mt.id
  1306. restored["printer_maintenance"] = 0
  1307. skipped["printer_maintenance"] = 0
  1308. skipped_details["printer_maintenance"] = []
  1309. for pm_data in backup["printer_maintenance"]:
  1310. printer_serial = pm_data.get("printer_serial")
  1311. maint_type_name = pm_data.get("maintenance_type_name")
  1312. if not printer_serial or not maint_type_name:
  1313. continue
  1314. printer_id = printer_serial_to_id.get(printer_serial)
  1315. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1316. if not printer_id or not maint_type_id:
  1317. skipped["printer_maintenance"] += 1
  1318. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1319. continue
  1320. # Check if exists
  1321. result = await db.execute(
  1322. select(PrinterMaintenance).where(
  1323. PrinterMaintenance.printer_id == printer_id,
  1324. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1325. )
  1326. )
  1327. existing = result.scalar_one_or_none()
  1328. if existing:
  1329. if overwrite:
  1330. existing.custom_interval_hours = pm_data.get("custom_interval_hours")
  1331. existing.custom_interval_type = pm_data.get("custom_interval_type")
  1332. existing.enabled = pm_data.get("enabled", True)
  1333. existing.last_performed_hours = pm_data.get("last_performed_hours", 0.0)
  1334. if pm_data.get("last_performed_at"):
  1335. existing.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1336. restored["printer_maintenance"] += 1
  1337. else:
  1338. skipped["printer_maintenance"] += 1
  1339. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1340. else:
  1341. pm = PrinterMaintenance(
  1342. printer_id=printer_id,
  1343. maintenance_type_id=maint_type_id,
  1344. custom_interval_hours=pm_data.get("custom_interval_hours"),
  1345. custom_interval_type=pm_data.get("custom_interval_type"),
  1346. enabled=pm_data.get("enabled", True),
  1347. last_performed_hours=pm_data.get("last_performed_hours", 0.0),
  1348. )
  1349. if pm_data.get("last_performed_at"):
  1350. pm.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1351. db.add(pm)
  1352. restored["printer_maintenance"] += 1
  1353. # Restore maintenance history
  1354. if "maintenance_history" in backup:
  1355. # Build lookups
  1356. printer_serial_to_id: dict[str, int] = {}
  1357. maint_type_name_to_id: dict[str, int] = {}
  1358. pr_result = await db.execute(select(Printer))
  1359. for pr in pr_result.scalars().all():
  1360. printer_serial_to_id[pr.serial_number] = pr.id
  1361. mt_result = await db.execute(select(MaintenanceType))
  1362. for mt in mt_result.scalars().all():
  1363. maint_type_name_to_id[mt.name] = mt.id
  1364. restored["maintenance_history"] = 0
  1365. skipped["maintenance_history"] = 0
  1366. skipped_details["maintenance_history"] = []
  1367. for mh_data in backup["maintenance_history"]:
  1368. printer_serial = mh_data.get("printer_serial")
  1369. maint_type_name = mh_data.get("maintenance_type_name")
  1370. if not printer_serial or not maint_type_name:
  1371. continue
  1372. printer_id = printer_serial_to_id.get(printer_serial)
  1373. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1374. if not printer_id or not maint_type_id:
  1375. skipped["maintenance_history"] += 1
  1376. continue
  1377. # Find the PrinterMaintenance record
  1378. result = await db.execute(
  1379. select(PrinterMaintenance).where(
  1380. PrinterMaintenance.printer_id == printer_id,
  1381. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1382. )
  1383. )
  1384. pm = result.scalar_one_or_none()
  1385. if not pm:
  1386. skipped["maintenance_history"] += 1
  1387. continue
  1388. # Create history entry (no duplicate check - history is append-only)
  1389. mh = MaintenanceHistory(
  1390. printer_maintenance_id=pm.id,
  1391. hours_at_maintenance=mh_data.get("hours_at_maintenance", 0.0),
  1392. notes=mh_data.get("notes"),
  1393. )
  1394. if mh_data.get("performed_at"):
  1395. mh.performed_at = datetime.fromisoformat(mh_data["performed_at"])
  1396. db.add(mh)
  1397. restored["maintenance_history"] += 1
  1398. # Restore archives (skip duplicates by content_hash - overwrite not supported for archives)
  1399. if "archives" in backup:
  1400. # Build printer serial to ID mapping
  1401. printer_serial_to_id: dict[str, int] = {}
  1402. printer_result = await db.execute(select(Printer))
  1403. for pr in printer_result.scalars().all():
  1404. printer_serial_to_id[pr.serial_number] = pr.id
  1405. for archive_data in backup["archives"]:
  1406. # Skip if no content_hash or already exists
  1407. content_hash = archive_data.get("content_hash")
  1408. if content_hash:
  1409. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1410. existing = result.scalar_one_or_none()
  1411. if existing:
  1412. skipped["archives"] += 1
  1413. skipped_details["archives"].append(archive_data.get("filename", "Unknown"))
  1414. continue
  1415. # Only restore if file exists (from ZIP extraction)
  1416. file_path = archive_data.get("file_path")
  1417. if file_path and (base_dir / file_path).exists():
  1418. # Look up printer_id from serial
  1419. printer_serial = archive_data.get("printer_serial")
  1420. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1421. archive = PrintArchive(
  1422. filename=archive_data["filename"],
  1423. file_path=file_path,
  1424. file_size=archive_data.get("file_size", 0),
  1425. content_hash=content_hash,
  1426. printer_id=printer_id,
  1427. thumbnail_path=archive_data.get("thumbnail_path"),
  1428. timelapse_path=archive_data.get("timelapse_path"),
  1429. source_3mf_path=archive_data.get("source_3mf_path"),
  1430. f3d_path=archive_data.get("f3d_path"),
  1431. print_name=archive_data.get("print_name"),
  1432. print_time_seconds=archive_data.get("print_time_seconds"),
  1433. filament_used_grams=archive_data.get("filament_used_grams"),
  1434. filament_type=archive_data.get("filament_type"),
  1435. filament_color=archive_data.get("filament_color"),
  1436. layer_height=archive_data.get("layer_height"),
  1437. total_layers=archive_data.get("total_layers"),
  1438. nozzle_diameter=archive_data.get("nozzle_diameter"),
  1439. bed_temperature=archive_data.get("bed_temperature"),
  1440. nozzle_temperature=archive_data.get("nozzle_temperature"),
  1441. status=archive_data.get("status", "completed"),
  1442. makerworld_url=archive_data.get("makerworld_url"),
  1443. designer=archive_data.get("designer"),
  1444. external_url=archive_data.get("external_url"),
  1445. is_favorite=archive_data.get("is_favorite", False),
  1446. tags=archive_data.get("tags"),
  1447. notes=archive_data.get("notes"),
  1448. cost=archive_data.get("cost"),
  1449. failure_reason=archive_data.get("failure_reason"),
  1450. quantity=archive_data.get("quantity", 1),
  1451. energy_kwh=archive_data.get("energy_kwh"),
  1452. energy_cost=archive_data.get("energy_cost"),
  1453. extra_data=archive_data.get("extra_data"),
  1454. photos=archive_data.get("photos"),
  1455. )
  1456. db.add(archive)
  1457. restored["archives"] = restored.get("archives", 0) + 1
  1458. # Restore projects (skip or overwrite duplicates by name)
  1459. if "projects" in backup:
  1460. for project_data in backup["projects"]:
  1461. result = await db.execute(select(Project).where(Project.name == project_data["name"]))
  1462. existing = result.scalar_one_or_none()
  1463. if existing:
  1464. if overwrite:
  1465. # Update existing project
  1466. existing.description = project_data.get("description")
  1467. existing.color = project_data.get("color")
  1468. existing.status = project_data.get("status", "active")
  1469. existing.target_count = project_data.get("target_count")
  1470. existing.notes = project_data.get("notes")
  1471. existing.tags = project_data.get("tags")
  1472. existing.priority = project_data.get("priority", "normal")
  1473. existing.budget = project_data.get("budget")
  1474. existing.is_template = project_data.get("is_template", False)
  1475. existing.template_source_id = project_data.get("template_source_id")
  1476. existing.parent_id = project_data.get("parent_id")
  1477. existing.attachments = project_data.get("attachments")
  1478. if project_data.get("due_date"):
  1479. existing.due_date = datetime.fromisoformat(project_data["due_date"])
  1480. # Delete existing BOM items and re-add
  1481. await db.execute(ProjectBOMItem.__table__.delete().where(ProjectBOMItem.project_id == existing.id))
  1482. for bom_data in project_data.get("bom_items", []):
  1483. bom_item = ProjectBOMItem(
  1484. project_id=existing.id,
  1485. name=bom_data["name"],
  1486. quantity_needed=bom_data.get("quantity_needed", 1),
  1487. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1488. unit_price=bom_data.get("unit_price"),
  1489. sourcing_url=bom_data.get("sourcing_url"),
  1490. stl_filename=bom_data.get("stl_filename"),
  1491. remarks=bom_data.get("remarks"),
  1492. sort_order=bom_data.get("sort_order", 0),
  1493. )
  1494. db.add(bom_item)
  1495. restored["projects"] += 1
  1496. else:
  1497. skipped["projects"] += 1
  1498. skipped_details["projects"].append(project_data["name"])
  1499. else:
  1500. # Create new project
  1501. project = Project(
  1502. name=project_data["name"],
  1503. description=project_data.get("description"),
  1504. color=project_data.get("color"),
  1505. status=project_data.get("status", "active"),
  1506. target_count=project_data.get("target_count"),
  1507. notes=project_data.get("notes"),
  1508. tags=project_data.get("tags"),
  1509. priority=project_data.get("priority", "normal"),
  1510. budget=project_data.get("budget"),
  1511. is_template=project_data.get("is_template", False),
  1512. template_source_id=project_data.get("template_source_id"),
  1513. parent_id=project_data.get("parent_id"),
  1514. attachments=project_data.get("attachments"),
  1515. )
  1516. if project_data.get("due_date"):
  1517. project.due_date = datetime.fromisoformat(project_data["due_date"])
  1518. db.add(project)
  1519. await db.flush() # Get the project ID
  1520. # Add BOM items
  1521. for bom_data in project_data.get("bom_items", []):
  1522. bom_item = ProjectBOMItem(
  1523. project_id=project.id,
  1524. name=bom_data["name"],
  1525. quantity_needed=bom_data.get("quantity_needed", 1),
  1526. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1527. unit_price=bom_data.get("unit_price"),
  1528. sourcing_url=bom_data.get("sourcing_url"),
  1529. stl_filename=bom_data.get("stl_filename"),
  1530. remarks=bom_data.get("remarks"),
  1531. sort_order=bom_data.get("sort_order", 0),
  1532. )
  1533. db.add(bom_item)
  1534. restored["projects"] += 1
  1535. # Link archives to projects by name (after both are restored)
  1536. if "archives" in backup and "projects" in backup:
  1537. # Build project name to ID mapping
  1538. proj_result = await db.execute(select(Project))
  1539. project_name_to_id: dict[str, int] = {}
  1540. for proj in proj_result.scalars().all():
  1541. project_name_to_id[proj.name] = proj.id
  1542. # Update archives with project_id
  1543. for archive_data in backup["archives"]:
  1544. project_name = archive_data.get("project_name")
  1545. if project_name and project_name in project_name_to_id:
  1546. content_hash = archive_data.get("content_hash")
  1547. if content_hash:
  1548. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1549. archive = result.scalar_one_or_none()
  1550. if archive:
  1551. archive.project_id = project_name_to_id[project_name]
  1552. # Restore print queue (must be after archives and projects)
  1553. if "print_queue" in backup:
  1554. # Build lookups
  1555. printer_serial_to_id: dict[str, int] = {}
  1556. archive_hash_to_id: dict[str, int] = {}
  1557. project_name_to_id: dict[str, int] = {}
  1558. pr_result = await db.execute(select(Printer))
  1559. for pr in pr_result.scalars().all():
  1560. printer_serial_to_id[pr.serial_number] = pr.id
  1561. ar_result = await db.execute(select(PrintArchive))
  1562. for ar in ar_result.scalars().all():
  1563. if ar.content_hash:
  1564. archive_hash_to_id[ar.content_hash] = ar.id
  1565. proj_result = await db.execute(select(Project))
  1566. for proj in proj_result.scalars().all():
  1567. project_name_to_id[proj.name] = proj.id
  1568. restored["print_queue"] = 0
  1569. skipped["print_queue"] = 0
  1570. skipped_details["print_queue"] = []
  1571. for qi_data in backup["print_queue"]:
  1572. printer_serial = qi_data.get("printer_serial") # Can be None for unassigned items
  1573. archive_hash = qi_data.get("archive_hash")
  1574. # Archive is required, but printer can be None (unassigned)
  1575. if not archive_hash:
  1576. skipped["print_queue"] += 1
  1577. continue
  1578. # Look up printer_id (None if unassigned or printer not found)
  1579. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1580. archive_id = archive_hash_to_id.get(archive_hash)
  1581. # Archive must exist, but printer is optional (unassigned items)
  1582. if not archive_id:
  1583. skipped["print_queue"] += 1
  1584. skipped_details["print_queue"].append(
  1585. f"{printer_serial or 'unassigned'}/{archive_hash[:8] if archive_hash else 'N/A'}"
  1586. )
  1587. continue
  1588. # If printer_serial was specified but printer not found, skip
  1589. if printer_serial and not printer_id:
  1590. skipped["print_queue"] += 1
  1591. skipped_details["print_queue"].append(f"{printer_serial}/{archive_hash[:8]}")
  1592. continue
  1593. project_name = qi_data.get("project_name")
  1594. project_id = project_name_to_id.get(project_name) if project_name else None
  1595. qi = PrintQueueItem(
  1596. printer_id=printer_id, # Can be None for unassigned items
  1597. archive_id=archive_id,
  1598. project_id=project_id,
  1599. position=qi_data.get("position", 0),
  1600. require_previous_success=qi_data.get("require_previous_success", False),
  1601. auto_off_after=qi_data.get("auto_off_after", False),
  1602. manual_start=qi_data.get("manual_start", False),
  1603. ams_mapping=qi_data.get("ams_mapping"),
  1604. plate_id=qi_data.get("plate_id"),
  1605. bed_levelling=qi_data.get("bed_levelling", True),
  1606. flow_cali=qi_data.get("flow_cali", False),
  1607. vibration_cali=qi_data.get("vibration_cali", True),
  1608. layer_inspect=qi_data.get("layer_inspect", False),
  1609. timelapse=qi_data.get("timelapse", False),
  1610. use_ams=qi_data.get("use_ams", True),
  1611. status=qi_data.get("status", "pending"),
  1612. error_message=qi_data.get("error_message"),
  1613. )
  1614. if qi_data.get("scheduled_time"):
  1615. qi.scheduled_time = datetime.fromisoformat(qi_data["scheduled_time"])
  1616. if qi_data.get("started_at"):
  1617. qi.started_at = datetime.fromisoformat(qi_data["started_at"])
  1618. if qi_data.get("completed_at"):
  1619. qi.completed_at = datetime.fromisoformat(qi_data["completed_at"])
  1620. db.add(qi)
  1621. restored["print_queue"] += 1
  1622. # Restore pending uploads (skip duplicates by filename)
  1623. if "pending_uploads" in backup:
  1624. # Ensure the pending uploads directory exists
  1625. pending_uploads_dir = base_dir / "virtual_printer" / "uploads"
  1626. pending_uploads_dir.mkdir(parents=True, exist_ok=True)
  1627. for upload_data in backup["pending_uploads"]:
  1628. # Check for existing by filename
  1629. result = await db.execute(
  1630. select(PendingUpload).where(
  1631. PendingUpload.filename == upload_data["filename"],
  1632. PendingUpload.status == "pending",
  1633. )
  1634. )
  1635. existing = result.scalar_one_or_none()
  1636. if existing:
  1637. if overwrite:
  1638. # Update existing
  1639. existing.file_size = upload_data.get("file_size", 0)
  1640. existing.source_ip = upload_data.get("source_ip")
  1641. existing.tags = upload_data.get("tags")
  1642. existing.notes = upload_data.get("notes")
  1643. existing.project_id = upload_data.get("project_id")
  1644. # Update file path if file was restored from ZIP
  1645. if upload_data.get("file_path"):
  1646. restored_file = base_dir / upload_data["file_path"]
  1647. if restored_file.exists():
  1648. # Move to proper location
  1649. target_path = pending_uploads_dir / upload_data["filename"]
  1650. if restored_file != target_path:
  1651. import shutil
  1652. shutil.move(str(restored_file), str(target_path))
  1653. existing.file_path = str(target_path)
  1654. restored["pending_uploads"] += 1
  1655. else:
  1656. skipped["pending_uploads"] += 1
  1657. skipped_details["pending_uploads"].append(upload_data["filename"])
  1658. else:
  1659. # Determine file path
  1660. file_path_str = None
  1661. if upload_data.get("file_path"):
  1662. restored_file = base_dir / upload_data["file_path"]
  1663. if restored_file.exists():
  1664. # Move to proper location
  1665. target_path = pending_uploads_dir / upload_data["filename"]
  1666. if restored_file != target_path:
  1667. import shutil
  1668. shutil.move(str(restored_file), str(target_path))
  1669. file_path_str = str(target_path)
  1670. # Parse uploaded_at
  1671. uploaded_at = None
  1672. if upload_data.get("uploaded_at"):
  1673. try:
  1674. uploaded_at = datetime.fromisoformat(upload_data["uploaded_at"].replace("Z", "+00:00"))
  1675. except (ValueError, AttributeError):
  1676. uploaded_at = datetime.utcnow()
  1677. else:
  1678. uploaded_at = datetime.utcnow()
  1679. pending = PendingUpload(
  1680. filename=upload_data["filename"],
  1681. file_path=file_path_str or "",
  1682. file_size=upload_data.get("file_size", 0),
  1683. source_ip=upload_data.get("source_ip"),
  1684. status="pending",
  1685. tags=upload_data.get("tags"),
  1686. notes=upload_data.get("notes"),
  1687. project_id=upload_data.get("project_id"),
  1688. uploaded_at=uploaded_at,
  1689. )
  1690. db.add(pending)
  1691. restored["pending_uploads"] += 1
  1692. # Restore API keys (generates new keys since we can't restore the hash)
  1693. new_api_keys: list[dict] = [] # Track newly generated keys for response
  1694. if "api_keys" in backup:
  1695. from backend.app.core.auth import generate_api_key
  1696. # Build printer serial to ID mapping
  1697. printer_serial_to_id: dict[str, int] = {}
  1698. pr_result = await db.execute(select(Printer))
  1699. for pr in pr_result.scalars().all():
  1700. printer_serial_to_id[pr.serial_number] = pr.id
  1701. restored["api_keys"] = 0
  1702. skipped["api_keys"] = 0
  1703. skipped_details["api_keys"] = []
  1704. for key_data in backup["api_keys"]:
  1705. # Check if key with same name already exists
  1706. result = await db.execute(select(APIKey).where(APIKey.name == key_data["name"]))
  1707. existing = result.scalar_one_or_none()
  1708. if existing:
  1709. if overwrite:
  1710. # Update permissions but keep the existing key
  1711. existing.can_queue = key_data.get("can_queue", True)
  1712. existing.can_control_printer = key_data.get("can_control_printer", False)
  1713. existing.can_read_status = key_data.get("can_read_status", True)
  1714. existing.enabled = key_data.get("enabled", True)
  1715. if key_data.get("expires_at"):
  1716. existing.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1717. # Convert printer serials to IDs
  1718. if key_data.get("printer_serials"):
  1719. existing.printer_ids = [
  1720. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1721. ]
  1722. restored["api_keys"] += 1
  1723. else:
  1724. skipped["api_keys"] += 1
  1725. skipped_details["api_keys"].append(key_data["name"])
  1726. else:
  1727. # Generate new key
  1728. full_key, key_hash, key_prefix = generate_api_key()
  1729. # Convert printer serials to IDs
  1730. printer_ids = None
  1731. if key_data.get("printer_serials"):
  1732. printer_ids = [
  1733. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1734. ]
  1735. api_key = APIKey(
  1736. name=key_data["name"],
  1737. key_hash=key_hash,
  1738. key_prefix=key_prefix,
  1739. can_queue=key_data.get("can_queue", True),
  1740. can_control_printer=key_data.get("can_control_printer", False),
  1741. can_read_status=key_data.get("can_read_status", True),
  1742. printer_ids=printer_ids,
  1743. enabled=key_data.get("enabled", True),
  1744. )
  1745. if key_data.get("expires_at"):
  1746. api_key.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1747. db.add(api_key)
  1748. restored["api_keys"] += 1
  1749. # Track the new key so user can see it
  1750. new_api_keys.append(
  1751. {
  1752. "name": key_data["name"],
  1753. "key": full_key,
  1754. "key_prefix": key_prefix,
  1755. }
  1756. )
  1757. # Restore users (note: passwords not included in backup - users will need new passwords)
  1758. # Users are skipped by default since they have no passwords; admin must recreate them
  1759. new_users: list[str] = []
  1760. if "users" in backup:
  1761. from backend.app.core.auth import get_password_hash
  1762. for user_data in backup["users"]:
  1763. result = await db.execute(select(User).where(User.username == user_data["username"]))
  1764. existing = result.scalar_one_or_none()
  1765. if existing:
  1766. if overwrite:
  1767. existing.role = user_data.get("role", "user")
  1768. existing.is_active = user_data.get("is_active", True)
  1769. # Don't change password - keep existing
  1770. restored["users"] += 1
  1771. else:
  1772. skipped["users"] += 1
  1773. skipped_details["users"].append(user_data["username"])
  1774. else:
  1775. # Create user with a temporary password that must be changed
  1776. # Generate a random temporary password
  1777. import secrets
  1778. temp_password = secrets.token_urlsafe(16)
  1779. user = User(
  1780. username=user_data["username"],
  1781. password_hash=get_password_hash(temp_password),
  1782. role=user_data.get("role", "user"),
  1783. is_active=user_data.get("is_active", True),
  1784. )
  1785. db.add(user)
  1786. restored["users"] += 1
  1787. new_users.append(f"{user_data['username']} (temp password: {temp_password})")
  1788. await db.commit()
  1789. # If printers were in the backup (restored, updated, or skipped), reconnect all active printers
  1790. # This ensures connections are re-established after restore, even if printers were skipped
  1791. if "printers" in backup:
  1792. # Need fresh query after commit to get proper IDs for newly created printers
  1793. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1794. active_printers = result.scalars().all()
  1795. for printer in active_printers:
  1796. # This will disconnect existing connection (if any) and reconnect
  1797. try:
  1798. await printer_manager.connect_printer(printer)
  1799. except Exception:
  1800. pass # Connection failed, but don't fail the restore
  1801. # If settings were restored, check if Spoolman needs to be reconnected
  1802. if "settings" in backup:
  1803. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1804. spoolman_url = await get_setting(db, "spoolman_url")
  1805. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1806. try:
  1807. client = await init_spoolman_client(spoolman_url)
  1808. if await client.health_check():
  1809. pass # Connected successfully
  1810. except Exception:
  1811. pass # Spoolman connection failed, but don't fail the restore
  1812. # Reconfigure virtual printer if settings were restored
  1813. try:
  1814. from backend.app.services.virtual_printer import virtual_printer_manager
  1815. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1816. vp_access_code = await get_setting(db, "virtual_printer_access_code")
  1817. vp_mode = await get_setting(db, "virtual_printer_mode")
  1818. vp_model = await get_setting(db, "virtual_printer_model")
  1819. enabled = vp_enabled and vp_enabled.lower() == "true"
  1820. access_code = vp_access_code or ""
  1821. mode = vp_mode or "immediate"
  1822. model = vp_model or ""
  1823. if enabled and access_code:
  1824. await virtual_printer_manager.configure(
  1825. enabled=True,
  1826. access_code=access_code,
  1827. mode=mode,
  1828. model=model,
  1829. )
  1830. elif not enabled and virtual_printer_manager.is_enabled:
  1831. await virtual_printer_manager.configure(
  1832. enabled=False,
  1833. access_code=access_code,
  1834. mode=mode,
  1835. model=model,
  1836. )
  1837. except Exception:
  1838. pass # Virtual printer config failed, but don't fail the restore
  1839. # Reconfigure MQTT relay if settings were restored
  1840. try:
  1841. from backend.app.services.mqtt_relay import mqtt_relay
  1842. mqtt_settings = {
  1843. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  1844. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  1845. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  1846. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  1847. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  1848. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  1849. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  1850. }
  1851. await mqtt_relay.configure(mqtt_settings)
  1852. except Exception:
  1853. pass # MQTT relay config failed, but don't fail the restore
  1854. # Build summary message
  1855. restored_parts = []
  1856. for key, count in restored.items():
  1857. if count > 0:
  1858. restored_parts.append(f"{count} {key.replace('_', ' ')}")
  1859. if files_restored > 0:
  1860. restored_parts.append(f"{files_restored} files")
  1861. skipped_parts = []
  1862. total_skipped = sum(skipped.values())
  1863. for key, count in skipped.items():
  1864. if count > 0:
  1865. skipped_parts.append(f"{count} {key.replace('_', ' ')}")
  1866. message_parts = []
  1867. if restored_parts:
  1868. message_parts.append(f"Restored: {', '.join(restored_parts)}")
  1869. if skipped_parts:
  1870. message_parts.append(f"Skipped (already exist): {', '.join(skipped_parts)}")
  1871. response = {
  1872. "success": True,
  1873. "message": ". ".join(message_parts) if message_parts else "Nothing to restore",
  1874. "restored": restored,
  1875. "skipped": skipped,
  1876. "skipped_details": skipped_details,
  1877. "files_restored": files_restored,
  1878. "total_skipped": total_skipped,
  1879. }
  1880. # Include newly generated API keys if any (so user can see them)
  1881. if new_api_keys:
  1882. response["new_api_keys"] = new_api_keys
  1883. # Include newly created users with temp passwords (so admin can share them)
  1884. if new_users:
  1885. response["new_users"] = new_users
  1886. return response
  1887. # =============================================================================
  1888. # Virtual Printer Settings
  1889. # =============================================================================
  1890. @router.get("/virtual-printer/models")
  1891. async def get_virtual_printer_models():
  1892. """Get available virtual printer models."""
  1893. from backend.app.services.virtual_printer import (
  1894. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1895. VIRTUAL_PRINTER_MODELS,
  1896. )
  1897. return {
  1898. "models": VIRTUAL_PRINTER_MODELS,
  1899. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1900. }
  1901. @router.get("/virtual-printer")
  1902. async def get_virtual_printer_settings(db: AsyncSession = Depends(get_db)):
  1903. """Get virtual printer settings and status."""
  1904. from backend.app.services.virtual_printer import (
  1905. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1906. virtual_printer_manager,
  1907. )
  1908. enabled = await get_setting(db, "virtual_printer_enabled")
  1909. access_code = await get_setting(db, "virtual_printer_access_code")
  1910. mode = await get_setting(db, "virtual_printer_mode")
  1911. model = await get_setting(db, "virtual_printer_model")
  1912. return {
  1913. "enabled": enabled == "true" if enabled else False,
  1914. "access_code_set": bool(access_code),
  1915. "mode": mode or "immediate",
  1916. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1917. "status": virtual_printer_manager.get_status(),
  1918. }
  1919. @router.put("/virtual-printer")
  1920. async def update_virtual_printer_settings(
  1921. enabled: bool = None,
  1922. access_code: str = None,
  1923. mode: str = None,
  1924. model: str = None,
  1925. db: AsyncSession = Depends(get_db),
  1926. ):
  1927. """Update virtual printer settings and restart services if needed."""
  1928. from backend.app.services.virtual_printer import (
  1929. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1930. VIRTUAL_PRINTER_MODELS,
  1931. virtual_printer_manager,
  1932. )
  1933. # Get current values
  1934. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  1935. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1936. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1937. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  1938. # Apply updates
  1939. new_enabled = enabled if enabled is not None else current_enabled
  1940. new_access_code = access_code if access_code is not None else current_access_code
  1941. new_mode = mode if mode is not None else current_mode
  1942. new_model = model if model is not None else current_model
  1943. # Validate mode
  1944. # "review" is the new name for "queue" (pending review before archiving)
  1945. # "print_queue" archives and adds to print queue (unassigned)
  1946. if new_mode not in ("immediate", "queue", "review", "print_queue"):
  1947. return JSONResponse(
  1948. status_code=400,
  1949. content={"detail": "Mode must be 'immediate', 'review', or 'print_queue'"},
  1950. )
  1951. # Normalize legacy "queue" to "review" for storage
  1952. if new_mode == "queue":
  1953. new_mode = "review"
  1954. # Validate model
  1955. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  1956. return JSONResponse(
  1957. status_code=400,
  1958. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  1959. )
  1960. # Validate access code when enabling
  1961. if new_enabled and not new_access_code:
  1962. return JSONResponse(
  1963. status_code=400,
  1964. content={"detail": "Access code is required when enabling virtual printer"},
  1965. )
  1966. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1967. if access_code is not None and len(access_code) != 8:
  1968. return JSONResponse(
  1969. status_code=400,
  1970. content={"detail": "Access code must be exactly 8 characters"},
  1971. )
  1972. # Save settings
  1973. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1974. if access_code is not None:
  1975. await set_setting(db, "virtual_printer_access_code", access_code)
  1976. await set_setting(db, "virtual_printer_mode", new_mode)
  1977. if model is not None:
  1978. await set_setting(db, "virtual_printer_model", model)
  1979. await db.commit()
  1980. db.expire_all()
  1981. # Reconfigure virtual printer
  1982. try:
  1983. await virtual_printer_manager.configure(
  1984. enabled=new_enabled,
  1985. access_code=new_access_code,
  1986. mode=new_mode,
  1987. model=new_model,
  1988. )
  1989. except ValueError as e:
  1990. return JSONResponse(
  1991. status_code=400,
  1992. content={"detail": str(e)},
  1993. )
  1994. except Exception as e:
  1995. return JSONResponse(
  1996. status_code=500,
  1997. content={"detail": f"Failed to configure virtual printer: {e}"},
  1998. )
  1999. return await get_virtual_printer_settings(db)
  2000. # =============================================================================
  2001. # MQTT Relay Settings
  2002. # =============================================================================
  2003. @router.get("/mqtt/status")
  2004. async def get_mqtt_status():
  2005. """Get MQTT relay connection status."""
  2006. from backend.app.services.mqtt_relay import mqtt_relay
  2007. return mqtt_relay.get_status()