github_backup.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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 base64
  6. import hashlib
  7. import json
  8. import logging
  9. import re
  10. from datetime import UTC, datetime, timedelta
  11. import httpx
  12. from sqlalchemy import desc, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.database import async_session
  15. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  16. from backend.app.models.printer import Printer
  17. from backend.app.models.settings import Settings
  18. from backend.app.services.bambu_cloud import get_cloud_service
  19. from backend.app.services.printer_manager import printer_manager
  20. logger = logging.getLogger(__name__)
  21. # Schedule intervals in seconds
  22. SCHEDULE_INTERVALS = {
  23. "hourly": 3600,
  24. "daily": 86400,
  25. "weekly": 604800,
  26. }
  27. class GitHubBackupService:
  28. """Service for backing up profiles to GitHub."""
  29. def __init__(self):
  30. self._scheduler_task: asyncio.Task | None = None
  31. self._check_interval = 60 # Check every minute for scheduled runs
  32. self._running_backup: bool = False
  33. self._backup_progress: str | None = None
  34. self._http_client: httpx.AsyncClient | None = None
  35. async def _get_client(self) -> httpx.AsyncClient:
  36. """Get or create HTTP client."""
  37. if self._http_client is None or self._http_client.is_closed:
  38. self._http_client = httpx.AsyncClient(timeout=60.0)
  39. return self._http_client
  40. async def start_scheduler(self):
  41. """Start the background scheduler loop."""
  42. if self._scheduler_task is not None:
  43. return
  44. logger.info("Starting GitHub backup scheduler")
  45. self._scheduler_task = asyncio.create_task(self._scheduler_loop())
  46. def stop_scheduler(self):
  47. """Stop the scheduler."""
  48. if self._scheduler_task:
  49. self._scheduler_task.cancel()
  50. self._scheduler_task = None
  51. logger.info("Stopped GitHub backup scheduler")
  52. async def _scheduler_loop(self):
  53. """Main scheduler loop - checks for due backups."""
  54. while True:
  55. try:
  56. await asyncio.sleep(self._check_interval)
  57. await self._check_scheduled_backups()
  58. except asyncio.CancelledError:
  59. break
  60. except Exception as e:
  61. logger.error(f"Error in GitHub backup scheduler: {e}")
  62. await asyncio.sleep(60)
  63. async def _check_scheduled_backups(self):
  64. """Check if any scheduled backups are due."""
  65. async with async_session() as db:
  66. result = await db.execute(
  67. select(GitHubBackupConfig).where(
  68. GitHubBackupConfig.enabled == True, # noqa: E712
  69. GitHubBackupConfig.schedule_enabled == True, # noqa: E712
  70. )
  71. )
  72. configs = result.scalars().all()
  73. now = datetime.now(UTC)
  74. for config in configs:
  75. # Handle both naive (from DB) and aware datetimes
  76. next_run = config.next_scheduled_run
  77. if next_run and next_run.tzinfo is None:
  78. next_run = next_run.replace(tzinfo=UTC)
  79. if next_run and next_run <= now:
  80. logger.info(f"Running scheduled backup for config {config.id}")
  81. await self.run_backup(config.id, trigger="scheduled")
  82. def _calculate_next_run(self, schedule_type: str, from_time: datetime | None = None) -> datetime:
  83. """Calculate the next scheduled run time."""
  84. now = from_time or datetime.now(UTC)
  85. interval = SCHEDULE_INTERVALS.get(schedule_type, SCHEDULE_INTERVALS["daily"])
  86. return now + timedelta(seconds=interval)
  87. async def test_connection(self, repo_url: str, token: str) -> dict:
  88. """Test GitHub connection and permissions.
  89. Args:
  90. repo_url: GitHub repository URL
  91. token: Personal Access Token
  92. Returns:
  93. dict with success, message, repo_name, permissions
  94. """
  95. try:
  96. owner, repo = self._parse_repo_url(repo_url)
  97. client = await self._get_client()
  98. # Test API access
  99. response = await client.get(
  100. f"https://api.github.com/repos/{owner}/{repo}",
  101. headers={
  102. "Authorization": f"token {token}",
  103. "Accept": "application/vnd.github.v3+json",
  104. "User-Agent": "Bambuddy-Backup",
  105. },
  106. )
  107. if response.status_code == 401:
  108. return {"success": False, "message": "Invalid access token", "repo_name": None, "permissions": None}
  109. if response.status_code == 404:
  110. return {
  111. "success": False,
  112. "message": "Repository not found. Check URL and token permissions.",
  113. "repo_name": None,
  114. "permissions": None,
  115. }
  116. if response.status_code != 200:
  117. return {
  118. "success": False,
  119. "message": f"GitHub API error: {response.status_code}",
  120. "repo_name": None,
  121. "permissions": None,
  122. }
  123. data = response.json()
  124. permissions = data.get("permissions", {})
  125. # Check for push permission
  126. if not permissions.get("push", False):
  127. return {
  128. "success": False,
  129. "message": "Token does not have push permission to this repository",
  130. "repo_name": data.get("full_name"),
  131. "permissions": permissions,
  132. }
  133. return {
  134. "success": True,
  135. "message": "Connection successful",
  136. "repo_name": data.get("full_name"),
  137. "permissions": permissions,
  138. }
  139. except Exception as e:
  140. logger.error(f"GitHub connection test failed: {e}")
  141. return {"success": False, "message": str(e), "repo_name": None, "permissions": None}
  142. def _parse_repo_url(self, url: str) -> tuple[str, str]:
  143. """Parse owner and repo from GitHub URL."""
  144. # Handle HTTPS URLs
  145. match = re.match(r"https://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$", url)
  146. if match:
  147. return match.group(1), match.group(2)
  148. # Handle SSH URLs
  149. match = re.match(r"git@github\.com:([^/]+)/([^/]+?)(?:\.git)?$", url)
  150. if match:
  151. return match.group(1), match.group(2)
  152. raise ValueError(f"Invalid GitHub URL: {url}")
  153. async def run_backup(self, config_id: int, trigger: str = "manual") -> dict:
  154. """Run a backup operation.
  155. Args:
  156. config_id: ID of the backup configuration
  157. trigger: "manual" or "scheduled"
  158. Returns:
  159. dict with success, message, log_id, commit_sha, files_changed
  160. """
  161. if self._running_backup:
  162. return {"success": False, "message": "A backup is already running", "log_id": None}
  163. self._running_backup = True
  164. log_id = None
  165. try:
  166. async with async_session() as db:
  167. # Get config
  168. result = await db.execute(select(GitHubBackupConfig).where(GitHubBackupConfig.id == config_id))
  169. config = result.scalar_one_or_none()
  170. if not config:
  171. return {"success": False, "message": "Configuration not found", "log_id": None}
  172. if not config.enabled:
  173. return {"success": False, "message": "Backup is disabled", "log_id": None}
  174. # Create log entry
  175. log = GitHubBackupLog(config_id=config_id, status="running", trigger=trigger)
  176. db.add(log)
  177. await db.commit()
  178. await db.refresh(log)
  179. log_id = log.id
  180. try:
  181. # Collect backup data
  182. self._backup_progress = "Collecting profiles..."
  183. backup_data = await self._collect_backup_data(db, config)
  184. if not backup_data:
  185. # No data to backup
  186. log.status = "skipped"
  187. log.completed_at = datetime.now(UTC)
  188. log.error_message = "No data to backup"
  189. config.last_backup_at = datetime.now(UTC)
  190. config.last_backup_status = "skipped"
  191. config.last_backup_message = "No data to backup"
  192. if config.schedule_enabled:
  193. config.next_scheduled_run = self._calculate_next_run(config.schedule_type)
  194. await db.commit()
  195. return {
  196. "success": True,
  197. "message": "No data to backup",
  198. "log_id": log_id,
  199. "commit_sha": None,
  200. "files_changed": 0,
  201. }
  202. # Push to GitHub
  203. self._backup_progress = "Pushing to GitHub..."
  204. push_result = await self._push_to_github(config, backup_data)
  205. # Update log and config
  206. log.status = push_result["status"]
  207. log.completed_at = datetime.now(UTC)
  208. log.commit_sha = push_result.get("commit_sha")
  209. log.files_changed = push_result.get("files_changed", 0)
  210. log.error_message = push_result.get("error")
  211. config.last_backup_at = datetime.now(UTC)
  212. config.last_backup_status = push_result["status"]
  213. config.last_backup_message = push_result.get("message", "")
  214. config.last_backup_commit_sha = push_result.get("commit_sha")
  215. if config.schedule_enabled:
  216. config.next_scheduled_run = self._calculate_next_run(config.schedule_type)
  217. await db.commit()
  218. return {
  219. "success": push_result["status"] in ("success", "skipped"),
  220. "message": push_result.get("message", "Backup completed"),
  221. "log_id": log_id,
  222. "commit_sha": push_result.get("commit_sha"),
  223. "files_changed": push_result.get("files_changed", 0),
  224. }
  225. except Exception as e:
  226. logger.error(f"Backup failed: {e}")
  227. log.status = "failed"
  228. log.completed_at = datetime.now(UTC)
  229. log.error_message = str(e)
  230. config.last_backup_at = datetime.now(UTC)
  231. config.last_backup_status = "failed"
  232. config.last_backup_message = str(e)
  233. if config.schedule_enabled:
  234. config.next_scheduled_run = self._calculate_next_run(config.schedule_type)
  235. await db.commit()
  236. return {
  237. "success": False,
  238. "message": str(e),
  239. "log_id": log_id,
  240. "commit_sha": None,
  241. "files_changed": 0,
  242. }
  243. finally:
  244. self._running_backup = False
  245. self._backup_progress = None
  246. async def _collect_backup_data(self, db: AsyncSession, config: GitHubBackupConfig) -> dict:
  247. """Collect data to backup based on config settings.
  248. Returns dict with structure:
  249. {
  250. "backup_metadata.json": {...},
  251. "kprofiles/{serial}/{nozzle}.json": {...},
  252. "cloud_profiles/filament.json": [...],
  253. "cloud_profiles/printer.json": [...],
  254. "cloud_profiles/process.json": [...],
  255. "settings/app_settings.json": {...},
  256. }
  257. """
  258. files: dict[str, dict | list] = {}
  259. # Metadata file (no timestamps - git tracks file history)
  260. metadata = {
  261. "version": "1.0",
  262. "backup_type": "bambuddy_profiles",
  263. "contents": {
  264. "kprofiles": config.backup_kprofiles,
  265. "cloud_profiles": config.backup_cloud_profiles,
  266. "settings": config.backup_settings,
  267. },
  268. }
  269. files["backup_metadata.json"] = metadata
  270. # Collect K-profiles from all connected printers
  271. if config.backup_kprofiles:
  272. self._backup_progress = "Collecting K-profiles from printers..."
  273. await self._collect_kprofiles(db, files)
  274. # Collect cloud profiles
  275. if config.backup_cloud_profiles:
  276. self._backup_progress = "Collecting cloud profiles from Bambu Cloud..."
  277. await self._collect_cloud_profiles(db, files)
  278. # Collect app settings
  279. if config.backup_settings:
  280. self._backup_progress = "Collecting app settings..."
  281. await self._collect_settings(db, files)
  282. return files
  283. async def _collect_kprofiles(self, db: AsyncSession, files: dict):
  284. """Collect K-profiles from all connected printers."""
  285. result = await db.execute(select(Printer).where(Printer.is_active == True)) # noqa: E712
  286. printers = result.scalars().all()
  287. nozzle_diameters = ["0.2", "0.4", "0.6", "0.8"]
  288. for printer in printers:
  289. client = printer_manager.get_client(printer.id)
  290. if not client or not client.state.connected:
  291. continue
  292. serial = printer.serial_number
  293. printer_profiles = {}
  294. for nozzle in nozzle_diameters:
  295. try:
  296. profiles = await client.get_kprofiles(nozzle_diameter=nozzle)
  297. if profiles:
  298. profile_data = {
  299. "version": "1.0",
  300. "printer_name": printer.name,
  301. "printer_serial": serial,
  302. "nozzle_diameter": nozzle,
  303. "profiles": [
  304. {
  305. "slot_id": p.slot_id,
  306. "name": p.name,
  307. "k_value": p.k_value,
  308. "filament_id": p.filament_id,
  309. "nozzle_id": p.nozzle_id,
  310. "extruder_id": p.extruder_id,
  311. "setting_id": p.setting_id,
  312. "n_coef": p.n_coef,
  313. }
  314. for p in profiles
  315. ],
  316. }
  317. files[f"kprofiles/{serial}/{nozzle}.json"] = profile_data
  318. printer_profiles[nozzle] = len(profiles)
  319. except Exception as e:
  320. logger.warning(f"Failed to get K-profiles for printer {serial} nozzle {nozzle}: {e}")
  321. if printer_profiles:
  322. logger.info(f"Collected K-profiles for {serial}: {printer_profiles}")
  323. async def _collect_cloud_profiles(self, db: AsyncSession, files: dict):
  324. """Collect Bambu Cloud profiles if authenticated."""
  325. # Check if cloud is authenticated
  326. cloud = get_cloud_service()
  327. # Try to restore token from DB
  328. result = await db.execute(select(Settings).where(Settings.key == "bambu_cloud_token"))
  329. setting = result.scalar_one_or_none()
  330. if setting and setting.value:
  331. cloud.set_token(setting.value)
  332. if not cloud.is_authenticated:
  333. logger.info("Cloud not authenticated, skipping cloud profiles")
  334. return
  335. try:
  336. settings = await cloud.get_slicer_settings()
  337. if not settings:
  338. return
  339. # Separate by type
  340. filament_settings = []
  341. printer_settings = []
  342. process_settings = []
  343. for setting in settings.get("setting", []) if isinstance(settings.get("setting"), list) else []:
  344. setting_type = setting.get("type", "")
  345. if setting_type == "filament":
  346. filament_settings.append(setting)
  347. elif setting_type == "printer":
  348. printer_settings.append(setting)
  349. elif setting_type == "process":
  350. process_settings.append(setting)
  351. if filament_settings:
  352. files["cloud_profiles/filament.json"] = {
  353. "version": "1.0",
  354. "profiles": filament_settings,
  355. }
  356. if printer_settings:
  357. files["cloud_profiles/printer.json"] = {
  358. "version": "1.0",
  359. "profiles": printer_settings,
  360. }
  361. if process_settings:
  362. files["cloud_profiles/process.json"] = {
  363. "version": "1.0",
  364. "profiles": process_settings,
  365. }
  366. logger.info(
  367. f"Collected cloud profiles: {len(filament_settings)} filament, "
  368. f"{len(printer_settings)} printer, {len(process_settings)} process"
  369. )
  370. except Exception as e:
  371. logger.warning(f"Failed to collect cloud profiles: {e}")
  372. async def _collect_settings(self, db: AsyncSession, files: dict):
  373. """Collect app settings."""
  374. result = await db.execute(select(Settings))
  375. settings = result.scalars().all()
  376. # Filter out sensitive settings
  377. sensitive_keys = {"bambu_cloud_token", "auth_secret_key"}
  378. settings_data = {s.key: s.value for s in settings if s.key not in sensitive_keys}
  379. files["settings/app_settings.json"] = {
  380. "version": "1.0",
  381. "settings": settings_data,
  382. }
  383. async def _push_to_github(self, config: GitHubBackupConfig, files: dict) -> dict:
  384. """Push files to GitHub using the GitHub API.
  385. Uses the Git Data API to create blobs, tree, and commit.
  386. Returns:
  387. dict with status, message, commit_sha, files_changed
  388. """
  389. try:
  390. owner, repo = self._parse_repo_url(config.repository_url)
  391. branch = config.branch
  392. client = await self._get_client()
  393. headers = {
  394. "Authorization": f"token {config.access_token}",
  395. "Accept": "application/vnd.github.v3+json",
  396. "User-Agent": "Bambuddy-Backup",
  397. }
  398. # Get current branch reference
  399. ref_response = await client.get(
  400. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}", headers=headers
  401. )
  402. if ref_response.status_code == 404:
  403. # Branch doesn't exist, need to create it from default branch
  404. return await self._create_branch_and_push(client, headers, owner, repo, branch, files)
  405. if ref_response.status_code != 200:
  406. return {
  407. "status": "failed",
  408. "message": f"Failed to get branch ref: {ref_response.status_code}",
  409. "error": ref_response.text,
  410. }
  411. ref_data = ref_response.json()
  412. current_commit_sha = ref_data["object"]["sha"]
  413. # Get the current tree
  414. commit_response = await client.get(
  415. f"https://api.github.com/repos/{owner}/{repo}/git/commits/{current_commit_sha}", headers=headers
  416. )
  417. if commit_response.status_code != 200:
  418. return {"status": "failed", "message": "Failed to get current commit"}
  419. current_tree_sha = commit_response.json()["tree"]["sha"]
  420. # Get existing files to check for changes
  421. tree_response = await client.get(
  422. f"https://api.github.com/repos/{owner}/{repo}/git/trees/{current_tree_sha}?recursive=1", headers=headers
  423. )
  424. existing_files = {}
  425. if tree_response.status_code == 200:
  426. for item in tree_response.json().get("tree", []):
  427. if item["type"] == "blob":
  428. existing_files[item["path"]] = item["sha"]
  429. # Create blobs for changed files
  430. tree_items = []
  431. files_changed = 0
  432. for path, content in files.items():
  433. content_str = json.dumps(content, indent=2, default=str)
  434. content_bytes = content_str.encode("utf-8")
  435. content_sha = hashlib.sha1(f"blob {len(content_bytes)}\0".encode() + content_bytes).hexdigest()
  436. # Skip if file hasn't changed
  437. if path in existing_files and existing_files[path] == content_sha:
  438. continue
  439. # Create blob
  440. blob_response = await client.post(
  441. f"https://api.github.com/repos/{owner}/{repo}/git/blobs",
  442. headers=headers,
  443. json={"content": base64.b64encode(content_bytes).decode(), "encoding": "base64"},
  444. )
  445. if blob_response.status_code != 201:
  446. logger.error(f"Failed to create blob for {path}: {blob_response.text}")
  447. continue
  448. blob_sha = blob_response.json()["sha"]
  449. tree_items.append({"path": path, "mode": "100644", "type": "blob", "sha": blob_sha})
  450. files_changed += 1
  451. if not tree_items:
  452. return {"status": "skipped", "message": "No changes to commit", "commit_sha": None, "files_changed": 0}
  453. # Create new tree
  454. tree_response = await client.post(
  455. f"https://api.github.com/repos/{owner}/{repo}/git/trees",
  456. headers=headers,
  457. json={"base_tree": current_tree_sha, "tree": tree_items},
  458. )
  459. if tree_response.status_code != 201:
  460. return {"status": "failed", "message": f"Failed to create tree: {tree_response.text}"}
  461. new_tree_sha = tree_response.json()["sha"]
  462. # Create commit
  463. commit_message = f"Bambuddy backup - {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  464. commit_response = await client.post(
  465. f"https://api.github.com/repos/{owner}/{repo}/git/commits",
  466. headers=headers,
  467. json={"message": commit_message, "tree": new_tree_sha, "parents": [current_commit_sha]},
  468. )
  469. if commit_response.status_code != 201:
  470. return {"status": "failed", "message": f"Failed to create commit: {commit_response.text}"}
  471. new_commit_sha = commit_response.json()["sha"]
  472. # Update branch reference
  473. ref_update = await client.patch(
  474. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}",
  475. headers=headers,
  476. json={"sha": new_commit_sha},
  477. )
  478. if ref_update.status_code != 200:
  479. return {"status": "failed", "message": f"Failed to update branch: {ref_update.text}"}
  480. return {
  481. "status": "success",
  482. "message": f"Backup successful - {files_changed} files updated",
  483. "commit_sha": new_commit_sha,
  484. "files_changed": files_changed,
  485. }
  486. except Exception as e:
  487. logger.error(f"Push to GitHub failed: {e}")
  488. return {"status": "failed", "message": str(e), "error": str(e)}
  489. async def _create_branch_and_push(
  490. self, client: httpx.AsyncClient, headers: dict, owner: str, repo: str, branch: str, files: dict
  491. ) -> dict:
  492. """Create a new branch and push files when branch doesn't exist."""
  493. try:
  494. # Get default branch
  495. repo_response = await client.get(f"https://api.github.com/repos/{owner}/{repo}", headers=headers)
  496. if repo_response.status_code != 200:
  497. return {"status": "failed", "message": "Failed to get repo info"}
  498. default_branch = repo_response.json().get("default_branch", "main")
  499. # Get default branch ref
  500. ref_response = await client.get(
  501. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{default_branch}", headers=headers
  502. )
  503. if ref_response.status_code != 200:
  504. # Empty repo - create initial commit
  505. return await self._create_initial_commit(client, headers, owner, repo, branch, files)
  506. base_sha = ref_response.json()["object"]["sha"]
  507. # Create new branch
  508. create_ref = await client.post(
  509. f"https://api.github.com/repos/{owner}/{repo}/git/refs",
  510. headers=headers,
  511. json={"ref": f"refs/heads/{branch}", "sha": base_sha},
  512. )
  513. if create_ref.status_code != 201:
  514. return {"status": "failed", "message": f"Failed to create branch: {create_ref.text}"}
  515. # Now push to the new branch (recursive call will find the branch)
  516. return await self._push_to_github(
  517. type(
  518. "Config",
  519. (),
  520. {
  521. "repository_url": f"https://github.com/{owner}/{repo}",
  522. "access_token": headers["Authorization"].replace("token ", ""),
  523. "branch": branch,
  524. },
  525. )(),
  526. files,
  527. )
  528. except Exception as e:
  529. return {"status": "failed", "message": str(e)}
  530. async def _create_initial_commit(
  531. self, client: httpx.AsyncClient, headers: dict, owner: str, repo: str, branch: str, files: dict
  532. ) -> dict:
  533. """Create initial commit in an empty repository."""
  534. try:
  535. # Create blobs
  536. tree_items = []
  537. for path, content in files.items():
  538. content_str = json.dumps(content, indent=2, default=str)
  539. blob_response = await client.post(
  540. f"https://api.github.com/repos/{owner}/{repo}/git/blobs",
  541. headers=headers,
  542. json={"content": base64.b64encode(content_str.encode()).decode(), "encoding": "base64"},
  543. )
  544. if blob_response.status_code == 201:
  545. tree_items.append(
  546. {"path": path, "mode": "100644", "type": "blob", "sha": blob_response.json()["sha"]}
  547. )
  548. # Create tree
  549. tree_response = await client.post(
  550. f"https://api.github.com/repos/{owner}/{repo}/git/trees",
  551. headers=headers,
  552. json={"tree": tree_items},
  553. )
  554. if tree_response.status_code != 201:
  555. return {"status": "failed", "message": "Failed to create tree"}
  556. tree_sha = tree_response.json()["sha"]
  557. # Create commit (no parents for initial)
  558. commit_response = await client.post(
  559. f"https://api.github.com/repos/{owner}/{repo}/git/commits",
  560. headers=headers,
  561. json={
  562. "message": f"Initial Bambuddy backup - {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}",
  563. "tree": tree_sha,
  564. },
  565. )
  566. if commit_response.status_code != 201:
  567. return {"status": "failed", "message": "Failed to create commit"}
  568. commit_sha = commit_response.json()["sha"]
  569. # Create branch ref
  570. ref_response = await client.post(
  571. f"https://api.github.com/repos/{owner}/{repo}/git/refs",
  572. headers=headers,
  573. json={"ref": f"refs/heads/{branch}", "sha": commit_sha},
  574. )
  575. if ref_response.status_code != 201:
  576. return {"status": "failed", "message": "Failed to create branch ref"}
  577. return {
  578. "status": "success",
  579. "message": f"Initial backup created - {len(files)} files",
  580. "commit_sha": commit_sha,
  581. "files_changed": len(files),
  582. }
  583. except Exception as e:
  584. return {"status": "failed", "message": str(e)}
  585. @property
  586. def is_running(self) -> bool:
  587. """Check if a backup is currently running."""
  588. return self._running_backup
  589. @property
  590. def progress(self) -> str | None:
  591. """Get current backup progress message."""
  592. return self._backup_progress
  593. async def get_logs(self, config_id: int, limit: int = 50, offset: int = 0) -> list[GitHubBackupLog]:
  594. """Get backup logs for a configuration."""
  595. async with async_session() as db:
  596. result = await db.execute(
  597. select(GitHubBackupLog)
  598. .where(GitHubBackupLog.config_id == config_id)
  599. .order_by(desc(GitHubBackupLog.started_at))
  600. .offset(offset)
  601. .limit(limit)
  602. )
  603. return list(result.scalars().all())
  604. # Singleton instance
  605. github_backup_service = GitHubBackupService()