github_backup.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. """GitHub backup service for printer profiles.
  2. Handles scheduled and on-demand backups of K-profiles and cloud profiles to GitHub.
  3. """
  4. import asyncio
  5. import logging
  6. from datetime import datetime, timedelta, timezone
  7. import httpx
  8. from sqlalchemy import desc, or_, select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.database import async_session
  11. from backend.app.core.logging_filters import URL_CREDENTIALS_PATTERN, redact_refused_headers
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  14. from backend.app.models.printer import Printer
  15. from backend.app.models.settings import Settings
  16. from backend.app.models.spool import Spool
  17. from backend.app.models.spool_usage_history import SpoolUsageHistory
  18. from backend.app.models.user import User
  19. from backend.app.services.git_providers.factory import get_provider_backend
  20. from backend.app.services.github_restore import is_restorable_setting_key
  21. from backend.app.services.printer_manager import printer_manager
  22. from backend.app.services.secret_fields import SECRET_PLACEHOLDER, is_secret_setting_key, mask_preset
  23. logger = logging.getLogger(__name__)
  24. # Bambu's listing endpoint is keyed by preset type and calls process presets
  25. # "print". Same mapping as `routes/cloud.py` — kept in step with it, since a
  26. # divergence here silently drops a whole preset type from every backup.
  27. _BAMBU_PRESET_TYPES = {
  28. "filament": "filament",
  29. "printer": "printer",
  30. "print": "process",
  31. }
  32. def _bambu_preset_record(setting_id, our_type: str, entry: dict, detail: dict) -> dict:
  33. """One Bambu preset as stored in the backup: metadata plus the payload.
  34. ``base_id`` and ``setting`` are the two fields ``BambuCloudService.
  35. create_setting`` needs, so a restore can rebuild the preset rather than
  36. just list it.
  37. ``user_id`` from the listing is deliberately dropped. It identifies the
  38. account and adds nothing to a rebuild, and backup repositories can be
  39. public. A printer connection's credentials in ``setting`` are shown as
  40. the placeholder.
  41. """
  42. return {
  43. "setting_id": str(setting_id),
  44. "name": detail.get("name") or entry.get("name") or "Unknown",
  45. "type": our_type,
  46. "version": detail.get("version") or entry.get("version"),
  47. "updated_time": entry.get("updated_time"),
  48. "base_id": detail.get("base_id"),
  49. "filament_id": detail.get("filament_id"),
  50. "setting": mask_preset(detail.get("setting") or {}),
  51. }
  52. def _orca_profile_record(entry: dict) -> dict:
  53. """One Orca profile as stored in the backup.
  54. ``content`` is kept whole rather than picked apart: it is the profile, the
  55. sync API hands it over inline, and Orca owns its shape. Narrowing it here
  56. would mean guessing which keys a future restore needs. A printer
  57. connection's credentials are the exception: shown as the placeholder.
  58. """
  59. return {
  60. "id": str(entry.get("id")) if entry.get("id") is not None else None,
  61. "name": entry.get("name"),
  62. "updated_time": entry.get("updated_time"),
  63. "created_time": entry.get("created_time"),
  64. "content": mask_preset(entry.get("content")),
  65. }
  66. # Schedule intervals in seconds
  67. SCHEDULE_INTERVALS = {
  68. "hourly": 3600,
  69. "daily": 86400,
  70. "weekly": 604800,
  71. }
  72. _PROVIDER_DISPLAY_NAMES = {
  73. "github": "GitHub",
  74. "gitlab": "GitLab",
  75. "gitea": "Gitea",
  76. "forgejo": "Forgejo",
  77. }
  78. def _without_refused_headers(result: dict) -> dict:
  79. """*result* with its texts masked where an HTTP client refusing a header
  80. quoted the value: the stored token, which the API never returns."""
  81. return {key: redact_refused_headers(value) if isinstance(value, str) else value for key, value in result.items()}
  82. class GitHubBackupService:
  83. """Service for backing up profiles to GitHub."""
  84. def __init__(self):
  85. self._scheduler_task: asyncio.Task | None = None
  86. self._check_interval = 60 # Check every minute for scheduled runs
  87. self._running_backup: bool = False
  88. self._backup_progress: str | None = None
  89. self._http_client: httpx.AsyncClient | None = None
  90. async def _get_client(self) -> httpx.AsyncClient:
  91. """Get or create HTTP client."""
  92. if self._http_client is None or self._http_client.is_closed:
  93. self._http_client = httpx.AsyncClient(timeout=60.0)
  94. return self._http_client
  95. async def start_scheduler(self):
  96. """Start the background scheduler loop."""
  97. if self._scheduler_task is not None:
  98. return
  99. logger.info("Starting GitHub backup scheduler")
  100. self._scheduler_task = asyncio.create_task(self._scheduler_loop())
  101. def stop_scheduler(self):
  102. """Stop the scheduler."""
  103. if self._scheduler_task:
  104. self._scheduler_task.cancel()
  105. self._scheduler_task = None
  106. logger.info("Stopped GitHub backup scheduler")
  107. async def _scheduler_loop(self):
  108. """Main scheduler loop - checks for due backups."""
  109. while True:
  110. try:
  111. await asyncio.sleep(self._check_interval)
  112. await self._check_scheduled_backups()
  113. except asyncio.CancelledError:
  114. break
  115. except Exception:
  116. logger.exception("Error in GitHub backup scheduler")
  117. await asyncio.sleep(60)
  118. async def _check_scheduled_backups(self):
  119. """Check if any scheduled backups are due."""
  120. async with async_session() as db:
  121. result = await db.execute(
  122. select(GitHubBackupConfig).where(
  123. GitHubBackupConfig.enabled == True, # noqa: E712
  124. GitHubBackupConfig.schedule_enabled == True, # noqa: E712
  125. )
  126. )
  127. configs = result.scalars().all()
  128. now = datetime.now(timezone.utc)
  129. for config in configs:
  130. # Handle both naive (from DB) and aware datetimes
  131. next_run = config.next_scheduled_run
  132. if next_run and next_run.tzinfo is None:
  133. next_run = next_run.replace(tzinfo=timezone.utc)
  134. if next_run and next_run <= now:
  135. logger.info("Running scheduled backup for config %s", config.id)
  136. await self.run_backup(config.id, trigger="scheduled")
  137. def calculate_next_run(self, schedule_type: str, from_time: datetime | None = None) -> datetime:
  138. """Calculate the next scheduled run time."""
  139. now = from_time or datetime.now(timezone.utc)
  140. interval = SCHEDULE_INTERVALS.get(schedule_type, SCHEDULE_INTERVALS["daily"])
  141. return now + timedelta(seconds=interval)
  142. async def test_connection(self, repo_url: str, token: str, provider: str = "github") -> dict:
  143. """Test connection and permissions for the given provider."""
  144. backend = get_provider_backend(provider)
  145. client = await self._get_client()
  146. return _without_refused_headers(await backend.test_connection(repo_url, token, client))
  147. async def run_backup(self, config_id: int, trigger: str = "manual") -> dict:
  148. """Run a backup operation.
  149. Args:
  150. config_id: ID of the backup configuration
  151. trigger: "manual" or "scheduled"
  152. Returns:
  153. dict with success, message, log_id, commit_sha, files_changed
  154. """
  155. # Everything from here to `self._running_backup = True` must stay
  156. # await-free. Both flags are plain bools and both callers are coroutines
  157. # on one event loop, so with no suspension point in between the loop
  158. # cannot run the restore service's mirror-image region (see
  159. # github_restore.run_restore) in the gap — whichever gets here first sets
  160. # its flag before the other can read it. Adding an `await` inside this
  161. # block reintroduces the check-then-set race and lets a backup and a
  162. # restore run at once.
  163. if self._running_backup:
  164. return {"success": False, "message": "A backup is already running", "log_id": None}
  165. # Imported locally to avoid a module-level import cycle — the restore
  166. # service imports this module's singleton to take the mirror-image lock.
  167. # A restore rewrites the same tables this collector reads and publishes
  168. # K-profiles to the same printers, so the two must not interleave.
  169. # (A local `import` of an already-loaded module is not a suspension
  170. # point, so it does not break the await-free rule above.)
  171. from backend.app.services.github_restore import github_restore_service
  172. if github_restore_service.is_running:
  173. return {
  174. "success": False,
  175. "message": "A restore is currently running. Wait for it to finish before backing up.",
  176. "log_id": None,
  177. }
  178. self._running_backup = True
  179. log_id = None
  180. try:
  181. async with async_session() as db:
  182. # Get config
  183. result = await db.execute(select(GitHubBackupConfig).where(GitHubBackupConfig.id == config_id))
  184. config = result.scalar_one_or_none()
  185. if not config:
  186. return {"success": False, "message": "Configuration not found", "log_id": None}
  187. if not config.enabled:
  188. return {"success": False, "message": "Backup is disabled", "log_id": None}
  189. # Defense in depth: re-verify the repo is private before each
  190. # push. The save endpoint already enforces this on every config
  191. # change, but a user can flip a repo from private to public in
  192. # GitHub's UI between configuration and the next scheduled run.
  193. test_result = await self.test_connection(
  194. config.repository_url, config.access_token, provider=config.provider
  195. )
  196. if not test_result.get("success") or test_result.get("is_private") is not True:
  197. visibility_note = (
  198. "the target repository is no longer private"
  199. if test_result.get("is_private") is False
  200. else "could not confirm the target repository is private"
  201. )
  202. abort_message = (
  203. f"Backup aborted: {visibility_note}. Bambuddy backups carry credentials "
  204. "and are refused for any non-private target. Make the repository private "
  205. "to resume scheduled backups."
  206. )
  207. log = GitHubBackupLog(
  208. config_id=config_id,
  209. status="failed",
  210. trigger=trigger,
  211. completed_at=datetime.now(timezone.utc),
  212. error_message=abort_message,
  213. )
  214. db.add(log)
  215. config.last_backup_at = datetime.now(timezone.utc)
  216. config.last_backup_status = "failed"
  217. config.last_backup_message = abort_message
  218. if config.schedule_enabled:
  219. config.next_scheduled_run = self.calculate_next_run(config.schedule_type)
  220. await db.commit()
  221. await db.refresh(log)
  222. logger.warning(
  223. "Backup aborted for config %s: repo not private (is_private=%r, success=%r)",
  224. config_id,
  225. test_result.get("is_private"),
  226. test_result.get("success"),
  227. )
  228. return {
  229. "success": False,
  230. "message": abort_message,
  231. "log_id": log.id,
  232. }
  233. # Create log entry
  234. log = GitHubBackupLog(config_id=config_id, status="running", trigger=trigger)
  235. db.add(log)
  236. await db.commit()
  237. await db.refresh(log)
  238. log_id = log.id
  239. try:
  240. # Collect backup data
  241. self._backup_progress = "Collecting profiles..."
  242. backup_data = await self._collect_backup_data(db, config)
  243. if not backup_data:
  244. # No data to backup
  245. log.status = "skipped"
  246. log.completed_at = datetime.now(timezone.utc)
  247. log.error_message = "No data to backup"
  248. config.last_backup_at = datetime.now(timezone.utc)
  249. config.last_backup_status = "skipped"
  250. config.last_backup_message = "No data to backup"
  251. if config.schedule_enabled:
  252. config.next_scheduled_run = self.calculate_next_run(config.schedule_type)
  253. await db.commit()
  254. return {
  255. "success": True,
  256. "message": "No data to backup",
  257. "log_id": log_id,
  258. "commit_sha": None,
  259. "files_changed": 0,
  260. }
  261. provider_name = _PROVIDER_DISPLAY_NAMES.get(config.provider, config.provider)
  262. self._backup_progress = f"Pushing to {provider_name}..."
  263. push_result = _without_refused_headers(await self._push_to_provider(config, backup_data))
  264. # Update log and config
  265. log.status = push_result["status"]
  266. log.completed_at = datetime.now(timezone.utc)
  267. log.commit_sha = push_result.get("commit_sha")
  268. log.files_changed = push_result.get("files_changed", 0)
  269. log.error_message = push_result.get("error")
  270. config.last_backup_at = datetime.now(timezone.utc)
  271. config.last_backup_status = push_result["status"]
  272. config.last_backup_message = push_result.get("message", "")
  273. config.last_backup_commit_sha = push_result.get("commit_sha")
  274. if config.schedule_enabled:
  275. config.next_scheduled_run = self.calculate_next_run(config.schedule_type)
  276. await db.commit()
  277. return {
  278. "success": push_result["status"] in ("success", "skipped"),
  279. "message": push_result.get("message", "Backup completed"),
  280. "log_id": log_id,
  281. "commit_sha": push_result.get("commit_sha"),
  282. "files_changed": push_result.get("files_changed", 0),
  283. }
  284. except Exception as e:
  285. logger.exception("Backup failed")
  286. error = redact_refused_headers(str(e)) or ""
  287. log.status = "failed"
  288. log.completed_at = datetime.now(timezone.utc)
  289. log.error_message = error
  290. config.last_backup_at = datetime.now(timezone.utc)
  291. config.last_backup_status = "failed"
  292. config.last_backup_message = error
  293. if config.schedule_enabled:
  294. config.next_scheduled_run = self.calculate_next_run(config.schedule_type)
  295. await db.commit()
  296. return {
  297. "success": False,
  298. "message": error,
  299. "log_id": log_id,
  300. "commit_sha": None,
  301. "files_changed": 0,
  302. }
  303. finally:
  304. self._running_backup = False
  305. self._backup_progress = None
  306. async def _collect_backup_data(self, db: AsyncSession, config: GitHubBackupConfig) -> dict:
  307. """Collect data to backup based on config settings.
  308. Returns dict with structure:
  309. {
  310. "backup_metadata.json": {...},
  311. "kprofiles/{serial}/{nozzle}.json": {...},
  312. "cloud_profiles/bambu/{account}/{filament,printer,process}.json": {...},
  313. "cloud_profiles/orca/{account}/{filament,printer,process}.json": {...},
  314. "settings/app_settings.json": {...},
  315. }
  316. ``{account}`` is ``global`` when auth is disabled, otherwise
  317. ``user-{id}`` — one directory per connected cloud account (#2717).
  318. """
  319. files: dict[str, dict | list] = {}
  320. # Metadata file (no timestamps - git tracks file history)
  321. metadata = {
  322. "version": "1.0",
  323. "backup_type": "bambuddy_profiles",
  324. "contents": {
  325. "kprofiles": config.backup_kprofiles,
  326. "cloud_profiles": config.backup_cloud_profiles,
  327. "settings": config.backup_settings,
  328. "spools": config.backup_spools,
  329. "archives": config.backup_archives,
  330. },
  331. }
  332. files["backup_metadata.json"] = metadata
  333. # Collect K-profiles from all connected printers
  334. if config.backup_kprofiles:
  335. self._backup_progress = "Collecting K-profiles from printers..."
  336. await self._collect_kprofiles(db, files)
  337. # Collect cloud profiles. `contents.cloud_profiles` is corrected below
  338. # from what was configured to what was actually written — it claimed
  339. # `true` on every backup, including the ones that collected nothing
  340. # (#2717), which is exactly the signal a restore needs to be able to
  341. # trust.
  342. if config.backup_cloud_profiles:
  343. self._backup_progress = "Collecting cloud profiles from Bambu Cloud and Orca Cloud..."
  344. cloud_summary = await self._collect_cloud_profiles(db, files)
  345. collected = bool(cloud_summary.get("bambu") or cloud_summary.get("orca"))
  346. metadata["contents"]["cloud_profiles"] = collected
  347. if collected:
  348. # Per-cloud, per-account counts, so a restore can tell an empty
  349. # account from one that failed to collect.
  350. metadata["cloud_profiles"] = cloud_summary
  351. # Collect app settings
  352. if config.backup_settings:
  353. self._backup_progress = "Collecting app settings..."
  354. await self._collect_settings(db, files)
  355. # Collect spool inventory
  356. if config.backup_spools:
  357. self._backup_progress = "Collecting spool inventory..."
  358. await self._collect_spools(db, files)
  359. # Collect print archives
  360. if config.backup_archives:
  361. self._backup_progress = "Collecting print archives..."
  362. await self._collect_archives(db, files)
  363. return files
  364. async def _collect_kprofiles(self, db: AsyncSession, files: dict):
  365. """Collect K-profiles from all connected printers."""
  366. result = await db.execute(select(Printer).where(Printer.is_active == True)) # noqa: E712
  367. printers = result.scalars().all()
  368. nozzle_diameters = ["0.2", "0.4", "0.6", "0.8"]
  369. for printer in printers:
  370. client = printer_manager.get_client(printer.id)
  371. if not client or not client.state.connected:
  372. continue
  373. serial = printer.serial_number
  374. printer_profiles = {}
  375. for nozzle in nozzle_diameters:
  376. try:
  377. profiles = await client.get_kprofiles(nozzle_diameter=nozzle)
  378. if profiles:
  379. profile_data = {
  380. "version": "1.0",
  381. "printer_name": printer.name,
  382. "printer_serial": serial,
  383. "nozzle_diameter": nozzle,
  384. "profiles": [
  385. {
  386. "slot_id": p.slot_id,
  387. "name": p.name,
  388. "k_value": p.k_value,
  389. "filament_id": p.filament_id,
  390. "nozzle_id": p.nozzle_id,
  391. "extruder_id": p.extruder_id,
  392. "setting_id": p.setting_id,
  393. "n_coef": p.n_coef,
  394. }
  395. for p in profiles
  396. ],
  397. }
  398. files[f"kprofiles/{serial}/{nozzle}.json"] = profile_data
  399. printer_profiles[nozzle] = len(profiles)
  400. except Exception as e:
  401. logger.warning("Failed to get K-profiles for printer %s nozzle %s: %s", serial, nozzle, e)
  402. if printer_profiles:
  403. logger.info("Collected K-profiles for %s: %s", serial, printer_profiles)
  404. async def _collect_cloud_profiles(self, db: AsyncSession, files: dict) -> dict:
  405. """Collect slicer presets from every connected cloud account.
  406. Two clouds, and on an auth-enabled install any number of accounts in
  407. each: Bambu Cloud tokens live on ``User.cloud_token`` and Orca Cloud
  408. tokens on ``User.orca_cloud_token``, falling back to the global
  409. ``Settings`` table only when auth is disabled. The previous version
  410. asked for the auth-disabled store unconditionally, so it collected
  411. nothing at all on any install with auth on (#2717).
  412. Layout is one directory per cloud per account, both clouds grouped the
  413. same way so a restore reads them identically::
  414. cloud_profiles/bambu/user-3/{filament,printer,process}.json
  415. cloud_profiles/orca/user-3/{filament,printer,process}.json
  416. Accounts are keyed by Bambuddy user id (``global`` when auth is off),
  417. never by email — a backup repository can be public.
  418. Returns a per-cloud summary for ``backup_metadata.json`` so the
  419. metadata records what was actually collected rather than what was
  420. merely enabled.
  421. """
  422. summary: dict = {"bambu": {}, "orca": {}}
  423. bambu_accounts, orca_accounts = await self.cloud_accounts(db)
  424. if not bambu_accounts and not orca_accounts:
  425. # Enabled but nothing to collect. Deliberately a warning: the INFO
  426. # line this replaces read as a successful collection of nothing,
  427. # which is how #2717 went unnoticed through every backup.
  428. logger.warning(
  429. "Cloud profiles are enabled for backup, but no Bambu Cloud or Orca Cloud "
  430. "account is connected — nothing to collect."
  431. )
  432. return summary
  433. for account_key, user in bambu_accounts:
  434. try:
  435. counts = await self._collect_bambu_profiles(db, files, account_key, user)
  436. except Exception:
  437. logger.warning("Failed to collect Bambu Cloud profiles for %s", account_key, exc_info=True)
  438. continue
  439. if counts:
  440. summary["bambu"][account_key] = counts
  441. for account_key, user in orca_accounts:
  442. try:
  443. counts = await self._collect_orca_profiles(db, files, account_key, user)
  444. except Exception:
  445. logger.warning("Failed to collect Orca Cloud profiles for %s", account_key, exc_info=True)
  446. continue
  447. if counts:
  448. summary["orca"][account_key] = counts
  449. if not summary["bambu"] and not summary["orca"]:
  450. logger.warning(
  451. "Cloud profiles are enabled and %d Bambu / %d Orca account(s) are connected, "
  452. "but no presets were collected — see the per-account warnings above.",
  453. len(bambu_accounts),
  454. len(orca_accounts),
  455. )
  456. else:
  457. logger.info("Collected cloud profiles: %s", summary)
  458. return summary
  459. async def cloud_accounts(self, db: AsyncSession) -> tuple[list, list]:
  460. """Enumerate connected accounts as ``(account_key, user_or_None)`` per cloud.
  461. With auth enabled every user holds their own credentials, so a backup
  462. that only looked at the global store saw none of them. With auth
  463. disabled there is a single global row and no ``User`` at all, which is
  464. what ``user=None`` means to both clouds' credential loaders.
  465. Both stores are read regardless: a ``Settings`` row survives enabling
  466. auth later, and dropping it silently would lose that account's presets.
  467. """
  468. from backend.app.api.routes.orca_cloud import _load_credentials
  469. from backend.app.services.bambu_cloud_credentials import get_stored_token
  470. bambu: list = []
  471. orca: list = []
  472. global_token, _email, _region = await get_stored_token(db, None)
  473. if global_token:
  474. bambu.append(("global", None))
  475. global_orca = await _load_credentials(db, None)
  476. if global_orca.token:
  477. orca.append(("global", None))
  478. result = await db.execute(
  479. select(User).where(or_(User.cloud_token.isnot(None), User.orca_cloud_token.isnot(None)))
  480. )
  481. for user in result.scalars().all():
  482. if user.cloud_token:
  483. bambu.append((f"user-{user.id}", user))
  484. if user.orca_cloud_token:
  485. orca.append((f"user-{user.id}", user))
  486. return bambu, orca
  487. async def _collect_bambu_profiles(self, db: AsyncSession, files: dict, account_key: str, user) -> dict:
  488. """Collect one Bambu Cloud account's custom presets, with their payloads.
  489. The listing endpoint is keyed by preset type, each holding ``private``
  490. and ``public`` lists — there is no flat ``setting`` array, and the
  491. entries carry no ``type`` of their own, which is why the type comes
  492. from the outer key here exactly as it does in ``routes/cloud.py``.
  493. Bambu calls process presets ``print``.
  494. ``public`` is skipped: those are Bambu's own bundled catalogue, the
  495. same hundreds of entries for every user, re-downloadable at any time
  496. and not recreatable under your account anyway. Backing them up would
  497. churn the repository on every run for nothing.
  498. Each private preset then costs one ``get_setting_detail`` call, because
  499. the listing carries only metadata. Without ``base_id`` and ``setting``
  500. the backup is a list of names, not something a restore can rebuild
  501. from. Bounded by the number of *custom* presets, and the backup already
  502. makes a round-trip per printer for K-profiles.
  503. """
  504. from backend.app.api.routes.cloud import build_authenticated_cloud
  505. cloud = await build_authenticated_cloud(db, user=user)
  506. if cloud is None or not cloud.is_authenticated:
  507. logger.info("Bambu Cloud not authenticated for %s, skipping", account_key)
  508. return {}
  509. counts: dict = {}
  510. try:
  511. settings = await cloud.get_slicer_settings()
  512. if not isinstance(settings, dict) or not settings:
  513. logger.warning("Bambu Cloud returned no slicer settings for %s", account_key)
  514. return {}
  515. failed = 0
  516. for api_key, our_type in _BAMBU_PRESET_TYPES.items():
  517. type_data = settings.get(api_key)
  518. if not isinstance(type_data, dict):
  519. continue
  520. private = type_data.get("private")
  521. if not isinstance(private, list) or not private:
  522. continue
  523. profiles = []
  524. for entry in private:
  525. setting_id = entry.get("setting_id") or entry.get("id")
  526. if not setting_id:
  527. continue
  528. try:
  529. detail = await cloud.get_setting_detail(str(setting_id))
  530. except Exception as e:
  531. # One unreadable preset must not cost the rest of the
  532. # account, but it must not vanish quietly either.
  533. failed += 1
  534. logger.warning(
  535. "Failed to fetch Bambu Cloud preset %s (%s) for %s: %s",
  536. setting_id,
  537. entry.get("name", "unnamed"),
  538. account_key,
  539. e,
  540. )
  541. continue
  542. profiles.append(_bambu_preset_record(setting_id, our_type, entry, detail))
  543. if profiles:
  544. files[f"cloud_profiles/bambu/{account_key}/{our_type}.json"] = {
  545. "version": "2.0",
  546. "cloud": "bambu",
  547. "type": our_type,
  548. "profiles": profiles,
  549. }
  550. counts[our_type] = len(profiles)
  551. if failed:
  552. counts["failed"] = failed
  553. return counts
  554. finally:
  555. await cloud.close()
  556. async def _collect_orca_profiles(self, db: AsyncSession, files: dict, account_key: str, user) -> dict:
  557. """Collect one Orca Cloud account's profiles, grouped the same three ways.
  558. Cheaper than Bambu: the sync-pull listing already carries each
  559. profile's full ``content``, so there is no per-profile fetch.
  560. The type lives at ``content.type`` and is mapped through the same
  561. ``_ORCA_TYPE_TO_BAMBU`` table the Orca tab uses, so the backup groups
  562. exactly as the UI does. Where that route *drops* a profile whose type
  563. it can't map, this writes it to ``other.json`` instead — a backup that
  564. silently omits a profile because Orca added a type is the same class of
  565. bug as #2717 itself.
  566. Uses the route layer's ``_build_authenticated_service`` rather than
  567. re-implementing the refresh: the Orca refresh token is single-use and
  568. rotating, and that helper already persists the new pair atomically
  569. before returning.
  570. Passes ``clear_on_auth_failure=False``, so a rejected refresh skips the
  571. account instead of disconnecting it. A backup is an observer; it should
  572. not change anyone's sign-in state on a schedule, least of all on a
  573. rejection reason Orca does not disambiguate. The next time the user
  574. opens the Orca Profiles page that route clears the dead pairing anyway,
  575. with the user present to pair again.
  576. """
  577. from fastapi import HTTPException
  578. from backend.app.api.routes.orca_cloud import (
  579. _ORCA_TYPE_TO_BAMBU,
  580. _build_authenticated_service,
  581. )
  582. try:
  583. svc = await _build_authenticated_service(db, user, clear_on_auth_failure=False)
  584. except HTTPException as e:
  585. # Either way the stored credentials are untouched and this account
  586. # is skipped, not disconnected — but the two need different advice.
  587. # A rejected refresh will not fix itself and needs the user to pair
  588. # again; an unreachable Orca is very likely gone by the next run.
  589. if e.status_code == 401:
  590. logger.warning(
  591. "Orca Cloud rejected the stored session for %s, so its profiles are not in this "
  592. "backup. Later runs will skip it too until the account is paired again under "
  593. "Profiles > Orca Cloud Profiles — which is also where the dead credentials get "
  594. "cleared. Cause: %s",
  595. account_key,
  596. e.detail,
  597. )
  598. else:
  599. logger.warning(
  600. "Orca Cloud unreachable for %s, skipping its profiles this run: %s",
  601. account_key,
  602. e.detail,
  603. )
  604. return {}
  605. except Exception as e:
  606. logger.warning("Orca Cloud not usable for %s: %s", account_key, e, exc_info=True)
  607. return {}
  608. counts: dict = {}
  609. try:
  610. raw_profiles = await svc.list_profiles()
  611. grouped: dict[str, list] = {}
  612. unknown_types: dict[str, int] = {}
  613. for entry in raw_profiles:
  614. if not isinstance(entry, dict):
  615. continue
  616. content = entry.get("content")
  617. raw_type = content.get("type") if isinstance(content, dict) else None
  618. our_type = _ORCA_TYPE_TO_BAMBU.get(str(raw_type)) if raw_type is not None else None
  619. if our_type is None:
  620. unknown_types[str(raw_type) if raw_type is not None else "<missing>"] = (
  621. unknown_types.get(str(raw_type) if raw_type is not None else "<missing>", 0) + 1
  622. )
  623. our_type = "other"
  624. grouped.setdefault(our_type, []).append(_orca_profile_record(entry))
  625. for our_type, profiles in grouped.items():
  626. files[f"cloud_profiles/orca/{account_key}/{our_type}.json"] = {
  627. "version": "2.0",
  628. "cloud": "orca",
  629. "type": our_type,
  630. "profiles": profiles,
  631. }
  632. counts[our_type] = len(profiles)
  633. if unknown_types:
  634. logger.warning(
  635. "Orca Cloud sent %d profile(s) for %s with unmapped content.type values %s — "
  636. "backed up to other.json rather than dropped.",
  637. sum(unknown_types.values()),
  638. account_key,
  639. unknown_types,
  640. )
  641. return counts
  642. finally:
  643. await svc.close()
  644. async def _collect_settings(self, db: AsyncSession, files: dict):
  645. """Collect app settings."""
  646. result = await db.execute(select(Settings))
  647. settings = result.scalars().all()
  648. # A credential is written as the placeholder when set (blank counts as
  649. # unset, as it does for the restore), so the restore can still tell
  650. # whether a switch had one. A URL with a login in it is
  651. # left out: masked, it would be restored over a working one.
  652. # Anything else a restore would not write is left out: keys earlier
  653. # versions left behind (some hold a credential under a name no rule
  654. # recognises), runtime state and Bambuddy's own flags.
  655. settings_data = {}
  656. for s in settings:
  657. if is_secret_setting_key(s.key):
  658. settings_data[s.key] = SECRET_PLACEHOLDER if (s.value or "").strip() else s.value
  659. elif is_restorable_setting_key(s.key) and not URL_CREDENTIALS_PATTERN.search(s.value or ""):
  660. settings_data[s.key] = s.value
  661. files["settings/app_settings.json"] = {
  662. "version": "1.0",
  663. "settings": settings_data,
  664. }
  665. async def _collect_spools(self, db: AsyncSession, files: dict):
  666. """Collect spool inventory data."""
  667. result = await db.execute(select(Spool))
  668. spools = result.scalars().all()
  669. if not spools:
  670. return
  671. spool_list = []
  672. for s in spools:
  673. spool_data = {
  674. "id": s.id,
  675. "material": s.material,
  676. "subtype": s.subtype,
  677. "color_name": s.color_name,
  678. "rgba": s.rgba,
  679. "brand": s.brand,
  680. "label_weight": s.label_weight,
  681. "core_weight": s.core_weight,
  682. "weight_used": s.weight_used,
  683. # The "Reset Total Consumed" point (WU-7).
  684. "weight_used_baseline": s.weight_used_baseline,
  685. "weight_locked": s.weight_locked,
  686. "slicer_filament": s.slicer_filament,
  687. "slicer_filament_name": s.slicer_filament_name,
  688. "nozzle_temp_min": s.nozzle_temp_min,
  689. "nozzle_temp_max": s.nozzle_temp_max,
  690. "note": s.note,
  691. "cost_per_kg": s.cost_per_kg,
  692. # The user's own bookkeeping on the spool: purchasing number
  693. # (#2870), category and low-stock override (#729), free-text
  694. # storage. All four were missing from this whitelist, so a
  695. # restore silently dropped them. `location_id` stays out —
  696. # the locations table itself is not in the backup, so the ID
  697. # would point at whatever happens to own it on the target.
  698. "material_number": s.material_number,
  699. "category": s.category,
  700. "low_stock_threshold_pct": s.low_stock_threshold_pct,
  701. "storage_location": s.storage_location,
  702. # Last drying (#2863).
  703. "last_dried_at": str(s.last_dried_at) if s.last_dried_at else None,
  704. "last_dried_temp": s.last_dried_temp,
  705. "last_dried_hours": s.last_dried_hours,
  706. "tag_uid": s.tag_uid,
  707. "tray_uuid": s.tray_uuid,
  708. "data_origin": s.data_origin,
  709. "tag_type": s.tag_type,
  710. "archived_at": str(s.archived_at) if s.archived_at else None,
  711. "created_at": str(s.created_at) if s.created_at else None,
  712. }
  713. spool_list.append(spool_data)
  714. files["spools/inventory.json"] = {
  715. "version": "1.0",
  716. "spools": spool_list,
  717. }
  718. # Collect usage history
  719. usage_result = await db.execute(select(SpoolUsageHistory))
  720. usages = usage_result.scalars().all()
  721. if usages:
  722. usage_list = []
  723. for u in usages:
  724. usage_list.append(
  725. {
  726. "id": u.id,
  727. "spool_id": u.spool_id,
  728. "printer_id": u.printer_id,
  729. "print_name": u.print_name,
  730. "archive_id": u.archive_id,
  731. "weight_used": u.weight_used,
  732. "percent_used": u.percent_used,
  733. "status": u.status,
  734. "cost": u.cost,
  735. "created_at": str(u.created_at) if u.created_at else None,
  736. }
  737. )
  738. files["spools/usage_history.json"] = {
  739. "version": "1.0",
  740. "usage_history": usage_list,
  741. }
  742. logger.info("Collected %d spools and %d usage records", len(spool_list), len(usages))
  743. async def _collect_archives(self, db: AsyncSession, files: dict):
  744. """Collect print archive metadata (no binary files)."""
  745. result = await db.execute(select(PrintArchive))
  746. archives = result.scalars().all()
  747. if not archives:
  748. return
  749. # The natural key for an owner. created_by_id alone is only meaningful on
  750. # the instance that wrote it: restoring onto a rebuilt instance — this
  751. # feature's main use case — renumbers the users table, so a live id can
  752. # land on a different person. username is unique on users, so the restore
  753. # can resolve on it and treat a rename as unknown rather than guess.
  754. # One query for the map; archives outnumber users by orders of magnitude.
  755. user_names = dict((await db.execute(select(User.id, User.username))).all())
  756. archive_list = []
  757. for a in archives:
  758. archive_data = {
  759. "id": a.id,
  760. "printer_id": a.printer_id,
  761. "project_id": a.project_id,
  762. "filename": a.filename,
  763. "file_size": a.file_size,
  764. "content_hash": a.content_hash,
  765. "print_name": a.print_name,
  766. "print_time_seconds": a.print_time_seconds,
  767. "filament_used_grams": a.filament_used_grams,
  768. "filament_type": a.filament_type,
  769. "filament_color": a.filament_color,
  770. "layer_height": a.layer_height,
  771. "total_layers": a.total_layers,
  772. "nozzle_diameter": a.nozzle_diameter,
  773. "bed_temperature": a.bed_temperature,
  774. "nozzle_temperature": a.nozzle_temperature,
  775. "sliced_for_model": a.sliced_for_model,
  776. "status": a.status,
  777. "started_at": str(a.started_at) if a.started_at else None,
  778. "completed_at": str(a.completed_at) if a.completed_at else None,
  779. "makerworld_url": a.makerworld_url,
  780. "designer": a.designer,
  781. "external_url": a.external_url,
  782. "is_favorite": a.is_favorite,
  783. "tags": a.tags,
  784. "notes": a.notes,
  785. "cost": a.cost,
  786. "failure_reason": a.failure_reason,
  787. "quantity": a.quantity,
  788. "energy_kwh": a.energy_kwh,
  789. "energy_cost": a.energy_cost,
  790. "wear_cost": a.wear_cost,
  791. "created_at": str(a.created_at) if a.created_at else None,
  792. # Soft-deleted archives are collected too — their row is kept on
  793. # purpose so the stats endpoint keeps counting their filament and
  794. # energy (see archive_service.soft_delete_archive). Recording
  795. # deleted_at is what lets a restore put them back the way they
  796. # were instead of resurrecting them as visible archives.
  797. "deleted_at": str(a.deleted_at) if a.deleted_at else None,
  798. # Who owns the archive, for the same reason deleted_at is here:
  799. # it is not decoration, it is what the access check runs on.
  800. # _ensure_archive_visible (api/routes/archives.py) fails closed on
  801. # a NULL created_by_id and the list paths filter on it, so a
  802. # restored row without it is invisible to everyone but an admin —
  803. # while the restore reports it restored.
  804. "created_by_id": a.created_by_id,
  805. # Preferred over the id on restore; the id stays as the fallback
  806. # for an owner whose row has since gone. Null when the archive
  807. # has no owner, or when it points at a user row that no longer
  808. # exists locally — the same "absent is not null" rule the restore
  809. # applies, so a backup can't claim an owner it cannot name.
  810. "created_by_username": user_names.get(a.created_by_id),
  811. }
  812. archive_list.append(archive_data)
  813. files["archives/print_history.json"] = {
  814. "version": "1.0",
  815. "archives": archive_list,
  816. }
  817. logger.info("Collected %d print archives", len(archive_list))
  818. async def _push_to_provider(self, config: GitHubBackupConfig, files: dict) -> dict:
  819. """Push files to the configured Git provider."""
  820. backend = get_provider_backend(config.provider)
  821. client = await self._get_client()
  822. return await backend.push_files(
  823. repo_url=config.repository_url,
  824. token=config.access_token,
  825. branch=config.branch,
  826. files=files,
  827. client=client,
  828. )
  829. @property
  830. def is_running(self) -> bool:
  831. """Check if a backup is currently running."""
  832. return self._running_backup
  833. @property
  834. def progress(self) -> str | None:
  835. """Get current backup progress message."""
  836. return self._backup_progress
  837. async def get_logs(self, config_id: int, limit: int = 50, offset: int = 0) -> list[GitHubBackupLog]:
  838. """Get backup logs for a configuration."""
  839. async with async_session() as db:
  840. result = await db.execute(
  841. select(GitHubBackupLog)
  842. .where(GitHubBackupLog.config_id == config_id)
  843. .order_by(desc(GitHubBackupLog.started_at))
  844. .offset(offset)
  845. .limit(limit)
  846. )
  847. return list(result.scalars().all())
  848. # Singleton instance
  849. github_backup_service = GitHubBackupService()