settings.py 88 KB

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