settings.py 95 KB

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