cloudairambo / routers /developer.py
rihancloud's picture
Deploy clean FastAPI backend without node_modules
99fdb5f
Raw History Blame Contribute Delete
10.6 kB
# backend/routers/developer.py
from fastapi import APIRouter, Form, File, UploadFile, Depends, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
import json
import os
import tempfile
import subprocess
import shutil
import traceback
from core.database import get_db
from core.dependencies import LogToolUsage
from services.developer_service import (
format_code_raw,
format_code_html,
json_pretty,
json_minify,
json_validate,
xml_pretty,
xml_validate,
sql_format,
base64_encode,
base64_decode,
json_to_csv,
analyze_url,
regex_test,
generate_hash,
api_request,
)
from utils.file_utils import save_upload_file
from utils.response_utils import send_file
from services.stats_service import increment_tool_usage
router = APIRouter()
# -----------------------
# Helper: Prettier Runner
# -----------------------
def _find_local_prettier():
"""
Try to find a local prettier binary in node_modules/.bin,
or fall back to 'npx prettier' or global 'prettier'.
Returns a list (command) suitable for subprocess.run.
"""
# 1) project local node_modules/.bin/prettier
local_bin = os.path.join(os.getcwd(), "node_modules", ".bin", "prettier")
if os.path.isfile(local_bin) and os.access(local_bin, os.X_OK):
return [local_bin]
# 2) npx (use npx prettier)
if shutil.which("npx"):
return ["npx", "prettier"]
# 3) global prettier
if shutil.which("prettier"):
return ["prettier"]
return None
def run_prettier_on_text(code: str, language: str, timeout: int = 10) -> str:
"""
Run Prettier (if available) to format code. If Prettier is not available or fails,
raise HTTPException. Caller may choose to fallback to Python formatter.
"""
cmd_prefix = _find_local_prettier()
if not cmd_prefix:
raise FileNotFoundError("Prettier not found (install locally with `npm i --save-dev prettier` or make `prettier` available).")
# Map language to prettier parser
parser_map = {
"javascript": "babel",
"typescript": "typescript",
"json": "json",
"html": "html",
"xml": "html",
"css": "css",
}
parser = parser_map.get(language.lower(), "babel")
# Prepare temp input file (prettier accepts file path or stdin; we'll use stdin to avoid temp files)
try:
proc = subprocess.run(
cmd_prefix + ["--parser", parser, "--stdin-filepath", f"file.{language}"],
input=code.encode("utf-8"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
)
except subprocess.TimeoutExpired as te:
raise RuntimeError(f"Prettier timed out: {te}")
if proc.returncode != 0:
stderr = proc.stderr.decode("utf-8", errors="ignore")
raise RuntimeError(f"Prettier failed: {stderr.strip() or 'unknown error'}")
return proc.stdout.decode("utf-8")
# ---------------- Code Formatter (Conditional Logging) ----------------
# We keep manual logging because the tool name / mode may be conditional.
@router.post("/code/format")
async def api_code_format(
code: str = Form(...),
lang: Optional[str] = Form(None),
html: bool = Form(False),
db: Session = Depends(get_db),
):
"""
Format provided code string.
If html=True, return highlighted HTML output (via format_code_html).
Otherwise return raw formatted code.
"""
try:
if html:
out = format_code_html(code, lang)
increment_tool_usage(db, "code_format_html")
return {"html": out}
else:
out = format_code_raw(code, lang)
increment_tool_usage(db, "code_format_raw")
return {"code": out}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ---------------- JSON Tools (Conditional Logging) ----------------
@router.post("/json/format")
async def api_json_format(text: str = Form(...), minify: bool = Form(False), db: Session = Depends(get_db)):
valid, msg = json_validate(text)
if not valid:
raise HTTPException(status_code=400, detail=msg)
try:
if minify:
out = json_minify(text)
increment_tool_usage(db, "json_minify")
else:
out = json_pretty(text)
increment_tool_usage(db, "json_pretty")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"result": out}
# ---------------- XML Tools (Automatic Logging) ----------------
@router.post("/xml/format", dependencies=[Depends(LogToolUsage("xml_pretty"))])
async def api_xml_format(text: str = Form(...), db: Session = Depends(get_db)):
valid, msg = xml_validate(text)
if not valid:
raise HTTPException(status_code=400, detail=msg)
try:
out = xml_pretty(text)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"result": out}
# ---------------- SQL Formatter (Automatic Logging) ----------------
@router.post("/sql/format", dependencies=[Depends(LogToolUsage("sql_format"))])
async def api_sql_format(query: str = Form(...), db: Session = Depends(get_db)):
try:
out = sql_format(query)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"result": out}
# ---------------- Base64 (Automatic Logging) ----------------
@router.post("/base64/encode", dependencies=[Depends(LogToolUsage("b64_encode"))])
async def api_b64_encode(text: str = Form(...), db: Session = Depends(get_db)):
out = base64_encode(text)
return {"result": out}
@router.post("/base64/decode", dependencies=[Depends(LogToolUsage("b64_decode"))])
async def api_b64_decode(text: str = Form(...), db: Session = Depends(get_db)):
out = base64_decode(text)
return {"result": out}
# ---------------- JSON -> CSV (Automatic Logging) ----------------
@router.post("/json/to-csv", dependencies=[Depends(LogToolUsage("json_to_csv"))])
async def api_json_to_csv(file: UploadFile = File(...), db: Session = Depends(get_db)):
p = save_upload_file(file)
try:
with open(p, "r", encoding="utf-8") as f:
json_content = f.read()
out_path = json_to_csv(json_content)
finally:
try:
os.remove(p)
except Exception:
pass
return send_file(out_path)
# ---------------- URL Analyzer (Automatic Logging) ----------------
@router.post("/url/analyze", dependencies=[Depends(LogToolUsage("url_analyze"))])
async def api_url_analyze(url: str = Form(...), db: Session = Depends(get_db)):
try:
out = analyze_url(url)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return out
# ---------------- Regex Tester (Automatic Logging) ----------------
@router.post("/regex/test", dependencies=[Depends(LogToolUsage("regex_test"))])
async def api_regex_test(pattern: str = Form(...), text: str = Form(...), db: Session = Depends(get_db)):
out = regex_test(pattern, text)
return out
# ---------------- Hash Generator (Automatic Logging) ----------------
@router.post("/hash/generate", dependencies=[Depends(LogToolUsage("hash_generate"))])
async def api_hash_generate(text: str = Form(...), algo: str = Form("md5"), db: Session = Depends(get_db)):
try:
out = generate_hash(text, algo)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return {"hash": out}
# ---------------- API Tester (Automatic Logging) ----------------
@router.post("/api/test", dependencies=[Depends(LogToolUsage("api_test"))])
async def api_api_test(
method: str = Form("GET"),
url: str = Form(...),
headers: Optional[str] = Form(None),
params: Optional[str] = Form(None),
body: Optional[str] = Form(None),
timeout: int = Form(20),
db: Session = Depends(get_db),
):
try:
hdrs = json.loads(headers) if headers else {}
pms = json.loads(params) if params else {}
except Exception as e:
raise HTTPException(status_code=400, detail="headers/params must be valid JSON if provided: " + str(e))
out = api_request(method, url, headers=hdrs, params=pms, body=body, timeout=timeout)
return out
# -------------------------
# CLEAN /developer/format ENDPOINT
# -------------------------
from fastapi import UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse
import tempfile
import subprocess
import os
@router.post("/format")
async def format_code_backend(
file: UploadFile = File(...),
language: str = Form(...)
):
"""
Accept uploaded code file and format it using Prettier backend.
Returns formatted file as FileResponse.
"""
# Read uploaded file safely
try:
raw_code = (await file.read()).decode("utf-8", errors="ignore")
except Exception:
raise HTTPException(status_code=400, detail="Failed to read uploaded file")
if not raw_code.strip():
raise HTTPException(status_code=400, detail="Empty code input")
# Temp file for input
tmp_in = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
tmp_in.write(raw_code.encode("utf-8"))
tmp_in.close()
# Temp file for output
tmp_out = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
tmp_out.close()
# Language → Prettier parser mapping
parser_map = {
"javascript": "babel",
"json": "json",
"html": "html",
"xml": "html",
"css": "css",
}
parser = parser_map.get(language, "babel")
# Run Prettier
try:
subprocess.run(
[
"npx", "prettier",
"--parser", parser,
tmp_in.name
],
check=True,
stdout=open(tmp_out.name, "w"),
stderr=subprocess.PIPE
)
except subprocess.CalledProcessError as e:
error_details = e.stderr.decode() if e.stderr else "Unknown error"
raise HTTPException(
status_code=400,
detail=f"Prettier formatting failed: {error_details}"
)
# Prepare output
final_output = tmp_out.name
# Cleanup input temp file
try:
os.remove(tmp_in.name)
except:
pass
return FileResponse(
final_output,
media_type="text/plain",
filename=f"formatted_{language}.txt"
)