github_backup.py 29 KB

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