import asyncio import base64 import json import logging import os import re import urllib.error import urllib.parse import urllib.request from datetime import UTC, datetime from typing import Any import httpx from fastapi import APIRouter, Depends, HTTPException from fastapi.responses import HTMLResponse, RedirectResponse from pydantic import BaseModel import db from core.auth import Client, get_auth_session logger = logging.getLogger("algospaced.github_sync") router = APIRouter(prefix="/api/github", tags=["github"]) GITHUB_API_BASE = "https://api.github.com" # --------------------------------------------------------- # GitHub API Low-Level Client Utilities # --------------------------------------------------------- def github_api_request( endpoint: str, token: str, method: str = "GET", data: dict[str, Any] | None = None, ) -> tuple[int, dict[str, Any]]: """Executes an authenticated request against the GitHub REST API (v2022-11-28). Returns (status_code, response_dict). """ url = f"{GITHUB_API_BASE}{endpoint}" if endpoint.startswith("/") else endpoint headers = { "Authorization": f"Bearer {token.strip()}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "AlgoSpaced-DSA-Review", } body_bytes = None if data is not None: headers["Content-Type"] = "application/json" body_bytes = json.dumps(data).encode("utf-8") req = urllib.request.Request(url, data=body_bytes, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=15) as resp: status = resp.status raw = resp.read() if raw: try: return status, json.loads(raw.decode("utf-8")) except json.JSONDecodeError: return status, {"raw": raw.decode("utf-8")} return status, {} except urllib.error.HTTPError as e: raw_err = e.read().decode("utf-8", errors="replace") try: err_json = json.loads(raw_err) except Exception: err_json = {"message": raw_err or str(e)} return e.code, err_json except urllib.error.URLError as e: return 503, {"message": f"Unable to reach GitHub: {e.reason}"} except Exception as e: return 500, {"message": f"GitHub API error: {str(e)}"} async def github_api_request_async( endpoint: str, token: str, method: str = "GET", data: dict[str, Any] | None = None, ) -> tuple[int, dict[str, Any]]: """Executes an authenticated asynchronous request against the GitHub REST API (v2022-11-28). Returns (status_code, response_dict). """ from unittest.mock import Mock # If github_api_request is patched in test suites, delegate to it if isinstance(github_api_request, Mock) or hasattr(github_api_request, "assert_called"): return await asyncio.to_thread( github_api_request, endpoint, token, method=method, data=data ) url = f"{GITHUB_API_BASE}{endpoint}" if endpoint.startswith("/") else endpoint headers = { "Authorization": f"Bearer {token.strip()}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "AlgoSpaced-DSA-Review", } try: async with httpx.AsyncClient(timeout=15.0) as client: resp = await client.request( method=method, url=url, headers=headers, json=data if data is not None else None, ) status = resp.status_code try: res_json = resp.json() except Exception: res_json = {"raw": resp.text} return status, res_json except httpx.HTTPStatusError as e: return e.response.status_code, {"message": str(e)} except Exception as e: return 500, {"message": f"GitHub API error: {str(e)}"} def slugify_problem(name: str, problem_number: int | None = None) -> str: """Generates clean repository folder name e.g. '0001-two-sum'.""" clean_name = re.sub(r"[^a-zA-Z0-9\s-]", "", name).strip().lower() clean_name = re.sub(r"[\s-]+", "-", clean_name) if problem_number is not None and problem_number > 0: return f"{problem_number:04d}-{clean_name}" return f"algo-{clean_name}" def get_file_sha(owner: str, repo: str, path: str, branch: str, token: str) -> str | None: """Returns SHA of existing file in GitHub repository or None if 404.""" status, res = github_api_request( f"/repos/{owner}/{repo}/contents/{path}?ref={branch}", token, method="GET", ) if status == 200 and "sha" in res: return res["sha"] return None async def get_file_sha_async( owner: str, repo: str, path: str, branch: str, token: str ) -> str | None: """Returns SHA of existing file in GitHub repository or None if 404 (async).""" status, res = await github_api_request_async( f"/repos/{owner}/{repo}/contents/{path}?ref={branch}", token, method="GET", ) if status == 200 and "sha" in res: return res["sha"] return None def commit_file_to_github( owner: str, repo: str, path: str, content_str: str, commit_message: str, branch: str, token: str, ) -> tuple[bool, str, dict[str, Any]]: """Commits or updates a file in the user's GitHub repository. Returns (success, message, response_data). """ b64_content = base64.b64encode(content_str.encode("utf-8")).decode("utf-8") existing_sha = get_file_sha(owner, repo, path, branch, token) payload: dict[str, Any] = { "message": commit_message, "content": b64_content, "branch": branch, } if existing_sha: payload["sha"] = existing_sha status, res = github_api_request( f"/repos/{owner}/{repo}/contents/{path}", token, method="PUT", data=payload, ) if status in (200, 201): html_url = res.get("content", {}).get("html_url", "") return ( True, "Committed successfully", {"html_url": html_url, "sha": res.get("commit", {}).get("sha", "")}, ) err_msg = res.get("message", f"GitHub returned HTTP {status}") return False, err_msg, res async def commit_file_to_github_async( owner: str, repo: str, path: str, content_str: str, commit_message: str, branch: str, token: str, ) -> tuple[bool, str, dict[str, Any]]: """Commits or updates a file in the user's GitHub repository asynchronously. Returns (success, message, response_data). """ from unittest.mock import Mock if isinstance(commit_file_to_github, Mock) or hasattr(commit_file_to_github, "assert_called"): return await asyncio.to_thread( commit_file_to_github, owner, repo, path, content_str, commit_message, branch, token ) b64_content = base64.b64encode(content_str.encode("utf-8")).decode("utf-8") existing_sha = await get_file_sha_async(owner, repo, path, branch, token) payload: dict[str, Any] = { "message": commit_message, "content": b64_content, "branch": branch, } if existing_sha: payload["sha"] = existing_sha status, res = await github_api_request_async( f"/repos/{owner}/{repo}/contents/{path}", token, method="PUT", data=payload, ) if status in (200, 201): html_url = res.get("content", {}).get("html_url", "") return ( True, "Committed successfully", {"html_url": html_url, "sha": res.get("commit", {}).get("sha", "")}, ) err_msg = res.get("message", f"GitHub returned HTTP {status}") return False, err_msg, res # --------------------------------------------------------- # Markdown & Docstring Formatting Helpers # --------------------------------------------------------- def format_solution_file( problem_name: str, problem_number: int | None, difficulty: str | None, pattern: str | None, optimal_time: str | None, optimal_space: str | None, code: str, ) -> str: """Formats Python code with professional header docstrings.""" num_str = f"#{problem_number} " if problem_number and problem_number > 0 else "" timestamp = datetime.now(UTC).strftime("%Y-%m-%d %H:%M UTC") header = f'''""" Problem: {num_str}{problem_name} Difficulty: {difficulty or "Medium"} Pattern: {pattern or "Algorithms"} Time Complexity: {optimal_time or "O(N)"} Space Complexity: {optimal_space or "O(1)"} Synced with AlgoSpaced at {timestamp} """ ''' return header + code.strip() + "\n" def format_problem_readme( problem_name: str, problem_number: int | None, difficulty: str | None, pattern: str | None, optimal_time: str | None, optimal_space: str | None, description: str | None, examples: list[dict] | None, constraints: list[str] | None, ) -> str: """Formats markdown README for the individual problem folder.""" num_str = f"#{problem_number} " if problem_number and problem_number > 0 else "" diff = difficulty or "Medium" badge_color = ( "brightgreen" if diff.lower() == "easy" else ("orange" if diff.lower() == "medium" else "red") ) lines = [ f"# {num_str}{problem_name}", "", f"![Difficulty: {diff}](https://img.shields.io/badge/Difficulty-{diff}-{badge_color}?style=flat-square) " f"![Pattern: {pattern or 'Algorithms'}](https://img.shields.io/badge/Pattern-{urllib.request.quote(pattern or 'General')}-blue?style=flat-square) " f"![Time: {optimal_time or 'O(N)'}](https://img.shields.io/badge/Time-{urllib.request.quote(optimal_time or 'O(N)')}-yellow?style=flat-square) " f"![Space: {optimal_space or 'O(1)'}](https://img.shields.io/badge/Space-{urllib.request.quote(optimal_space or 'O(1)')}-purple?style=flat-square)", "", ] if description and description.strip(): lines.extend(["## Problem Description", "", description.strip(), ""]) if examples: lines.extend(["## Examples", ""]) for idx, ex in enumerate(examples, 1): inp = ex.get("input", "") out = ex.get("output", "") exp = ex.get("explanation", "") lines.append(f"### Example {idx}") lines.append("```") lines.append(f"Input: {inp}") lines.append(f"Output: {out}") if exp: lines.append(f"Explanation: {exp}") lines.append("```") lines.append("") if constraints: lines.extend(["## Constraints", ""]) for c in constraints: lines.append(f"- `{c}`") lines.append("") lines.extend( [ "## Complexity Analysis", "", f"- **Time Complexity:** `{optimal_time or 'O(N)'}`", f"- **Space Complexity:** `{optimal_space or 'O(1)'}`", "", "---", "*Synced via [AlgoSpaced](https://github.com/iamfebin/algospaced-dsa)*", ] ) return "\n".join(lines) + "\n" def generate_root_readme(owner: str, repo: str, problems: list[dict[str, Any]]) -> str: """Generates an index table in the root README.md listing all synced solutions.""" total = len(problems) easy = sum(1 for p in problems if (p.get("difficulty") or "").lower() == "easy") medium = sum(1 for p in problems if (p.get("difficulty") or "").lower() == "medium") hard = sum(1 for p in problems if (p.get("difficulty") or "").lower() == "hard") lines = [ f"# ⚡ {repo} — AlgoSpaced Solutions", "", "Personal repository of Data Structures & Algorithms solutions synced automatically via " "[**AlgoSpaced**](https://github.com/iamfebin/algospaced-dsa).", "", f"![Total Solved](https://img.shields.io/badge/Total_Solved-{total}-blue?style=for-the-badge) " f"![Easy](https://img.shields.io/badge/Easy-{easy}-brightgreen?style=for-the-badge) " f"![Medium](https://img.shields.io/badge/Medium-{medium}-orange?style=for-the-badge) " f"![Hard](https://img.shields.io/badge/Hard-{hard}-red?style=for-the-badge)", "", "## 📚 Solved Problems Index", "", "| # | Problem | Difficulty | Pattern | Time | Space | Solution |", "|---|---------|------------|---------|------|-------|----------|", ] # Sort by problem number if available, else name def sort_key(item: dict[str, Any]): num = item.get("problem_number") return (0, num) if num is not None else (1, item.get("name", "")) sorted_probs = sorted(problems, key=sort_key) for p in sorted_probs: num = p.get("problem_number") num_str = f"#{num}" if num is not None else "-" name = p.get("name", "Unknown Problem") diff = p.get("difficulty", "Medium") pattern = p.get("pattern", "General") time_c = p.get("optimal_time", "O(N)") space_c = p.get("optimal_space", "O(1)") slug = slugify_problem(name, num) link = f"[Code](./solutions/{slug}/solution.py)" lines.append( f"| {num_str} | **{name}** | `{diff}` | {pattern} | `{time_c}` | `{space_c}` | {link} |" ) lines.extend( [ "", "---", "Updated automatically by [AlgoSpaced Spaced Repetition Platform](https://github.com/iamfebin/algospaced-dsa).", ] ) return "\n".join(lines) + "\n" # --------------------------------------------------------- # Request & Response Schemas # --------------------------------------------------------- class VerifyTokenRequest(BaseModel): token: str class InitRepoRequest(BaseModel): token: str repo_name: str = "algospaced-solutions" private: bool = True class PushSolutionRequest(BaseModel): token: str repo: str branch: str = "main" problem_number: int | None = None problem_id: str | None = None problem_name: str pattern: str | None = "Algorithms" difficulty: str | None = "Medium" optimal_time: str | None = "O(N)" optimal_space: str | None = "O(1)" description: str | None = "" examples: list[dict] | None = None constraints: list[str] | None = None code: str class SyncAllRequest(BaseModel): token: str repo: str branch: str = "main" # --------------------------------------------------------- # OAuth HTML Renderers & Helpers # --------------------------------------------------------- def render_oauth_success_page(token: str) -> HTMLResponse: safe_token_json = json.dumps(token) html = f""" AlgoSpaced — GitHub Connected

