settings.py 91 KB

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