github_backup.py 43 KB

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