settings.py 95 KB

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