settings.py 83 KB

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