settings.py 89 KB

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