settings.py 96 KB

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