settings.py 102 KB

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