settings.py 94 KB

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