github_backup.py 43 KB

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