github_backup.py 38 KB

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