Render markdown in gist and project sidebar titles; add content visibility and GIF picker
DevPlace CI / test (push) Failing after 1h5m29s
DevPlace CI / test (push) Failing after 1h5m29s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from devplacepy.attachments import (
|
||||
RemoteFetchError,
|
||||
is_extension_allowed,
|
||||
store_attachment_from_url,
|
||||
)
|
||||
from devplacepy.dependencies import json_or_form
|
||||
from devplacepy.models import GiphyAttachForm
|
||||
from devplacepy.responses import json_error
|
||||
from devplacepy.services.audit import record as audit
|
||||
from devplacepy.services.giphy import runtime
|
||||
from devplacepy.services.giphy.client import MAX_LIMIT, GiphyError
|
||||
from devplacepy.services.giphy.config import giphy_config
|
||||
from devplacepy.services.giphy.limits import UserRateLimiter
|
||||
from devplacepy.utils import require_user_api, track_action
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
limiter = UserRateLimiter()
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def giphy_status(request: Request):
|
||||
require_user_api(request)
|
||||
return JSONResponse({"configured": giphy_config().is_configured})
|
||||
|
||||
|
||||
def _limit_value(limit: int) -> int:
|
||||
return max(1, min(int(limit), MAX_LIMIT))
|
||||
|
||||
|
||||
def _error(exc: GiphyError) -> JSONResponse:
|
||||
status = exc.status if 400 <= exc.status < 600 else 502
|
||||
return json_error(status, exc.message)
|
||||
|
||||
|
||||
def _throttled(user: dict) -> JSONResponse | None:
|
||||
if limiter.allow(user["uid"]):
|
||||
return None
|
||||
response = json_error(429, "Too many GIF searches, slow down")
|
||||
response.headers["Retry-After"] = str(int(limiter.window_seconds))
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/search")
|
||||
async def search_gifs(
|
||||
request: Request, q: str = Query(default="", max_length=200), limit: int = 24
|
||||
):
|
||||
user = require_user_api(request)
|
||||
query = q.strip()
|
||||
if not query:
|
||||
return json_error(400, "q is required")
|
||||
if (refused := _throttled(user)) is not None:
|
||||
return refused
|
||||
try:
|
||||
gifs = await runtime.get_client().search(query, limit=_limit_value(limit))
|
||||
except GiphyError as exc:
|
||||
return _error(exc)
|
||||
return JSONResponse({"query": query, "results": gifs})
|
||||
|
||||
|
||||
@router.get("/trending")
|
||||
async def trending_gifs(request: Request, limit: int = 24):
|
||||
user = require_user_api(request)
|
||||
if (refused := _throttled(user)) is not None:
|
||||
return refused
|
||||
try:
|
||||
gifs = await runtime.get_client().trending(limit=_limit_value(limit))
|
||||
except GiphyError as exc:
|
||||
return _error(exc)
|
||||
return JSONResponse({"results": gifs})
|
||||
|
||||
|
||||
@router.post("/attach")
|
||||
async def attach_gif(
|
||||
request: Request,
|
||||
data: Annotated[GiphyAttachForm, Depends(json_or_form(GiphyAttachForm))],
|
||||
):
|
||||
user = require_user_api(request)
|
||||
client = runtime.get_client()
|
||||
try:
|
||||
gif = await client.get_gif(data.gif_id)
|
||||
except GiphyError as exc:
|
||||
return _error(exc)
|
||||
|
||||
url = (gif.get("original") or {}).get("url") or (gif.get("preview") or {}).get("url")
|
||||
if not url:
|
||||
return json_error(502, "GIPHY returned no downloadable file")
|
||||
|
||||
stem = (data.title or gif.get("title") or gif.get("id") or "giphy").strip()
|
||||
filename = f"{stem[:200]}.gif"
|
||||
if not is_extension_allowed(".gif"):
|
||||
return json_error(415, "GIF uploads are disabled")
|
||||
|
||||
try:
|
||||
result = await store_attachment_from_url(url, user["uid"], filename)
|
||||
except RemoteFetchError as exc:
|
||||
logger.warning("Giphy attach failed for %s: %s", gif.get("id"), exc.message)
|
||||
return json_error(exc.status, exc.message)
|
||||
|
||||
audit.record(
|
||||
request,
|
||||
"attachment.giphy",
|
||||
user=user,
|
||||
target_type="attachment",
|
||||
target_uid=result.get("uid"),
|
||||
target_label=filename,
|
||||
metadata={
|
||||
"gif_id": gif.get("id"),
|
||||
"source_host": urlparse(url).hostname,
|
||||
"size": result.get("file_size"),
|
||||
"mime": result.get("mime_type"),
|
||||
},
|
||||
summary=f"{user['username']} attached a GIF from Giphy",
|
||||
links=[audit.attachment_link(result.get("uid"), filename)],
|
||||
)
|
||||
track_action(user["uid"], "upload")
|
||||
return JSONResponse(result, status_code=201)
|
||||
Reference in New Issue
Block a user