settings.py 105 KB

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