settings.py 97 KB

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