settings.py 91 KB

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