settings.py 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  1. import io
  2. import json
  3. import zipfile
  4. from datetime import datetime
  5. from pathlib import Path
  6. from fastapi import APIRouter, Depends, File, Query, UploadFile
  7. from fastapi.responses import JSONResponse, StreamingResponse
  8. from sqlalchemy import select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.config import settings as app_settings
  11. from backend.app.core.database import get_db
  12. from backend.app.models.api_key import APIKey
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.external_link import ExternalLink
  15. from backend.app.models.filament import Filament
  16. from backend.app.models.github_backup import GitHubBackupConfig
  17. from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
  18. from backend.app.models.notification import NotificationProvider
  19. from backend.app.models.notification_template import NotificationTemplate
  20. from backend.app.models.pending_upload import PendingUpload
  21. from backend.app.models.print_queue import PrintQueueItem
  22. from backend.app.models.printer import Printer
  23. from backend.app.models.project import Project
  24. from backend.app.models.project_bom import ProjectBOMItem
  25. from backend.app.models.settings import Settings
  26. from backend.app.models.smart_plug import SmartPlug
  27. from backend.app.models.user import User
  28. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  29. from backend.app.services.printer_manager import printer_manager
  30. from backend.app.services.spoolman import init_spoolman_client
  31. router = APIRouter(prefix="/settings", tags=["settings"])
  32. # Default settings
  33. DEFAULT_SETTINGS = AppSettings()
  34. async def get_setting(db: AsyncSession, key: str) -> str | None:
  35. """Get a single setting value by key."""
  36. result = await db.execute(select(Settings).where(Settings.key == key))
  37. setting = result.scalar_one_or_none()
  38. return setting.value if setting else None
  39. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  40. """Set a single setting value."""
  41. from sqlalchemy import func
  42. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  43. # Use upsert (INSERT ... ON CONFLICT UPDATE) for reliability
  44. stmt = sqlite_insert(Settings).values(key=key, value=value)
  45. stmt = stmt.on_conflict_do_update(index_elements=["key"], set_={"value": value, "updated_at": func.now()})
  46. await db.execute(stmt)
  47. @router.get("", response_model=AppSettings)
  48. @router.get("/", response_model=AppSettings)
  49. async def get_settings(db: AsyncSession = Depends(get_db)):
  50. """Get all application settings."""
  51. settings_dict = DEFAULT_SETTINGS.model_dump()
  52. # Load saved settings from database
  53. result = await db.execute(select(Settings))
  54. db_settings = result.scalars().all()
  55. for setting in db_settings:
  56. if setting.key in settings_dict:
  57. # Parse the value based on the expected type
  58. if setting.key in [
  59. "auto_archive",
  60. "save_thumbnails",
  61. "capture_finish_photo",
  62. "spoolman_enabled",
  63. "check_updates",
  64. "virtual_printer_enabled",
  65. "ftp_retry_enabled",
  66. "mqtt_enabled",
  67. "mqtt_use_tls",
  68. "ha_enabled",
  69. "per_printer_mapping_expanded",
  70. "prometheus_enabled",
  71. ]:
  72. settings_dict[setting.key] = setting.value.lower() == "true"
  73. elif setting.key in [
  74. "default_filament_cost",
  75. "energy_cost_per_kwh",
  76. "ams_temp_good",
  77. "ams_temp_fair",
  78. "library_disk_warning_gb",
  79. ]:
  80. settings_dict[setting.key] = float(setting.value)
  81. elif setting.key in [
  82. "ams_humidity_good",
  83. "ams_humidity_fair",
  84. "ams_history_retention_days",
  85. "ftp_retry_count",
  86. "ftp_retry_delay",
  87. "mqtt_port",
  88. ]:
  89. settings_dict[setting.key] = int(setting.value)
  90. elif setting.key == "default_printer_id":
  91. # Handle nullable integer
  92. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  93. else:
  94. settings_dict[setting.key] = setting.value
  95. return AppSettings(**settings_dict)
  96. @router.put("/", response_model=AppSettings)
  97. async def update_settings(
  98. settings_update: AppSettingsUpdate,
  99. db: AsyncSession = Depends(get_db),
  100. ):
  101. """Update application settings."""
  102. update_data = settings_update.model_dump(exclude_unset=True)
  103. # Check if any MQTT settings are being updated
  104. mqtt_keys = {
  105. "mqtt_enabled",
  106. "mqtt_broker",
  107. "mqtt_port",
  108. "mqtt_username",
  109. "mqtt_password",
  110. "mqtt_topic_prefix",
  111. "mqtt_use_tls",
  112. }
  113. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  114. for key, value in update_data.items():
  115. # Convert value to string for storage
  116. if isinstance(value, bool):
  117. str_value = "true" if value else "false"
  118. elif value is None:
  119. str_value = "None"
  120. else:
  121. str_value = str(value)
  122. await set_setting(db, key, str_value)
  123. await db.commit()
  124. # Expire all objects to ensure fresh reads after commit
  125. db.expire_all()
  126. # Reconfigure MQTT relay if any MQTT settings changed
  127. if mqtt_updated:
  128. try:
  129. from backend.app.services.mqtt_relay import mqtt_relay
  130. mqtt_settings = {
  131. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  132. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  133. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  134. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  135. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  136. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  137. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  138. }
  139. await mqtt_relay.configure(mqtt_settings)
  140. except Exception:
  141. pass # Don't fail the settings update if MQTT reconfiguration fails
  142. # Return updated settings
  143. return await get_settings(db)
  144. @router.patch("/", response_model=AppSettings)
  145. @router.patch("", response_model=AppSettings)
  146. async def patch_settings(
  147. settings_update: AppSettingsUpdate,
  148. db: AsyncSession = Depends(get_db),
  149. ):
  150. """Partially update application settings (same as PUT, for REST compatibility)."""
  151. return await update_settings(settings_update, db)
  152. @router.post("/reset", response_model=AppSettings)
  153. async def reset_settings(db: AsyncSession = Depends(get_db)):
  154. """Reset all settings to defaults."""
  155. # Delete all settings
  156. result = await db.execute(select(Settings))
  157. for setting in result.scalars().all():
  158. await db.delete(setting)
  159. await db.commit()
  160. return DEFAULT_SETTINGS
  161. @router.get("/check-ffmpeg")
  162. async def check_ffmpeg():
  163. """Check if ffmpeg is installed and available."""
  164. from backend.app.services.camera import get_ffmpeg_path
  165. ffmpeg_path = get_ffmpeg_path()
  166. return {
  167. "installed": ffmpeg_path is not None,
  168. "path": ffmpeg_path,
  169. }
  170. @router.get("/spoolman")
  171. async def get_spoolman_settings(db: AsyncSession = Depends(get_db)):
  172. """Get Spoolman integration settings."""
  173. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  174. spoolman_url = await get_setting(db, "spoolman_url") or ""
  175. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  176. return {
  177. "spoolman_enabled": spoolman_enabled,
  178. "spoolman_url": spoolman_url,
  179. "spoolman_sync_mode": spoolman_sync_mode,
  180. }
  181. @router.put("/spoolman")
  182. async def update_spoolman_settings(
  183. settings: dict,
  184. db: AsyncSession = Depends(get_db),
  185. ):
  186. """Update Spoolman integration settings."""
  187. if "spoolman_enabled" in settings:
  188. await set_setting(db, "spoolman_enabled", settings["spoolman_enabled"])
  189. if "spoolman_url" in settings:
  190. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  191. if "spoolman_sync_mode" in settings:
  192. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  193. await db.commit()
  194. db.expire_all()
  195. # Return updated settings
  196. return await get_spoolman_settings(db)
  197. @router.get("/backup")
  198. async def export_backup(
  199. db: AsyncSession = Depends(get_db),
  200. include_settings: bool = Query(True, description="Include app settings"),
  201. include_notifications: bool = Query(True, description="Include notification providers"),
  202. include_templates: bool = Query(True, description="Include notification templates"),
  203. include_smart_plugs: bool = Query(True, description="Include smart plugs"),
  204. include_external_links: bool = Query(True, description="Include external sidebar links"),
  205. include_printers: bool = Query(False, description="Include printers (without access codes)"),
  206. include_plate_calibration: bool = Query(False, description="Include plate detection reference images"),
  207. include_filaments: bool = Query(False, description="Include filament inventory"),
  208. include_maintenance: bool = Query(
  209. False, description="Include maintenance types, per-printer settings, and history"
  210. ),
  211. include_print_queue: bool = Query(False, description="Include print queue items"),
  212. include_archives: bool = Query(False, description="Include print archive metadata"),
  213. include_projects: bool = Query(False, description="Include projects with BOM items"),
  214. include_pending_uploads: bool = Query(False, description="Include pending virtual printer uploads"),
  215. include_access_codes: bool = Query(False, description="Include printer access codes (security risk!)"),
  216. include_api_keys: bool = Query(False, description="Include API keys (keys will need to be regenerated on import)"),
  217. include_users: bool = Query(
  218. False, description="Include users (passwords not exported - users will need new passwords)"
  219. ),
  220. include_github_backup: bool = Query(False, description="Include GitHub backup configuration (token not exported)"),
  221. ):
  222. """Export selected data as JSON backup."""
  223. backup: dict = {
  224. "version": "2.0",
  225. "exported_at": datetime.utcnow().isoformat(),
  226. "included": [],
  227. }
  228. # Settings
  229. if include_settings:
  230. result = await db.execute(select(Settings))
  231. db_settings = result.scalars().all()
  232. backup["settings"] = {s.key: s.value for s in db_settings}
  233. backup["included"].append("settings")
  234. # Notification providers
  235. if include_notifications:
  236. # Build printer ID to serial lookup for cross-system backup
  237. printer_id_to_serial: dict[int, str] = {}
  238. pr_result = await db.execute(select(Printer))
  239. for pr in pr_result.scalars().all():
  240. printer_id_to_serial[pr.id] = pr.serial_number
  241. result = await db.execute(select(NotificationProvider))
  242. providers = result.scalars().all()
  243. backup["notification_providers"] = []
  244. for p in providers:
  245. # Use printer_serial for cross-system compatibility
  246. provider_printer_id = getattr(p, "printer_id", None)
  247. printer_serial = printer_id_to_serial.get(provider_printer_id) if provider_printer_id else None
  248. backup["notification_providers"].append(
  249. {
  250. "name": p.name,
  251. "provider_type": p.provider_type,
  252. "enabled": p.enabled,
  253. "config": json.loads(p.config) if isinstance(p.config, str) else p.config,
  254. "on_print_start": p.on_print_start,
  255. "on_print_complete": p.on_print_complete,
  256. "on_print_failed": p.on_print_failed,
  257. "on_print_stopped": p.on_print_stopped,
  258. "on_print_progress": p.on_print_progress,
  259. "on_printer_offline": p.on_printer_offline,
  260. "on_printer_error": p.on_printer_error,
  261. "on_filament_low": p.on_filament_low,
  262. "on_maintenance_due": p.on_maintenance_due,
  263. "on_ams_humidity_high": getattr(p, "on_ams_humidity_high", False),
  264. "on_ams_temperature_high": getattr(p, "on_ams_temperature_high", False),
  265. "on_ams_ht_humidity_high": getattr(p, "on_ams_ht_humidity_high", False),
  266. "on_ams_ht_temperature_high": getattr(p, "on_ams_ht_temperature_high", False),
  267. "on_plate_not_empty": getattr(p, "on_plate_not_empty", True),
  268. "on_queue_job_added": getattr(p, "on_queue_job_added", False),
  269. "on_queue_job_assigned": getattr(p, "on_queue_job_assigned", False),
  270. "on_queue_job_started": getattr(p, "on_queue_job_started", False),
  271. "on_queue_job_waiting": getattr(p, "on_queue_job_waiting", True),
  272. "on_queue_job_skipped": getattr(p, "on_queue_job_skipped", True),
  273. "on_queue_job_failed": getattr(p, "on_queue_job_failed", True),
  274. "on_queue_completed": getattr(p, "on_queue_completed", False),
  275. "quiet_hours_enabled": p.quiet_hours_enabled,
  276. "quiet_hours_start": p.quiet_hours_start,
  277. "quiet_hours_end": p.quiet_hours_end,
  278. "daily_digest_enabled": getattr(p, "daily_digest_enabled", False),
  279. "daily_digest_time": getattr(p, "daily_digest_time", None),
  280. "printer_serial": printer_serial,
  281. }
  282. )
  283. backup["included"].append("notification_providers")
  284. # Notification templates
  285. if include_templates:
  286. result = await db.execute(select(NotificationTemplate))
  287. templates = result.scalars().all()
  288. backup["notification_templates"] = []
  289. for t in templates:
  290. backup["notification_templates"].append(
  291. {
  292. "event_type": t.event_type,
  293. "name": t.name,
  294. "title_template": t.title_template,
  295. "body_template": t.body_template,
  296. "is_default": t.is_default,
  297. }
  298. )
  299. backup["included"].append("notification_templates")
  300. # Smart plugs
  301. if include_smart_plugs:
  302. result = await db.execute(select(SmartPlug))
  303. plugs = result.scalars().all()
  304. backup["smart_plugs"] = []
  305. # Build printer ID to serial mapping
  306. printer_id_to_serial: dict[int, str] = {}
  307. pr_result = await db.execute(select(Printer))
  308. for pr in pr_result.scalars().all():
  309. printer_id_to_serial[pr.id] = pr.serial_number
  310. for plug in plugs:
  311. backup["smart_plugs"].append(
  312. {
  313. "name": plug.name,
  314. "plug_type": plug.plug_type,
  315. "ip_address": plug.ip_address,
  316. "ha_entity_id": plug.ha_entity_id,
  317. "ha_power_entity": plug.ha_power_entity,
  318. "ha_energy_today_entity": plug.ha_energy_today_entity,
  319. "ha_energy_total_entity": plug.ha_energy_total_entity,
  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.on_queue_job_added = provider_data.get("on_queue_job_added", False)
  1068. existing.on_queue_job_assigned = provider_data.get("on_queue_job_assigned", False)
  1069. existing.on_queue_job_started = provider_data.get("on_queue_job_started", False)
  1070. existing.on_queue_job_waiting = provider_data.get("on_queue_job_waiting", True)
  1071. existing.on_queue_job_skipped = provider_data.get("on_queue_job_skipped", True)
  1072. existing.on_queue_job_failed = provider_data.get("on_queue_job_failed", True)
  1073. existing.on_queue_completed = provider_data.get("on_queue_completed", False)
  1074. existing.quiet_hours_enabled = provider_data.get("quiet_hours_enabled", False)
  1075. existing.quiet_hours_start = provider_data.get("quiet_hours_start")
  1076. existing.quiet_hours_end = provider_data.get("quiet_hours_end")
  1077. existing.daily_digest_enabled = provider_data.get("daily_digest_enabled", False)
  1078. existing.daily_digest_time = provider_data.get("daily_digest_time")
  1079. existing.printer_id = printer_id
  1080. restored["notification_providers"] += 1
  1081. else:
  1082. skipped["notification_providers"] += 1
  1083. skipped_details["notification_providers"].append(provider_data["name"])
  1084. else:
  1085. provider = NotificationProvider(
  1086. name=provider_data["name"],
  1087. provider_type=provider_data["provider_type"],
  1088. enabled=provider_data.get("enabled", True),
  1089. config=json.dumps(provider_data.get("config", {})),
  1090. on_print_start=provider_data.get("on_print_start", False),
  1091. on_print_complete=provider_data.get("on_print_complete", True),
  1092. on_print_failed=provider_data.get("on_print_failed", True),
  1093. on_print_stopped=provider_data.get("on_print_stopped", True),
  1094. on_print_progress=provider_data.get("on_print_progress", False),
  1095. on_printer_offline=provider_data.get("on_printer_offline", False),
  1096. on_printer_error=provider_data.get("on_printer_error", False),
  1097. on_filament_low=provider_data.get("on_filament_low", False),
  1098. on_maintenance_due=provider_data.get("on_maintenance_due", False),
  1099. on_ams_humidity_high=provider_data.get("on_ams_humidity_high", False),
  1100. on_ams_temperature_high=provider_data.get("on_ams_temperature_high", False),
  1101. on_ams_ht_humidity_high=provider_data.get("on_ams_ht_humidity_high", False),
  1102. on_ams_ht_temperature_high=provider_data.get("on_ams_ht_temperature_high", False),
  1103. on_plate_not_empty=provider_data.get("on_plate_not_empty", True),
  1104. on_queue_job_added=provider_data.get("on_queue_job_added", False),
  1105. on_queue_job_assigned=provider_data.get("on_queue_job_assigned", False),
  1106. on_queue_job_started=provider_data.get("on_queue_job_started", False),
  1107. on_queue_job_waiting=provider_data.get("on_queue_job_waiting", True),
  1108. on_queue_job_skipped=provider_data.get("on_queue_job_skipped", True),
  1109. on_queue_job_failed=provider_data.get("on_queue_job_failed", True),
  1110. on_queue_completed=provider_data.get("on_queue_completed", False),
  1111. quiet_hours_enabled=provider_data.get("quiet_hours_enabled", False),
  1112. quiet_hours_start=provider_data.get("quiet_hours_start"),
  1113. quiet_hours_end=provider_data.get("quiet_hours_end"),
  1114. daily_digest_enabled=provider_data.get("daily_digest_enabled", False),
  1115. daily_digest_time=provider_data.get("daily_digest_time"),
  1116. printer_id=printer_id,
  1117. )
  1118. db.add(provider)
  1119. restored["notification_providers"] += 1
  1120. # Restore notification templates (update existing by event_type)
  1121. if "notification_templates" in backup:
  1122. for template_data in backup["notification_templates"]:
  1123. result = await db.execute(
  1124. select(NotificationTemplate).where(NotificationTemplate.event_type == template_data["event_type"])
  1125. )
  1126. existing = result.scalar_one_or_none()
  1127. if existing:
  1128. # Update existing template
  1129. existing.name = template_data.get("name", existing.name)
  1130. existing.title_template = template_data.get("title_template", existing.title_template)
  1131. existing.body_template = template_data.get("body_template", existing.body_template)
  1132. existing.is_default = template_data.get("is_default", False)
  1133. else:
  1134. template = NotificationTemplate(
  1135. event_type=template_data["event_type"],
  1136. name=template_data["name"],
  1137. title_template=template_data["title_template"],
  1138. body_template=template_data["body_template"],
  1139. is_default=template_data.get("is_default", False),
  1140. )
  1141. db.add(template)
  1142. restored["notification_templates"] += 1
  1143. # Restore smart plugs (skip or overwrite duplicates by IP)
  1144. # Note: Smart plugs reference printers, so printers should be restored first
  1145. if "smart_plugs" in backup:
  1146. # Build printer serial to ID lookup
  1147. printer_serial_to_id: dict[str, int] = {}
  1148. pr_result = await db.execute(select(Printer))
  1149. for pr in pr_result.scalars().all():
  1150. printer_serial_to_id[pr.serial_number] = pr.id
  1151. for plug_data in backup["smart_plugs"]:
  1152. # Look up printer_id from serial (supports both old printer_id and new printer_serial format)
  1153. printer_serial = plug_data.get("printer_serial")
  1154. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else plug_data.get("printer_id")
  1155. # Determine plug type (default to tasmota for backwards compatibility)
  1156. plug_type = plug_data.get("plug_type", "tasmota")
  1157. # Find existing plug by IP (Tasmota) or entity_id (Home Assistant)
  1158. existing = None
  1159. if plug_type == "homeassistant" and plug_data.get("ha_entity_id"):
  1160. result = await db.execute(select(SmartPlug).where(SmartPlug.ha_entity_id == plug_data["ha_entity_id"]))
  1161. existing = result.scalar_one_or_none()
  1162. plug_identifier = plug_data["ha_entity_id"]
  1163. elif plug_data.get("ip_address"):
  1164. result = await db.execute(select(SmartPlug).where(SmartPlug.ip_address == plug_data["ip_address"]))
  1165. existing = result.scalar_one_or_none()
  1166. plug_identifier = plug_data["ip_address"]
  1167. else:
  1168. # Skip invalid plug data
  1169. continue
  1170. if existing:
  1171. if overwrite:
  1172. existing.name = plug_data["name"]
  1173. existing.plug_type = plug_type
  1174. existing.ha_entity_id = plug_data.get("ha_entity_id")
  1175. existing.ha_power_entity = plug_data.get("ha_power_entity")
  1176. existing.ha_energy_today_entity = plug_data.get("ha_energy_today_entity")
  1177. existing.ha_energy_total_entity = plug_data.get("ha_energy_total_entity")
  1178. existing.printer_id = printer_id
  1179. existing.enabled = plug_data.get("enabled", True)
  1180. existing.auto_on = plug_data.get("auto_on", True)
  1181. existing.auto_off = plug_data.get("auto_off", True)
  1182. existing.off_delay_mode = plug_data.get("off_delay_mode", "time")
  1183. existing.off_delay_minutes = plug_data.get("off_delay_minutes", 5)
  1184. existing.off_temp_threshold = plug_data.get("off_temp_threshold", 70)
  1185. existing.username = plug_data.get("username")
  1186. existing.password = plug_data.get("password")
  1187. existing.power_alert_enabled = plug_data.get("power_alert_enabled", False)
  1188. existing.power_alert_high = plug_data.get("power_alert_high")
  1189. existing.power_alert_low = plug_data.get("power_alert_low")
  1190. existing.schedule_enabled = plug_data.get("schedule_enabled", False)
  1191. existing.schedule_on_time = plug_data.get("schedule_on_time")
  1192. existing.schedule_off_time = plug_data.get("schedule_off_time")
  1193. existing.show_in_switchbar = plug_data.get("show_in_switchbar", False)
  1194. restored["smart_plugs"] += 1
  1195. else:
  1196. skipped["smart_plugs"] += 1
  1197. skipped_details["smart_plugs"].append(f"{plug_data['name']} ({plug_identifier})")
  1198. else:
  1199. plug = SmartPlug(
  1200. name=plug_data["name"],
  1201. plug_type=plug_type,
  1202. ip_address=plug_data.get("ip_address"),
  1203. ha_entity_id=plug_data.get("ha_entity_id"),
  1204. ha_power_entity=plug_data.get("ha_power_entity"),
  1205. ha_energy_today_entity=plug_data.get("ha_energy_today_entity"),
  1206. ha_energy_total_entity=plug_data.get("ha_energy_total_entity"),
  1207. printer_id=printer_id,
  1208. enabled=plug_data.get("enabled", True),
  1209. auto_on=plug_data.get("auto_on", True),
  1210. auto_off=plug_data.get("auto_off", True),
  1211. off_delay_mode=plug_data.get("off_delay_mode", "time"),
  1212. off_delay_minutes=plug_data.get("off_delay_minutes", 5),
  1213. off_temp_threshold=plug_data.get("off_temp_threshold", 70),
  1214. username=plug_data.get("username"),
  1215. password=plug_data.get("password"),
  1216. power_alert_enabled=plug_data.get("power_alert_enabled", False),
  1217. power_alert_high=plug_data.get("power_alert_high"),
  1218. power_alert_low=plug_data.get("power_alert_low"),
  1219. schedule_enabled=plug_data.get("schedule_enabled", False),
  1220. schedule_on_time=plug_data.get("schedule_on_time"),
  1221. schedule_off_time=plug_data.get("schedule_off_time"),
  1222. show_in_switchbar=plug_data.get("show_in_switchbar", False),
  1223. )
  1224. db.add(plug)
  1225. restored["smart_plugs"] += 1
  1226. # Restore external links (skip or overwrite duplicates by name+url)
  1227. if "external_links" in backup:
  1228. icons_dir = base_dir / "icons"
  1229. icons_dir.mkdir(parents=True, exist_ok=True)
  1230. for link_data in backup["external_links"]:
  1231. result = await db.execute(
  1232. select(ExternalLink).where(ExternalLink.name == link_data["name"], ExternalLink.url == link_data["url"])
  1233. )
  1234. existing = result.scalar_one_or_none()
  1235. if existing:
  1236. if overwrite:
  1237. existing.icon = link_data.get("icon", "link")
  1238. existing.sort_order = link_data.get("sort_order", 0)
  1239. # Handle custom icon
  1240. if link_data.get("custom_icon"):
  1241. existing.custom_icon = link_data["custom_icon"]
  1242. restored["external_links"] += 1
  1243. else:
  1244. skipped["external_links"] += 1
  1245. skipped_details["external_links"].append(link_data["name"])
  1246. else:
  1247. link = ExternalLink(
  1248. name=link_data["name"],
  1249. url=link_data["url"],
  1250. icon=link_data.get("icon", "link"),
  1251. custom_icon=link_data.get("custom_icon"),
  1252. sort_order=link_data.get("sort_order", 0),
  1253. )
  1254. db.add(link)
  1255. restored["external_links"] += 1
  1256. # Restore filaments (skip or overwrite duplicates by name+type+brand)
  1257. if "filaments" in backup:
  1258. for filament_data in backup["filaments"]:
  1259. result = await db.execute(
  1260. select(Filament).where(
  1261. Filament.name == filament_data["name"],
  1262. Filament.type == filament_data["type"],
  1263. Filament.brand == filament_data.get("brand"),
  1264. )
  1265. )
  1266. existing = result.scalar_one_or_none()
  1267. if existing:
  1268. if overwrite:
  1269. existing.color = filament_data.get("color")
  1270. existing.color_hex = filament_data.get("color_hex")
  1271. existing.cost_per_kg = filament_data.get("cost_per_kg", 25.0)
  1272. existing.spool_weight_g = filament_data.get("spool_weight_g", 1000.0)
  1273. existing.currency = filament_data.get("currency", "USD")
  1274. existing.density = filament_data.get("density")
  1275. existing.print_temp_min = filament_data.get("print_temp_min")
  1276. existing.print_temp_max = filament_data.get("print_temp_max")
  1277. existing.bed_temp_min = filament_data.get("bed_temp_min")
  1278. existing.bed_temp_max = filament_data.get("bed_temp_max")
  1279. restored["filaments"] += 1
  1280. else:
  1281. skipped["filaments"] += 1
  1282. skipped_details["filaments"].append(
  1283. f"{filament_data.get('brand', '')} {filament_data['name']} ({filament_data['type']})"
  1284. )
  1285. else:
  1286. filament = Filament(
  1287. name=filament_data["name"],
  1288. type=filament_data["type"],
  1289. brand=filament_data.get("brand"),
  1290. color=filament_data.get("color"),
  1291. color_hex=filament_data.get("color_hex"),
  1292. cost_per_kg=filament_data.get("cost_per_kg", 25.0),
  1293. spool_weight_g=filament_data.get("spool_weight_g", 1000.0),
  1294. currency=filament_data.get("currency", "USD"),
  1295. density=filament_data.get("density"),
  1296. print_temp_min=filament_data.get("print_temp_min"),
  1297. print_temp_max=filament_data.get("print_temp_max"),
  1298. bed_temp_min=filament_data.get("bed_temp_min"),
  1299. bed_temp_max=filament_data.get("bed_temp_max"),
  1300. )
  1301. db.add(filament)
  1302. restored["filaments"] += 1
  1303. # Restore maintenance types (skip or overwrite duplicates by name)
  1304. if "maintenance_types" in backup:
  1305. for mt_data in backup["maintenance_types"]:
  1306. result = await db.execute(select(MaintenanceType).where(MaintenanceType.name == mt_data["name"]))
  1307. existing = result.scalar_one_or_none()
  1308. if existing:
  1309. if overwrite:
  1310. existing.description = mt_data.get("description")
  1311. existing.default_interval_hours = mt_data.get("default_interval_hours", 100.0)
  1312. existing.interval_type = mt_data.get("interval_type", "hours")
  1313. existing.icon = mt_data.get("icon")
  1314. # Don't overwrite is_system
  1315. restored["maintenance_types"] += 1
  1316. else:
  1317. skipped["maintenance_types"] += 1
  1318. skipped_details["maintenance_types"].append(mt_data["name"])
  1319. else:
  1320. mt = MaintenanceType(
  1321. name=mt_data["name"],
  1322. description=mt_data.get("description"),
  1323. default_interval_hours=mt_data.get("default_interval_hours", 100.0),
  1324. interval_type=mt_data.get("interval_type", "hours"),
  1325. icon=mt_data.get("icon"),
  1326. is_system=mt_data.get("is_system", False),
  1327. )
  1328. db.add(mt)
  1329. restored["maintenance_types"] += 1
  1330. # Restore printer maintenance settings (per-printer)
  1331. if "printer_maintenance" in backup:
  1332. # Build lookups
  1333. printer_serial_to_id: dict[str, int] = {}
  1334. maint_type_name_to_id: dict[str, int] = {}
  1335. pr_result = await db.execute(select(Printer))
  1336. for pr in pr_result.scalars().all():
  1337. printer_serial_to_id[pr.serial_number] = pr.id
  1338. mt_result = await db.execute(select(MaintenanceType))
  1339. for mt in mt_result.scalars().all():
  1340. maint_type_name_to_id[mt.name] = mt.id
  1341. restored["printer_maintenance"] = 0
  1342. skipped["printer_maintenance"] = 0
  1343. skipped_details["printer_maintenance"] = []
  1344. for pm_data in backup["printer_maintenance"]:
  1345. printer_serial = pm_data.get("printer_serial")
  1346. maint_type_name = pm_data.get("maintenance_type_name")
  1347. if not printer_serial or not maint_type_name:
  1348. continue
  1349. printer_id = printer_serial_to_id.get(printer_serial)
  1350. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1351. if not printer_id or not maint_type_id:
  1352. skipped["printer_maintenance"] += 1
  1353. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1354. continue
  1355. # Check if exists
  1356. result = await db.execute(
  1357. select(PrinterMaintenance).where(
  1358. PrinterMaintenance.printer_id == printer_id,
  1359. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1360. )
  1361. )
  1362. existing = result.scalar_one_or_none()
  1363. if existing:
  1364. if overwrite:
  1365. existing.custom_interval_hours = pm_data.get("custom_interval_hours")
  1366. existing.custom_interval_type = pm_data.get("custom_interval_type")
  1367. existing.enabled = pm_data.get("enabled", True)
  1368. existing.last_performed_hours = pm_data.get("last_performed_hours", 0.0)
  1369. if pm_data.get("last_performed_at"):
  1370. existing.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1371. restored["printer_maintenance"] += 1
  1372. else:
  1373. skipped["printer_maintenance"] += 1
  1374. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1375. else:
  1376. pm = PrinterMaintenance(
  1377. printer_id=printer_id,
  1378. maintenance_type_id=maint_type_id,
  1379. custom_interval_hours=pm_data.get("custom_interval_hours"),
  1380. custom_interval_type=pm_data.get("custom_interval_type"),
  1381. enabled=pm_data.get("enabled", True),
  1382. last_performed_hours=pm_data.get("last_performed_hours", 0.0),
  1383. )
  1384. if pm_data.get("last_performed_at"):
  1385. pm.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1386. db.add(pm)
  1387. restored["printer_maintenance"] += 1
  1388. # Restore maintenance history
  1389. if "maintenance_history" in backup:
  1390. # Build lookups
  1391. printer_serial_to_id: dict[str, int] = {}
  1392. maint_type_name_to_id: dict[str, int] = {}
  1393. pr_result = await db.execute(select(Printer))
  1394. for pr in pr_result.scalars().all():
  1395. printer_serial_to_id[pr.serial_number] = pr.id
  1396. mt_result = await db.execute(select(MaintenanceType))
  1397. for mt in mt_result.scalars().all():
  1398. maint_type_name_to_id[mt.name] = mt.id
  1399. restored["maintenance_history"] = 0
  1400. skipped["maintenance_history"] = 0
  1401. skipped_details["maintenance_history"] = []
  1402. for mh_data in backup["maintenance_history"]:
  1403. printer_serial = mh_data.get("printer_serial")
  1404. maint_type_name = mh_data.get("maintenance_type_name")
  1405. if not printer_serial or not maint_type_name:
  1406. continue
  1407. printer_id = printer_serial_to_id.get(printer_serial)
  1408. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1409. if not printer_id or not maint_type_id:
  1410. skipped["maintenance_history"] += 1
  1411. continue
  1412. # Find the PrinterMaintenance record
  1413. result = await db.execute(
  1414. select(PrinterMaintenance).where(
  1415. PrinterMaintenance.printer_id == printer_id,
  1416. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1417. )
  1418. )
  1419. pm = result.scalar_one_or_none()
  1420. if not pm:
  1421. skipped["maintenance_history"] += 1
  1422. continue
  1423. # Create history entry (no duplicate check - history is append-only)
  1424. mh = MaintenanceHistory(
  1425. printer_maintenance_id=pm.id,
  1426. hours_at_maintenance=mh_data.get("hours_at_maintenance", 0.0),
  1427. notes=mh_data.get("notes"),
  1428. )
  1429. if mh_data.get("performed_at"):
  1430. mh.performed_at = datetime.fromisoformat(mh_data["performed_at"])
  1431. db.add(mh)
  1432. restored["maintenance_history"] += 1
  1433. # Restore archives (skip duplicates by content_hash - overwrite not supported for archives)
  1434. if "archives" in backup:
  1435. # Build printer serial to ID mapping
  1436. printer_serial_to_id: dict[str, int] = {}
  1437. printer_result = await db.execute(select(Printer))
  1438. for pr in printer_result.scalars().all():
  1439. printer_serial_to_id[pr.serial_number] = pr.id
  1440. for archive_data in backup["archives"]:
  1441. # Skip if no content_hash or already exists
  1442. content_hash = archive_data.get("content_hash")
  1443. if content_hash:
  1444. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1445. existing = result.scalar_one_or_none()
  1446. if existing:
  1447. skipped["archives"] += 1
  1448. skipped_details["archives"].append(archive_data.get("filename", "Unknown"))
  1449. continue
  1450. # Only restore if file exists (from ZIP extraction)
  1451. file_path = archive_data.get("file_path")
  1452. if file_path and (base_dir / file_path).exists():
  1453. # Look up printer_id from serial
  1454. printer_serial = archive_data.get("printer_serial")
  1455. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1456. archive = PrintArchive(
  1457. filename=archive_data["filename"],
  1458. file_path=file_path,
  1459. file_size=archive_data.get("file_size", 0),
  1460. content_hash=content_hash,
  1461. printer_id=printer_id,
  1462. thumbnail_path=archive_data.get("thumbnail_path"),
  1463. timelapse_path=archive_data.get("timelapse_path"),
  1464. source_3mf_path=archive_data.get("source_3mf_path"),
  1465. f3d_path=archive_data.get("f3d_path"),
  1466. print_name=archive_data.get("print_name"),
  1467. print_time_seconds=archive_data.get("print_time_seconds"),
  1468. filament_used_grams=archive_data.get("filament_used_grams"),
  1469. filament_type=archive_data.get("filament_type"),
  1470. filament_color=archive_data.get("filament_color"),
  1471. layer_height=archive_data.get("layer_height"),
  1472. total_layers=archive_data.get("total_layers"),
  1473. nozzle_diameter=archive_data.get("nozzle_diameter"),
  1474. bed_temperature=archive_data.get("bed_temperature"),
  1475. nozzle_temperature=archive_data.get("nozzle_temperature"),
  1476. status=archive_data.get("status", "completed"),
  1477. makerworld_url=archive_data.get("makerworld_url"),
  1478. designer=archive_data.get("designer"),
  1479. external_url=archive_data.get("external_url"),
  1480. is_favorite=archive_data.get("is_favorite", False),
  1481. tags=archive_data.get("tags"),
  1482. notes=archive_data.get("notes"),
  1483. cost=archive_data.get("cost"),
  1484. failure_reason=archive_data.get("failure_reason"),
  1485. quantity=archive_data.get("quantity", 1),
  1486. energy_kwh=archive_data.get("energy_kwh"),
  1487. energy_cost=archive_data.get("energy_cost"),
  1488. extra_data=archive_data.get("extra_data"),
  1489. photos=archive_data.get("photos"),
  1490. )
  1491. db.add(archive)
  1492. restored["archives"] = restored.get("archives", 0) + 1
  1493. # Restore projects (skip or overwrite duplicates by name)
  1494. if "projects" in backup:
  1495. for project_data in backup["projects"]:
  1496. result = await db.execute(select(Project).where(Project.name == project_data["name"]))
  1497. existing = result.scalar_one_or_none()
  1498. if existing:
  1499. if overwrite:
  1500. # Update existing project
  1501. existing.description = project_data.get("description")
  1502. existing.color = project_data.get("color")
  1503. existing.status = project_data.get("status", "active")
  1504. existing.target_count = project_data.get("target_count")
  1505. existing.notes = project_data.get("notes")
  1506. existing.tags = project_data.get("tags")
  1507. existing.priority = project_data.get("priority", "normal")
  1508. existing.budget = project_data.get("budget")
  1509. existing.is_template = project_data.get("is_template", False)
  1510. existing.template_source_id = project_data.get("template_source_id")
  1511. existing.parent_id = project_data.get("parent_id")
  1512. existing.attachments = project_data.get("attachments")
  1513. if project_data.get("due_date"):
  1514. existing.due_date = datetime.fromisoformat(project_data["due_date"])
  1515. # Delete existing BOM items and re-add
  1516. await db.execute(ProjectBOMItem.__table__.delete().where(ProjectBOMItem.project_id == existing.id))
  1517. for bom_data in project_data.get("bom_items", []):
  1518. bom_item = ProjectBOMItem(
  1519. project_id=existing.id,
  1520. name=bom_data["name"],
  1521. quantity_needed=bom_data.get("quantity_needed", 1),
  1522. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1523. unit_price=bom_data.get("unit_price"),
  1524. sourcing_url=bom_data.get("sourcing_url"),
  1525. stl_filename=bom_data.get("stl_filename"),
  1526. remarks=bom_data.get("remarks"),
  1527. sort_order=bom_data.get("sort_order", 0),
  1528. )
  1529. db.add(bom_item)
  1530. restored["projects"] += 1
  1531. else:
  1532. skipped["projects"] += 1
  1533. skipped_details["projects"].append(project_data["name"])
  1534. else:
  1535. # Create new project
  1536. project = Project(
  1537. name=project_data["name"],
  1538. description=project_data.get("description"),
  1539. color=project_data.get("color"),
  1540. status=project_data.get("status", "active"),
  1541. target_count=project_data.get("target_count"),
  1542. notes=project_data.get("notes"),
  1543. tags=project_data.get("tags"),
  1544. priority=project_data.get("priority", "normal"),
  1545. budget=project_data.get("budget"),
  1546. is_template=project_data.get("is_template", False),
  1547. template_source_id=project_data.get("template_source_id"),
  1548. parent_id=project_data.get("parent_id"),
  1549. attachments=project_data.get("attachments"),
  1550. )
  1551. if project_data.get("due_date"):
  1552. project.due_date = datetime.fromisoformat(project_data["due_date"])
  1553. db.add(project)
  1554. await db.flush() # Get the project ID
  1555. # Add BOM items
  1556. for bom_data in project_data.get("bom_items", []):
  1557. bom_item = ProjectBOMItem(
  1558. project_id=project.id,
  1559. name=bom_data["name"],
  1560. quantity_needed=bom_data.get("quantity_needed", 1),
  1561. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1562. unit_price=bom_data.get("unit_price"),
  1563. sourcing_url=bom_data.get("sourcing_url"),
  1564. stl_filename=bom_data.get("stl_filename"),
  1565. remarks=bom_data.get("remarks"),
  1566. sort_order=bom_data.get("sort_order", 0),
  1567. )
  1568. db.add(bom_item)
  1569. restored["projects"] += 1
  1570. # Link archives to projects by name (after both are restored)
  1571. if "archives" in backup and "projects" in backup:
  1572. # Build project name to ID mapping
  1573. proj_result = await db.execute(select(Project))
  1574. project_name_to_id: dict[str, int] = {}
  1575. for proj in proj_result.scalars().all():
  1576. project_name_to_id[proj.name] = proj.id
  1577. # Update archives with project_id
  1578. for archive_data in backup["archives"]:
  1579. project_name = archive_data.get("project_name")
  1580. if project_name and project_name in project_name_to_id:
  1581. content_hash = archive_data.get("content_hash")
  1582. if content_hash:
  1583. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1584. archive = result.scalar_one_or_none()
  1585. if archive:
  1586. archive.project_id = project_name_to_id[project_name]
  1587. # Restore print queue (must be after archives and projects)
  1588. if "print_queue" in backup:
  1589. # Build lookups
  1590. printer_serial_to_id: dict[str, int] = {}
  1591. archive_hash_to_id: dict[str, int] = {}
  1592. project_name_to_id: dict[str, int] = {}
  1593. pr_result = await db.execute(select(Printer))
  1594. for pr in pr_result.scalars().all():
  1595. printer_serial_to_id[pr.serial_number] = pr.id
  1596. ar_result = await db.execute(select(PrintArchive))
  1597. for ar in ar_result.scalars().all():
  1598. if ar.content_hash:
  1599. archive_hash_to_id[ar.content_hash] = ar.id
  1600. proj_result = await db.execute(select(Project))
  1601. for proj in proj_result.scalars().all():
  1602. project_name_to_id[proj.name] = proj.id
  1603. restored["print_queue"] = 0
  1604. skipped["print_queue"] = 0
  1605. skipped_details["print_queue"] = []
  1606. for qi_data in backup["print_queue"]:
  1607. printer_serial = qi_data.get("printer_serial") # Can be None for unassigned items
  1608. archive_hash = qi_data.get("archive_hash")
  1609. # Archive is required, but printer can be None (unassigned)
  1610. if not archive_hash:
  1611. skipped["print_queue"] += 1
  1612. continue
  1613. # Look up printer_id (None if unassigned or printer not found)
  1614. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1615. archive_id = archive_hash_to_id.get(archive_hash)
  1616. # Archive must exist, but printer is optional (unassigned items)
  1617. if not archive_id:
  1618. skipped["print_queue"] += 1
  1619. skipped_details["print_queue"].append(
  1620. f"{printer_serial or 'unassigned'}/{archive_hash[:8] if archive_hash else 'N/A'}"
  1621. )
  1622. continue
  1623. # If printer_serial was specified but printer not found, skip
  1624. if printer_serial and not printer_id:
  1625. skipped["print_queue"] += 1
  1626. skipped_details["print_queue"].append(f"{printer_serial}/{archive_hash[:8]}")
  1627. continue
  1628. project_name = qi_data.get("project_name")
  1629. project_id = project_name_to_id.get(project_name) if project_name else None
  1630. qi = PrintQueueItem(
  1631. printer_id=printer_id, # Can be None for unassigned items
  1632. archive_id=archive_id,
  1633. project_id=project_id,
  1634. position=qi_data.get("position", 0),
  1635. require_previous_success=qi_data.get("require_previous_success", False),
  1636. auto_off_after=qi_data.get("auto_off_after", False),
  1637. manual_start=qi_data.get("manual_start", False),
  1638. ams_mapping=qi_data.get("ams_mapping"),
  1639. plate_id=qi_data.get("plate_id"),
  1640. bed_levelling=qi_data.get("bed_levelling", True),
  1641. flow_cali=qi_data.get("flow_cali", False),
  1642. vibration_cali=qi_data.get("vibration_cali", True),
  1643. layer_inspect=qi_data.get("layer_inspect", False),
  1644. timelapse=qi_data.get("timelapse", False),
  1645. use_ams=qi_data.get("use_ams", True),
  1646. status=qi_data.get("status", "pending"),
  1647. error_message=qi_data.get("error_message"),
  1648. )
  1649. if qi_data.get("scheduled_time"):
  1650. qi.scheduled_time = datetime.fromisoformat(qi_data["scheduled_time"])
  1651. if qi_data.get("started_at"):
  1652. qi.started_at = datetime.fromisoformat(qi_data["started_at"])
  1653. if qi_data.get("completed_at"):
  1654. qi.completed_at = datetime.fromisoformat(qi_data["completed_at"])
  1655. db.add(qi)
  1656. restored["print_queue"] += 1
  1657. # Restore pending uploads (skip duplicates by filename)
  1658. if "pending_uploads" in backup:
  1659. # Ensure the pending uploads directory exists
  1660. pending_uploads_dir = base_dir / "virtual_printer" / "uploads"
  1661. pending_uploads_dir.mkdir(parents=True, exist_ok=True)
  1662. for upload_data in backup["pending_uploads"]:
  1663. # Check for existing by filename
  1664. result = await db.execute(
  1665. select(PendingUpload).where(
  1666. PendingUpload.filename == upload_data["filename"],
  1667. PendingUpload.status == "pending",
  1668. )
  1669. )
  1670. existing = result.scalar_one_or_none()
  1671. if existing:
  1672. if overwrite:
  1673. # Update existing
  1674. existing.file_size = upload_data.get("file_size", 0)
  1675. existing.source_ip = upload_data.get("source_ip")
  1676. existing.tags = upload_data.get("tags")
  1677. existing.notes = upload_data.get("notes")
  1678. existing.project_id = upload_data.get("project_id")
  1679. # Update file path if file was restored from ZIP
  1680. if upload_data.get("file_path"):
  1681. restored_file = base_dir / upload_data["file_path"]
  1682. if restored_file.exists():
  1683. # Move to proper location
  1684. target_path = pending_uploads_dir / upload_data["filename"]
  1685. if restored_file != target_path:
  1686. import shutil
  1687. shutil.move(str(restored_file), str(target_path))
  1688. existing.file_path = str(target_path)
  1689. restored["pending_uploads"] += 1
  1690. else:
  1691. skipped["pending_uploads"] += 1
  1692. skipped_details["pending_uploads"].append(upload_data["filename"])
  1693. else:
  1694. # Determine file path
  1695. file_path_str = None
  1696. if upload_data.get("file_path"):
  1697. restored_file = base_dir / upload_data["file_path"]
  1698. if restored_file.exists():
  1699. # Move to proper location
  1700. target_path = pending_uploads_dir / upload_data["filename"]
  1701. if restored_file != target_path:
  1702. import shutil
  1703. shutil.move(str(restored_file), str(target_path))
  1704. file_path_str = str(target_path)
  1705. # Parse uploaded_at
  1706. uploaded_at = None
  1707. if upload_data.get("uploaded_at"):
  1708. try:
  1709. uploaded_at = datetime.fromisoformat(upload_data["uploaded_at"].replace("Z", "+00:00"))
  1710. except (ValueError, AttributeError):
  1711. uploaded_at = datetime.utcnow()
  1712. else:
  1713. uploaded_at = datetime.utcnow()
  1714. pending = PendingUpload(
  1715. filename=upload_data["filename"],
  1716. file_path=file_path_str or "",
  1717. file_size=upload_data.get("file_size", 0),
  1718. source_ip=upload_data.get("source_ip"),
  1719. status="pending",
  1720. tags=upload_data.get("tags"),
  1721. notes=upload_data.get("notes"),
  1722. project_id=upload_data.get("project_id"),
  1723. uploaded_at=uploaded_at,
  1724. )
  1725. db.add(pending)
  1726. restored["pending_uploads"] += 1
  1727. # Restore API keys (generates new keys since we can't restore the hash)
  1728. new_api_keys: list[dict] = [] # Track newly generated keys for response
  1729. if "api_keys" in backup:
  1730. from backend.app.core.auth import generate_api_key
  1731. # Build printer serial to ID mapping
  1732. printer_serial_to_id: dict[str, int] = {}
  1733. pr_result = await db.execute(select(Printer))
  1734. for pr in pr_result.scalars().all():
  1735. printer_serial_to_id[pr.serial_number] = pr.id
  1736. restored["api_keys"] = 0
  1737. skipped["api_keys"] = 0
  1738. skipped_details["api_keys"] = []
  1739. for key_data in backup["api_keys"]:
  1740. # Check if key with same name already exists
  1741. result = await db.execute(select(APIKey).where(APIKey.name == key_data["name"]))
  1742. existing = result.scalar_one_or_none()
  1743. if existing:
  1744. if overwrite:
  1745. # Update permissions but keep the existing key
  1746. existing.can_queue = key_data.get("can_queue", True)
  1747. existing.can_control_printer = key_data.get("can_control_printer", False)
  1748. existing.can_read_status = key_data.get("can_read_status", True)
  1749. existing.enabled = key_data.get("enabled", True)
  1750. if key_data.get("expires_at"):
  1751. existing.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1752. # Convert printer serials to IDs
  1753. if key_data.get("printer_serials"):
  1754. existing.printer_ids = [
  1755. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1756. ]
  1757. restored["api_keys"] += 1
  1758. else:
  1759. skipped["api_keys"] += 1
  1760. skipped_details["api_keys"].append(key_data["name"])
  1761. else:
  1762. # Generate new key
  1763. full_key, key_hash, key_prefix = generate_api_key()
  1764. # Convert printer serials to IDs
  1765. printer_ids = None
  1766. if key_data.get("printer_serials"):
  1767. printer_ids = [
  1768. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1769. ]
  1770. api_key = APIKey(
  1771. name=key_data["name"],
  1772. key_hash=key_hash,
  1773. key_prefix=key_prefix,
  1774. can_queue=key_data.get("can_queue", True),
  1775. can_control_printer=key_data.get("can_control_printer", False),
  1776. can_read_status=key_data.get("can_read_status", True),
  1777. printer_ids=printer_ids,
  1778. enabled=key_data.get("enabled", True),
  1779. )
  1780. if key_data.get("expires_at"):
  1781. api_key.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1782. db.add(api_key)
  1783. restored["api_keys"] += 1
  1784. # Track the new key so user can see it
  1785. new_api_keys.append(
  1786. {
  1787. "name": key_data["name"],
  1788. "key": full_key,
  1789. "key_prefix": key_prefix,
  1790. }
  1791. )
  1792. # Restore users (note: passwords not included in backup - users will need new passwords)
  1793. # Users are skipped by default since they have no passwords; admin must recreate them
  1794. new_users: list[str] = []
  1795. if "users" in backup:
  1796. from backend.app.core.auth import get_password_hash
  1797. for user_data in backup["users"]:
  1798. result = await db.execute(select(User).where(User.username == user_data["username"]))
  1799. existing = result.scalar_one_or_none()
  1800. if existing:
  1801. if overwrite:
  1802. existing.role = user_data.get("role", "user")
  1803. existing.is_active = user_data.get("is_active", True)
  1804. # Don't change password - keep existing
  1805. restored["users"] += 1
  1806. else:
  1807. skipped["users"] += 1
  1808. skipped_details["users"].append(user_data["username"])
  1809. else:
  1810. # Create user with a temporary password that must be changed
  1811. # Generate a random temporary password
  1812. import secrets
  1813. temp_password = secrets.token_urlsafe(16)
  1814. user = User(
  1815. username=user_data["username"],
  1816. password_hash=get_password_hash(temp_password),
  1817. role=user_data.get("role", "user"),
  1818. is_active=user_data.get("is_active", True),
  1819. )
  1820. db.add(user)
  1821. restored["users"] += 1
  1822. new_users.append(f"{user_data['username']} (temp password: {temp_password})")
  1823. # Restore GitHub backup configuration (note: access_token not included for security)
  1824. if "github_backup" in backup:
  1825. github_data = backup["github_backup"]
  1826. result = await db.execute(select(GitHubBackupConfig).limit(1))
  1827. existing = result.scalar_one_or_none()
  1828. if existing:
  1829. if overwrite:
  1830. existing.repository_url = github_data.get("repository_url", existing.repository_url)
  1831. existing.branch = github_data.get("branch", existing.branch)
  1832. existing.schedule_enabled = github_data.get("schedule_enabled", existing.schedule_enabled)
  1833. existing.schedule_type = github_data.get("schedule_type", existing.schedule_type)
  1834. existing.backup_kprofiles = github_data.get("backup_kprofiles", existing.backup_kprofiles)
  1835. existing.backup_cloud_profiles = github_data.get(
  1836. "backup_cloud_profiles", existing.backup_cloud_profiles
  1837. )
  1838. existing.backup_settings = github_data.get("backup_settings", existing.backup_settings)
  1839. existing.enabled = github_data.get("enabled", existing.enabled)
  1840. # Note: access_token must be re-entered after restore
  1841. restored["github_backup"] += 1
  1842. else:
  1843. skipped["github_backup"] += 1
  1844. else:
  1845. config = GitHubBackupConfig(
  1846. repository_url=github_data.get("repository_url", ""),
  1847. access_token="", # Must be entered after restore
  1848. branch=github_data.get("branch", "main"),
  1849. schedule_enabled=github_data.get("schedule_enabled", False),
  1850. schedule_type=github_data.get("schedule_type", "daily"),
  1851. backup_kprofiles=github_data.get("backup_kprofiles", True),
  1852. backup_cloud_profiles=github_data.get("backup_cloud_profiles", True),
  1853. backup_settings=github_data.get("backup_settings", False),
  1854. enabled=False, # Disabled until token is entered
  1855. )
  1856. db.add(config)
  1857. restored["github_backup"] += 1
  1858. await db.commit()
  1859. # If printers were in the backup (restored, updated, or skipped), reconnect all active printers
  1860. # This ensures connections are re-established after restore, even if printers were skipped
  1861. if "printers" in backup:
  1862. # Need fresh query after commit to get proper IDs for newly created printers
  1863. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1864. active_printers = result.scalars().all()
  1865. for printer in active_printers:
  1866. # This will disconnect existing connection (if any) and reconnect
  1867. try:
  1868. await printer_manager.connect_printer(printer)
  1869. except Exception:
  1870. pass # Connection failed, but don't fail the restore
  1871. # If settings were restored, check if Spoolman needs to be reconnected
  1872. if "settings" in backup:
  1873. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1874. spoolman_url = await get_setting(db, "spoolman_url")
  1875. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1876. try:
  1877. client = await init_spoolman_client(spoolman_url)
  1878. if await client.health_check():
  1879. pass # Connected successfully
  1880. except Exception:
  1881. pass # Spoolman connection failed, but don't fail the restore
  1882. # Reconfigure virtual printer if settings were restored
  1883. try:
  1884. from backend.app.services.virtual_printer import virtual_printer_manager
  1885. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1886. vp_access_code = await get_setting(db, "virtual_printer_access_code")
  1887. vp_mode = await get_setting(db, "virtual_printer_mode")
  1888. vp_model = await get_setting(db, "virtual_printer_model")
  1889. enabled = vp_enabled and vp_enabled.lower() == "true"
  1890. access_code = vp_access_code or ""
  1891. mode = vp_mode or "immediate"
  1892. model = vp_model or ""
  1893. if enabled and access_code:
  1894. await virtual_printer_manager.configure(
  1895. enabled=True,
  1896. access_code=access_code,
  1897. mode=mode,
  1898. model=model,
  1899. )
  1900. elif not enabled and virtual_printer_manager.is_enabled:
  1901. await virtual_printer_manager.configure(
  1902. enabled=False,
  1903. access_code=access_code,
  1904. mode=mode,
  1905. model=model,
  1906. )
  1907. except Exception:
  1908. pass # Virtual printer config failed, but don't fail the restore
  1909. # Reconfigure MQTT relay if settings were restored
  1910. try:
  1911. from backend.app.services.mqtt_relay import mqtt_relay
  1912. mqtt_settings = {
  1913. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  1914. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  1915. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  1916. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  1917. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  1918. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  1919. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  1920. }
  1921. await mqtt_relay.configure(mqtt_settings)
  1922. except Exception:
  1923. pass # MQTT relay config failed, but don't fail the restore
  1924. # Build summary message
  1925. restored_parts = []
  1926. for key, count in restored.items():
  1927. if count > 0:
  1928. restored_parts.append(f"{count} {key.replace('_', ' ')}")
  1929. if files_restored > 0:
  1930. restored_parts.append(f"{files_restored} files")
  1931. skipped_parts = []
  1932. total_skipped = sum(skipped.values())
  1933. for key, count in skipped.items():
  1934. if count > 0:
  1935. skipped_parts.append(f"{count} {key.replace('_', ' ')}")
  1936. message_parts = []
  1937. if restored_parts:
  1938. message_parts.append(f"Restored: {', '.join(restored_parts)}")
  1939. if skipped_parts:
  1940. message_parts.append(f"Skipped (already exist): {', '.join(skipped_parts)}")
  1941. response = {
  1942. "success": True,
  1943. "message": ". ".join(message_parts) if message_parts else "Nothing to restore",
  1944. "restored": restored,
  1945. "skipped": skipped,
  1946. "skipped_details": skipped_details,
  1947. "files_restored": files_restored,
  1948. "total_skipped": total_skipped,
  1949. }
  1950. # Include newly generated API keys if any (so user can see them)
  1951. if new_api_keys:
  1952. response["new_api_keys"] = new_api_keys
  1953. # Include newly created users with temp passwords (so admin can share them)
  1954. if new_users:
  1955. response["new_users"] = new_users
  1956. return response
  1957. # =============================================================================
  1958. # Virtual Printer Settings
  1959. # =============================================================================
  1960. @router.get("/virtual-printer/models")
  1961. async def get_virtual_printer_models():
  1962. """Get available virtual printer models."""
  1963. from backend.app.services.virtual_printer import (
  1964. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1965. VIRTUAL_PRINTER_MODELS,
  1966. )
  1967. return {
  1968. "models": VIRTUAL_PRINTER_MODELS,
  1969. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1970. }
  1971. @router.get("/virtual-printer")
  1972. async def get_virtual_printer_settings(db: AsyncSession = Depends(get_db)):
  1973. """Get virtual printer settings and status."""
  1974. from backend.app.services.virtual_printer import (
  1975. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1976. virtual_printer_manager,
  1977. )
  1978. enabled = await get_setting(db, "virtual_printer_enabled")
  1979. access_code = await get_setting(db, "virtual_printer_access_code")
  1980. mode = await get_setting(db, "virtual_printer_mode")
  1981. model = await get_setting(db, "virtual_printer_model")
  1982. return {
  1983. "enabled": enabled == "true" if enabled else False,
  1984. "access_code_set": bool(access_code),
  1985. "mode": mode or "immediate",
  1986. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1987. "status": virtual_printer_manager.get_status(),
  1988. }
  1989. @router.put("/virtual-printer")
  1990. async def update_virtual_printer_settings(
  1991. enabled: bool = None,
  1992. access_code: str = None,
  1993. mode: str = None,
  1994. model: str = None,
  1995. db: AsyncSession = Depends(get_db),
  1996. ):
  1997. """Update virtual printer settings and restart services if needed."""
  1998. from backend.app.services.virtual_printer import (
  1999. DEFAULT_VIRTUAL_PRINTER_MODEL,
  2000. VIRTUAL_PRINTER_MODELS,
  2001. virtual_printer_manager,
  2002. )
  2003. # Get current values
  2004. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  2005. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  2006. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  2007. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  2008. # Apply updates
  2009. new_enabled = enabled if enabled is not None else current_enabled
  2010. new_access_code = access_code if access_code is not None else current_access_code
  2011. new_mode = mode if mode is not None else current_mode
  2012. new_model = model if model is not None else current_model
  2013. # Validate mode
  2014. # "review" is the new name for "queue" (pending review before archiving)
  2015. # "print_queue" archives and adds to print queue (unassigned)
  2016. if new_mode not in ("immediate", "queue", "review", "print_queue"):
  2017. return JSONResponse(
  2018. status_code=400,
  2019. content={"detail": "Mode must be 'immediate', 'review', or 'print_queue'"},
  2020. )
  2021. # Normalize legacy "queue" to "review" for storage
  2022. if new_mode == "queue":
  2023. new_mode = "review"
  2024. # Validate model
  2025. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  2026. return JSONResponse(
  2027. status_code=400,
  2028. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  2029. )
  2030. # Validate access code when enabling
  2031. if new_enabled and not new_access_code:
  2032. return JSONResponse(
  2033. status_code=400,
  2034. content={"detail": "Access code is required when enabling virtual printer"},
  2035. )
  2036. # Validate access code length (Bambu Studio requires exactly 8 characters)
  2037. if access_code is not None and len(access_code) != 8:
  2038. return JSONResponse(
  2039. status_code=400,
  2040. content={"detail": "Access code must be exactly 8 characters"},
  2041. )
  2042. # Save settings
  2043. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  2044. if access_code is not None:
  2045. await set_setting(db, "virtual_printer_access_code", access_code)
  2046. await set_setting(db, "virtual_printer_mode", new_mode)
  2047. if model is not None:
  2048. await set_setting(db, "virtual_printer_model", model)
  2049. await db.commit()
  2050. db.expire_all()
  2051. # Reconfigure virtual printer
  2052. try:
  2053. await virtual_printer_manager.configure(
  2054. enabled=new_enabled,
  2055. access_code=new_access_code,
  2056. mode=new_mode,
  2057. model=new_model,
  2058. )
  2059. except ValueError as e:
  2060. return JSONResponse(
  2061. status_code=400,
  2062. content={"detail": str(e)},
  2063. )
  2064. except Exception as e:
  2065. return JSONResponse(
  2066. status_code=500,
  2067. content={"detail": f"Failed to configure virtual printer: {e}"},
  2068. )
  2069. return await get_virtual_printer_settings(db)
  2070. # =============================================================================
  2071. # MQTT Relay Settings
  2072. # =============================================================================
  2073. @router.get("/mqtt/status")
  2074. async def get_mqtt_status():
  2075. """Get MQTT relay connection status."""
  2076. from backend.app.services.mqtt_relay import mqtt_relay
  2077. return mqtt_relay.get_status()