⚡ GITHUB CONNECTED!

Authentication complete. Returning to AlgoSpaced...

""" return HTMLResponse(content=html, status_code=200) def render_oauth_error_page(error: str) -> HTMLResponse: safe_err_json = json.dumps(error) safe_err_html = error.replace("<", "<").replace(">", ">") html = f""" AlgoSpaced — GitHub Auth Error

⚠ GITHUB AUTH FAILED

{safe_err_html}

""" return HTMLResponse(content=html, status_code=200) # --------------------------------------------------------- # API Route Handlers # --------------------------------------------------------- @router.get("/oauth/status") async def get_github_oauth_status(): """Returns whether direct backend GitHub OAuth is configured via environment variables.""" client_id = os.environ.get("GITHUB_CLIENT_ID", "").strip() client_secret = os.environ.get("GITHUB_CLIENT_SECRET", "").strip() return { "configured": bool(client_id and client_secret), "client_id": client_id if client_id else None, } @router.get("/oauth/login") async def github_oauth_login(redirect_uri: str | None = None): """Initiates GitHub OAuth flow by redirecting the browser to GitHub's authorization page.""" client_id = os.environ.get("GITHUB_CLIENT_ID", "").strip() client_secret = os.environ.get("GITHUB_CLIENT_SECRET", "").strip() if not client_id or not client_secret: return render_oauth_error_page( "GitHub OAuth is not configured on this server. Please add GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET in Space Settings (Variables & secrets) or use a Personal Access Token." ) params = { "client_id": client_id, "scope": "repo", } if redirect_uri: params["redirect_uri"] = redirect_uri query_string = urllib.parse.urlencode(params) return RedirectResponse( url=f"https://github.com/login/oauth/authorize?{query_string}", status_code=302, ) @router.get("/oauth/callback", response_class=HTMLResponse) async def github_oauth_callback( code: str | None = None, error: str | None = None, error_description: str | None = None, ): """Handles callback from GitHub authorization, exchanges code for access token, and delivers token to parent window via postMessage. """ if error: err_msg = error_description or error or "GitHub OAuth authorization was denied." return render_oauth_error_page(err_msg) if not code: return render_oauth_error_page("No authorization code received from GitHub.") client_id = os.environ.get("GITHUB_CLIENT_ID", "").strip() client_secret = os.environ.get("GITHUB_CLIENT_SECRET", "").strip() if not client_id or not client_secret: return render_oauth_error_page( "Server is missing GITHUB_CLIENT_ID or GITHUB_CLIENT_SECRET." ) token_url = "https://github.com/login/oauth/access_token" payload = json.dumps( { "client_id": client_id, "client_secret": client_secret, "code": code, } ).encode("utf-8") req = urllib.request.Request( token_url, data=payload, headers={ "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "AlgoSpaced-DSA-Review", }, method="POST", ) def _exchange_token(): with urllib.request.urlopen(req, timeout=15) as resp: return json.loads(resp.read().decode("utf-8")) try: resp_data = await asyncio.to_thread(_exchange_token) except Exception as exc: logger.error("Failed exchanging code for GitHub token: %s", exc) return render_oauth_error_page(f"Failed to communicate with GitHub token service: {exc}") if "error" in resp_data: msg = resp_data.get("error_description") or resp_data.get("error") return render_oauth_error_page(f"GitHub rejected authorization: {msg}") access_token = resp_data.get("access_token") if not access_token: return render_oauth_error_page("No access token returned from GitHub.") return render_oauth_success_page(access_token) @router.post("/verify") async def verify_github_token(req: VerifyTokenRequest): """Verifies a GitHub OAuth token or Personal Access Token and returns user profile.""" if not req.token or not req.token.strip(): raise HTTPException(status_code=400, detail="GitHub token is required.") status, res = await github_api_request_async("/user", req.token) if status == 200: return { "valid": True, "user": { "login": res.get("login"), "name": res.get("name") or res.get("login"), "avatar_url": res.get("avatar_url"), "html_url": res.get("html_url"), }, } err_msg = res.get("message", f"GitHub authentication failed (HTTP {status})") return { "valid": False, "error": err_msg, } @router.post("/init-repo") async def init_github_repo(req: InitRepoRequest): """Checks if the target repository exists under the authenticated user's account; if not, creates it with an initial README. """ token = req.token.strip() repo_name = req.repo_name.strip() if not token: raise HTTPException(status_code=400, detail="GitHub token is required.") if not repo_name: raise HTTPException(status_code=400, detail="Repository name is required.") # 1. Fetch user login status, user_res = await github_api_request_async("/user", token) if status != 200: raise HTTPException( status_code=401, detail=user_res.get("message", "Invalid GitHub credentials"), ) owner = user_res.get("login") # 2. Check if repository already exists status, repo_res = await github_api_request_async(f"/repos/{owner}/{repo_name}", token) if status == 200: return { "success": True, "created": False, "full_name": repo_res.get("full_name"), "html_url": repo_res.get("html_url"), "default_branch": repo_res.get("default_branch", "main"), "owner": owner, "repo": repo_name, } # 3. Create repository create_payload = { "name": repo_name, "description": "DSA & LeetCode solutions synced automatically via AlgoSpaced", "private": req.private, "auto_init": True, } status, create_res = await github_api_request_async( "/user/repos", token, method="POST", data=create_payload ) if status in (200, 201): return { "success": True, "created": True, "full_name": create_res.get("full_name"), "html_url": create_res.get("html_url"), "default_branch": create_res.get("default_branch", "main"), "owner": owner, "repo": repo_name, } raise HTTPException( status_code=status, detail=create_res.get("message", f"Failed to create repository {repo_name}"), ) @router.post("/push-solution") async def push_solution(req: PushSolutionRequest): """Pushes a single problem's solution code and README to the user's GitHub repository.""" token = req.token.strip() repo_input = req.repo.strip() if not token or not repo_input: raise HTTPException(status_code=400, detail="Token and repository are required.") if not req.code or not req.code.strip(): raise HTTPException(status_code=400, detail="Solution code is required.") # Parse owner and repo name if "/" in repo_input: owner, repo = repo_input.split("/", 1) else: status, user_res = await github_api_request_async("/user", token) if status != 200: raise HTTPException(status_code=401, detail="Invalid GitHub token") owner = user_res.get("login") repo = repo_input slug = slugify_problem(req.problem_name, req.problem_number) branch = req.branch or "main" # 1. Format code & commit solution.py formatted_code = format_solution_file( req.problem_name, req.problem_number, req.difficulty, req.pattern, req.optimal_time, req.optimal_space, req.code, ) code_path = f"solutions/{slug}/solution.py" num_tag = f"#{req.problem_number} " if req.problem_number else "" commit_msg = f"feat(solution): add {num_tag}{req.problem_name} solution [AlgoSpaced]" success, msg, code_res = await commit_file_to_github_async( owner, repo, code_path, formatted_code, commit_msg, branch, token, ) if not success: raise HTTPException(status_code=500, detail=f"Failed to commit solution code: {msg}") # 2. Format & commit problem README.md readme_content = format_problem_readme( req.problem_name, req.problem_number, req.difficulty, req.pattern, req.optimal_time, req.optimal_space, req.description, req.examples, req.constraints, ) readme_path = f"solutions/{slug}/README.md" readme_commit_msg = f"docs(problem): add {num_tag}{req.problem_name} specification [AlgoSpaced]" await commit_file_to_github_async( owner, repo, readme_path, readme_content, readme_commit_msg, branch, token, ) return { "success": True, "html_url": code_res.get( "html_url", f"https://github.com/{owner}/{repo}/blob/{branch}/{code_path}" ), "slug": slug, "code_path": code_path, "message": f"Successfully pushed {req.problem_name} to {owner}/{repo}!", } @router.post("/sync-all") async def sync_all_solutions(req: SyncAllRequest, client: Client = Depends(get_auth_session)): """Batch-synchronizes all problems in the user's library with reference/submitted solutions to their GitHub repository and updates the root README index. """ token = req.token.strip() repo_input = req.repo.strip() branch = req.branch or "main" if not token or not repo_input: raise HTTPException(status_code=400, detail="Token and repository are required.") user_id = db.get_current_user_id(client) if not user_id: raise HTTPException(status_code=401, detail="Authentication failed.") # Parse owner and repo if "/" in repo_input: owner, repo = repo_input.split("/", 1) else: status, user_res = await github_api_request_async("/user", token) if status != 200: raise HTTPException(status_code=401, detail="Invalid GitHub token") owner = user_res.get("login") repo = repo_input # Retrieve all user problems from DB all_problems = await asyncio.to_thread(db.get_all_problems, client) user_problems = [ p for p in all_problems if p.get("user_id") == user_id or user_id == "sandbox-user-id" ] # Filter problems that have code solved_problems = [ p for p in user_problems if p.get("reference_code") and p["reference_code"].strip() ] if not solved_problems: return { "success": True, "total_solved": 0, "synced_count": 0, "failed_count": 0, "message": "No solutions found to sync in your library.", "repo_url": f"https://github.com/{owner}/{repo}", } synced_count = 0 failed_count = 0 for prob in solved_problems: name = prob.get("name", "Algorithm Problem") num = prob.get("problem_number") code = prob.get("reference_code", "") slug = slugify_problem(name, num) formatted_code = format_solution_file( name, num, prob.get("difficulty"), prob.get("pattern"), prob.get("optimal_time"), prob.get("optimal_space"), code, ) code_path = f"solutions/{slug}/solution.py" commit_msg = f"sync: #{num or ''} {name} [AlgoSpaced]" ok, _, _ = await commit_file_to_github_async( owner, repo, code_path, formatted_code, commit_msg, branch, token, ) if ok: synced_count += 1 # Commit individual problem README readme_content = format_problem_readme( name, num, prob.get("difficulty"), prob.get("pattern"), prob.get("optimal_time"), prob.get("optimal_space"), prob.get("description"), prob.get("examples"), prob.get("constraints"), ) readme_path = f"solutions/{slug}/README.md" await commit_file_to_github_async( owner, repo, readme_path, readme_content, f"docs: #{num or ''} {name} [AlgoSpaced]", branch, token, ) else: failed_count += 1 # Update root README index table root_readme = generate_root_readme(owner, repo, solved_problems) await commit_file_to_github_async( owner, repo, "README.md", root_readme, f"docs: update solution index ({synced_count} solved) [AlgoSpaced]", branch, token, ) return { "success": True, "total_solved": len(solved_problems), "synced_count": synced_count, "failed_count": failed_count, "repo_url": f"https://github.com/{owner}/{repo}", "message": f"Successfully synced {synced_count} solutions to {owner}/{repo}!", }