83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
"""GIPHY search for the embedded Kronic Chat browser.
|
|
|
|
This route runs in Chat's FastAPI application and is exposed by the
|
|
existing /borg-chat/ gateway, without an Nginx custom location.
|
|
"""
|
|
|
|
import asyncio
|
|
import os
|
|
import time
|
|
from collections import OrderedDict
|
|
|
|
import requests
|
|
from fastapi import APIRouter, HTTPException, Query
|
|
|
|
router = APIRouter()
|
|
_GIPHY_SEARCH_URL = "https://api.giphy.com/v1/gifs/search"
|
|
_CACHE_TTL_SECONDS = 300
|
|
_CACHE_LIMIT = 100
|
|
_cache = OrderedDict()
|
|
|
|
|
|
def _fetch_giphy(query: str, key: str) -> dict:
|
|
try:
|
|
response = requests.get(
|
|
_GIPHY_SEARCH_URL,
|
|
params={"api_key": key, "q": query, "limit": 25, "rating": "g"},
|
|
timeout=(5, 12),
|
|
)
|
|
response.raise_for_status()
|
|
payload = response.json()
|
|
except requests.RequestException as exc:
|
|
# Avoid passing the token or upstream URL into user-visible errors.
|
|
raise HTTPException(502, "GIPHY search service unavailable") from exc
|
|
except ValueError as exc:
|
|
raise HTTPException(502, "GIPHY returned an invalid response") from exc
|
|
|
|
items = []
|
|
for item in payload.get("data", []):
|
|
images = item.get("images") or {}
|
|
original = (images.get("original") or {}).get("url")
|
|
preview = (images.get("downsized_medium") or {}).get("url") or \
|
|
(images.get("downsized") or {}).get("url") or original
|
|
thumbnail = (images.get("fixed_width_small") or {}).get("url") or \
|
|
(images.get("fixed_height_small") or {}).get("url") or preview
|
|
if not preview:
|
|
continue
|
|
items.append({
|
|
"id": item.get("id"),
|
|
"title": item.get("title", ""),
|
|
"url": preview,
|
|
"originalUrl": original or preview,
|
|
"thumbnail": thumbnail or preview,
|
|
"source": "giphy",
|
|
})
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/api/giphy/search")
|
|
async def search_giphy(
|
|
q: str = Query(..., min_length=1, max_length=150),
|
|
refresh: bool = False,
|
|
):
|
|
key = os.getenv("GIPHY_API_KEY", "").strip()
|
|
if not key:
|
|
raise HTTPException(503, "GIPHY_API_KEY is not configured in Chat")
|
|
query = q.strip()
|
|
if not query:
|
|
return {"items": []}
|
|
cache_key = query.casefold()
|
|
now = time.monotonic()
|
|
if not refresh and cache_key in _cache:
|
|
expiry, result = _cache[cache_key]
|
|
if now < expiry:
|
|
_cache.move_to_end(cache_key)
|
|
return result
|
|
del _cache[cache_key]
|
|
result = await asyncio.to_thread(_fetch_giphy, query, key)
|
|
_cache[cache_key] = (time.monotonic() + _CACHE_TTL_SECONDS, result)
|
|
_cache.move_to_end(cache_key)
|
|
while len(_cache) > _CACHE_LIMIT:
|
|
_cache.popitem(last=False)
|
|
return result
|