settings.py 95 KB

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