settings.py 107 KB

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