settings.py 105 KB

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