settings.py 107 KB

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