108 lines
3.7 KiB
Python
108 lines
3.7 KiB
Python
"""
|
|
controllers/tenor.py — GIPHY API proxy (requests-based).
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
import requests
|
|
from bottle import route, request, response
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_giphy_key: str = "GIPHY_API_KEY"
|
|
_session = requests.Session()
|
|
_session.headers.update({'User-Agent': 'GIPHY-Proxy/1.0'})
|
|
|
|
GIPHY_BASE = "https://api.giphy.com/v1/gifs"
|
|
|
|
|
|
def init(tenor_cfg):
|
|
global _giphy_key
|
|
if hasattr(tenor_cfg, 'api_key') and tenor_cfg.api_key:
|
|
_giphy_key = tenor_cfg.api_key
|
|
logger.info(f"GIPHY API key initialized: {_giphy_key[:10]}...")
|
|
else:
|
|
logger.warning("No GIPHY API key configured, using default placeholder")
|
|
|
|
|
|
def _build_params(query_params, extra=None):
|
|
params = {
|
|
"api_key": _giphy_key,
|
|
"limit": query_params.get("limit", "20"),
|
|
"rating": query_params.get("rating", "g"),
|
|
"lang": query_params.get("lang", "en"),
|
|
}
|
|
if query_params.get("offset"):
|
|
params["offset"] = query_params["offset"]
|
|
if extra:
|
|
params.update(extra)
|
|
return params
|
|
|
|
|
|
def _transform_giphy_result(gif):
|
|
"""Convert GIPHY format -> unified {id, title, file: {hd, md, sm, xs}}."""
|
|
images = gif.get("images", {})
|
|
return {
|
|
"id": gif.get("id"),
|
|
"title": gif.get("title", ""),
|
|
"slug": gif.get("slug", gif.get("id", "")),
|
|
"file": {
|
|
"hd": {"gif": {"url": images.get("original", {}).get("url", "")}},
|
|
"md": {"gif": {"url": images.get("downsized_large", {}).get("url", "") or images.get("downsized", {}).get("url", "")}},
|
|
"sm": {"gif": {"url": images.get("fixed_width_downsampled", {}).get("url", "") or images.get("fixed_width", {}).get("url", "")}},
|
|
"xs": {"gif": {"url": images.get("fixed_width_small", {}).get("url", "")}},
|
|
},
|
|
"blur_preview": images.get("preview_gif", {}).get("url", ""),
|
|
}
|
|
|
|
|
|
def _fetch_giphy(endpoint, params):
|
|
url = f"{GIPHY_BASE}/{endpoint}"
|
|
logger.debug(f"GET {url}")
|
|
try:
|
|
resp = _session.get(url, params=params, timeout=15)
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
results = data.get("data", [])
|
|
if isinstance(results, dict):
|
|
results = [results]
|
|
transformed = [_transform_giphy_result(g) for g in results]
|
|
return {
|
|
"success": True,
|
|
"results": transformed,
|
|
"pagination": {
|
|
"current_page": (int(params.get("offset", 0)) // max(int(params.get("limit", 20)), 1)) + 1,
|
|
"per_page": params.get("limit", 20),
|
|
"has_next": len(transformed) >= int(params.get("limit", 20)),
|
|
},
|
|
}
|
|
except requests.exceptions.RequestException as e:
|
|
error_msg = f"GIPHY error: {str(e)}"
|
|
logger.error(error_msg)
|
|
response.status = 502
|
|
return {"success": False, "error": error_msg}
|
|
except Exception as e:
|
|
error_msg = f"Unexpected error: {str(e)}"
|
|
logger.error(error_msg)
|
|
response.status = 502
|
|
return {"success": False, "error": error_msg}
|
|
|
|
|
|
def register_routes(app):
|
|
@app.route("/api/gifs/trending", method="GET")
|
|
def gifs_trending():
|
|
logger.debug(f"Trending request: {dict(request.query)}")
|
|
params = _build_params(request.query)
|
|
return _fetch_giphy("trending", params)
|
|
|
|
@app.route("/api/gifs/search", method="GET")
|
|
def gifs_search():
|
|
logger.debug(f"Search request: {dict(request.query)}")
|
|
q = request.query.get("q", "")
|
|
if not q:
|
|
response.status = 400
|
|
return {"success": False, "error": "Missing query"}
|
|
params = _build_params(request.query, extra={"q": q})
|
|
return _fetch_giphy("search", params)
|