github_backup.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. now = datetime.now(UTC)
  260. # Metadata file
  261. metadata = {
  262. "version": "1.0",
  263. "backup_type": "bambuddy_profiles",
  264. "created_at": now.isoformat(),
  265. "contents": {
  266. "kprofiles": config.backup_kprofiles,
  267. "cloud_profiles": config.backup_cloud_profiles,
  268. "settings": config.backup_settings,
  269. },
  270. }
  271. files["backup_metadata.json"] = metadata
  272. # Collect K-profiles from all connected printers
  273. if config.backup_kprofiles:
  274. self._backup_progress = "Collecting K-profiles from printers..."
  275. await self._collect_kprofiles(db, files)
  276. # Collect cloud profiles
  277. if config.backup_cloud_profiles:
  278. self._backup_progress = "Collecting cloud profiles from Bambu Cloud..."
  279. await self._collect_cloud_profiles(db, files)
  280. # Collect app settings
  281. if config.backup_settings:
  282. self._backup_progress = "Collecting app settings..."
  283. await self._collect_settings(db, files)
  284. return files
  285. async def _collect_kprofiles(self, db: AsyncSession, files: dict):
  286. """Collect K-profiles from all connected printers."""
  287. result = await db.execute(select(Printer).where(Printer.is_active == True)) # noqa: E712
  288. printers = result.scalars().all()
  289. nozzle_diameters = ["0.2", "0.4", "0.6", "0.8"]
  290. for printer in printers:
  291. client = printer_manager.get_client(printer.id)
  292. if not client or not client.state.connected:
  293. continue
  294. serial = printer.serial_number
  295. printer_profiles = {}
  296. for nozzle in nozzle_diameters:
  297. try:
  298. profiles = await client.get_kprofiles(nozzle_diameter=nozzle)
  299. if profiles:
  300. profile_data = {
  301. "version": "1.0",
  302. "printer_name": printer.name,
  303. "printer_serial": serial,
  304. "nozzle_diameter": nozzle,
  305. "exported_at": datetime.now(UTC).isoformat(),
  306. "profiles": [
  307. {
  308. "slot_id": p.slot_id,
  309. "name": p.name,
  310. "k_value": p.k_value,
  311. "filament_id": p.filament_id,
  312. "nozzle_id": p.nozzle_id,
  313. "extruder_id": p.extruder_id,
  314. "setting_id": p.setting_id,
  315. "n_coef": p.n_coef,
  316. }
  317. for p in profiles
  318. ],
  319. }
  320. files[f"kprofiles/{serial}/{nozzle}.json"] = profile_data
  321. printer_profiles[nozzle] = len(profiles)
  322. except Exception as e:
  323. logger.warning(f"Failed to get K-profiles for printer {serial} nozzle {nozzle}: {e}")
  324. if printer_profiles:
  325. logger.info(f"Collected K-profiles for {serial}: {printer_profiles}")
  326. async def _collect_cloud_profiles(self, db: AsyncSession, files: dict):
  327. """Collect Bambu Cloud profiles if authenticated."""
  328. # Check if cloud is authenticated
  329. cloud = get_cloud_service()
  330. # Try to restore token from DB
  331. result = await db.execute(select(Settings).where(Settings.key == "bambu_cloud_token"))
  332. setting = result.scalar_one_or_none()
  333. if setting and setting.value:
  334. cloud.set_token(setting.value)
  335. if not cloud.is_authenticated:
  336. logger.info("Cloud not authenticated, skipping cloud profiles")
  337. return
  338. try:
  339. settings = await cloud.get_slicer_settings()
  340. if not settings:
  341. return
  342. # Separate by type
  343. filament_settings = []
  344. printer_settings = []
  345. process_settings = []
  346. for setting in settings.get("setting", []) if isinstance(settings.get("setting"), list) else []:
  347. setting_type = setting.get("type", "")
  348. if setting_type == "filament":
  349. filament_settings.append(setting)
  350. elif setting_type == "printer":
  351. printer_settings.append(setting)
  352. elif setting_type == "process":
  353. process_settings.append(setting)
  354. if filament_settings:
  355. files["cloud_profiles/filament.json"] = {
  356. "version": "1.0",
  357. "exported_at": datetime.now(UTC).isoformat(),
  358. "profiles": filament_settings,
  359. }
  360. if printer_settings:
  361. files["cloud_profiles/printer.json"] = {
  362. "version": "1.0",
  363. "exported_at": datetime.now(UTC).isoformat(),
  364. "profiles": printer_settings,
  365. }
  366. if process_settings:
  367. files["cloud_profiles/process.json"] = {
  368. "version": "1.0",
  369. "exported_at": datetime.now(UTC).isoformat(),
  370. "profiles": process_settings,
  371. }
  372. logger.info(
  373. f"Collected cloud profiles: {len(filament_settings)} filament, "
  374. f"{len(printer_settings)} printer, {len(process_settings)} process"
  375. )
  376. except Exception as e:
  377. logger.warning(f"Failed to collect cloud profiles: {e}")
  378. async def _collect_settings(self, db: AsyncSession, files: dict):
  379. """Collect app settings."""
  380. result = await db.execute(select(Settings))
  381. settings = result.scalars().all()
  382. # Filter out sensitive settings
  383. sensitive_keys = {"bambu_cloud_token", "auth_secret_key"}
  384. settings_data = {s.key: s.value for s in settings if s.key not in sensitive_keys}
  385. files["settings/app_settings.json"] = {
  386. "version": "1.0",
  387. "exported_at": datetime.now(UTC).isoformat(),
  388. "settings": settings_data,
  389. }
  390. async def _push_to_github(self, config: GitHubBackupConfig, files: dict) -> dict:
  391. """Push files to GitHub using the GitHub API.
  392. Uses the Git Data API to create blobs, tree, and commit.
  393. Returns:
  394. dict with status, message, commit_sha, files_changed
  395. """
  396. try:
  397. owner, repo = self._parse_repo_url(config.repository_url)
  398. branch = config.branch
  399. client = await self._get_client()
  400. headers = {
  401. "Authorization": f"token {config.access_token}",
  402. "Accept": "application/vnd.github.v3+json",
  403. "User-Agent": "Bambuddy-Backup",
  404. }
  405. # Get current branch reference
  406. ref_response = await client.get(
  407. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}", headers=headers
  408. )
  409. if ref_response.status_code == 404:
  410. # Branch doesn't exist, need to create it from default branch
  411. return await self._create_branch_and_push(client, headers, owner, repo, branch, files)
  412. if ref_response.status_code != 200:
  413. return {
  414. "status": "failed",
  415. "message": f"Failed to get branch ref: {ref_response.status_code}",
  416. "error": ref_response.text,
  417. }
  418. ref_data = ref_response.json()
  419. current_commit_sha = ref_data["object"]["sha"]
  420. # Get the current tree
  421. commit_response = await client.get(
  422. f"https://api.github.com/repos/{owner}/{repo}/git/commits/{current_commit_sha}", headers=headers
  423. )
  424. if commit_response.status_code != 200:
  425. return {"status": "failed", "message": "Failed to get current commit"}
  426. current_tree_sha = commit_response.json()["tree"]["sha"]
  427. # Get existing files to check for changes
  428. tree_response = await client.get(
  429. f"https://api.github.com/repos/{owner}/{repo}/git/trees/{current_tree_sha}?recursive=1", headers=headers
  430. )
  431. existing_files = {}
  432. if tree_response.status_code == 200:
  433. for item in tree_response.json().get("tree", []):
  434. if item["type"] == "blob":
  435. existing_files[item["path"]] = item["sha"]
  436. # Create blobs for changed files
  437. tree_items = []
  438. files_changed = 0
  439. for path, content in files.items():
  440. content_str = json.dumps(content, indent=2, default=str)
  441. content_bytes = content_str.encode("utf-8")
  442. content_sha = hashlib.sha1(f"blob {len(content_bytes)}\0".encode() + content_bytes).hexdigest()
  443. # Skip if file hasn't changed
  444. if path in existing_files and existing_files[path] == content_sha:
  445. continue
  446. # Create blob
  447. blob_response = await client.post(
  448. f"https://api.github.com/repos/{owner}/{repo}/git/blobs",
  449. headers=headers,
  450. json={"content": base64.b64encode(content_bytes).decode(), "encoding": "base64"},
  451. )
  452. if blob_response.status_code != 201:
  453. logger.error(f"Failed to create blob for {path}: {blob_response.text}")
  454. continue
  455. blob_sha = blob_response.json()["sha"]
  456. tree_items.append({"path": path, "mode": "100644", "type": "blob", "sha": blob_sha})
  457. files_changed += 1
  458. if not tree_items:
  459. return {"status": "skipped", "message": "No changes to commit", "commit_sha": None, "files_changed": 0}
  460. # Create new tree
  461. tree_response = await client.post(
  462. f"https://api.github.com/repos/{owner}/{repo}/git/trees",
  463. headers=headers,
  464. json={"base_tree": current_tree_sha, "tree": tree_items},
  465. )
  466. if tree_response.status_code != 201:
  467. return {"status": "failed", "message": f"Failed to create tree: {tree_response.text}"}
  468. new_tree_sha = tree_response.json()["sha"]
  469. # Create commit
  470. commit_message = f"Bambuddy backup - {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  471. commit_response = await client.post(
  472. f"https://api.github.com/repos/{owner}/{repo}/git/commits",
  473. headers=headers,
  474. json={"message": commit_message, "tree": new_tree_sha, "parents": [current_commit_sha]},
  475. )
  476. if commit_response.status_code != 201:
  477. return {"status": "failed", "message": f"Failed to create commit: {commit_response.text}"}
  478. new_commit_sha = commit_response.json()["sha"]
  479. # Update branch reference
  480. ref_update = await client.patch(
  481. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}",
  482. headers=headers,
  483. json={"sha": new_commit_sha},
  484. )
  485. if ref_update.status_code != 200:
  486. return {"status": "failed", "message": f"Failed to update branch: {ref_update.text}"}
  487. return {
  488. "status": "success",
  489. "message": f"Backup successful - {files_changed} files updated",
  490. "commit_sha": new_commit_sha,
  491. "files_changed": files_changed,
  492. }
  493. except Exception as e:
  494. logger.error(f"Push to GitHub failed: {e}")
  495. return {"status": "failed", "message": str(e), "error": str(e)}
  496. async def _create_branch_and_push(
  497. self, client: httpx.AsyncClient, headers: dict, owner: str, repo: str, branch: str, files: dict
  498. ) -> dict:
  499. """Create a new branch and push files when branch doesn't exist."""
  500. try:
  501. # Get default branch
  502. repo_response = await client.get(f"https://api.github.com/repos/{owner}/{repo}", headers=headers)
  503. if repo_response.status_code != 200:
  504. return {"status": "failed", "message": "Failed to get repo info"}
  505. default_branch = repo_response.json().get("default_branch", "main")
  506. # Get default branch ref
  507. ref_response = await client.get(
  508. f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{default_branch}", headers=headers
  509. )
  510. if ref_response.status_code != 200:
  511. # Empty repo - create initial commit
  512. return await self._create_initial_commit(client, headers, owner, repo, branch, files)
  513. base_sha = ref_response.json()["object"]["sha"]
  514. # Create new branch
  515. create_ref = await client.post(
  516. f"https://api.github.com/repos/{owner}/{repo}/git/refs",
  517. headers=headers,
  518. json={"ref": f"refs/heads/{branch}", "sha": base_sha},
  519. )
  520. if create_ref.status_code != 201:
  521. return {"status": "failed", "message": f"Failed to create branch: {create_ref.text}"}
  522. # Now push to the new branch (recursive call will find the branch)
  523. return await self._push_to_github(
  524. type(
  525. "Config",
  526. (),
  527. {
  528. "repository_url": f"https://github.com/{owner}/{repo}",
  529. "access_token": headers["Authorization"].replace("token ", ""),
  530. "branch": branch,
  531. },
  532. )(),
  533. files,
  534. )
  535. except Exception as e:
  536. return {"status": "failed", "message": str(e)}
  537. async def _create_initial_commit(
  538. self, client: httpx.AsyncClient, headers: dict, owner: str, repo: str, branch: str, files: dict
  539. ) -> dict:
  540. """Create initial commit in an empty repository."""
  541. try:
  542. # Create blobs
  543. tree_items = []
  544. for path, content in files.items():
  545. content_str = json.dumps(content, indent=2, default=str)
  546. blob_response = await client.post(
  547. f"https://api.github.com/repos/{owner}/{repo}/git/blobs",
  548. headers=headers,
  549. json={"content": base64.b64encode(content_str.encode()).decode(), "encoding": "base64"},
  550. )
  551. if blob_response.status_code == 201:
  552. tree_items.append(
  553. {"path": path, "mode": "100644", "type": "blob", "sha": blob_response.json()["sha"]}
  554. )
  555. # Create tree
  556. tree_response = await client.post(
  557. f"https://api.github.com/repos/{owner}/{repo}/git/trees",
  558. headers=headers,
  559. json={"tree": tree_items},
  560. )
  561. if tree_response.status_code != 201:
  562. return {"status": "failed", "message": "Failed to create tree"}
  563. tree_sha = tree_response.json()["sha"]
  564. # Create commit (no parents for initial)
  565. commit_response = await client.post(
  566. f"https://api.github.com/repos/{owner}/{repo}/git/commits",
  567. headers=headers,
  568. json={
  569. "message": f"Initial Bambuddy backup - {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}",
  570. "tree": tree_sha,
  571. },
  572. )
  573. if commit_response.status_code != 201:
  574. return {"status": "failed", "message": "Failed to create commit"}
  575. commit_sha = commit_response.json()["sha"]
  576. # Create branch ref
  577. ref_response = await client.post(
  578. f"https://api.github.com/repos/{owner}/{repo}/git/refs",
  579. headers=headers,
  580. json={"ref": f"refs/heads/{branch}", "sha": commit_sha},
  581. )
  582. if ref_response.status_code != 201:
  583. return {"status": "failed", "message": "Failed to create branch ref"}
  584. return {
  585. "status": "success",
  586. "message": f"Initial backup created - {len(files)} files",
  587. "commit_sha": commit_sha,
  588. "files_changed": len(files),
  589. }
  590. except Exception as e:
  591. return {"status": "failed", "message": str(e)}
  592. @property
  593. def is_running(self) -> bool:
  594. """Check if a backup is currently running."""
  595. return self._running_backup
  596. @property
  597. def progress(self) -> str | None:
  598. """Get current backup progress message."""
  599. return self._backup_progress
  600. async def get_logs(self, config_id: int, limit: int = 50, offset: int = 0) -> list[GitHubBackupLog]:
  601. """Get backup logs for a configuration."""
  602. async with async_session() as db:
  603. result = await db.execute(
  604. select(GitHubBackupLog)
  605. .where(GitHubBackupLog.config_id == config_id)
  606. .order_by(desc(GitHubBackupLog.started_at))
  607. .offset(offset)
  608. .limit(limit)
  609. )
  610. return list(result.scalars().all())
  611. # Singleton instance
  612. github_backup_service = GitHubBackupService()