File size: 10,554 Bytes
99fdb5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# 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"
    )