settings.py 105 KB

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