settings.py 110 KB

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