settings.py 96 KB

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