settings.py 111 KB

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