settings.py 114 KB

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