mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): add shortcut for rendering grade widget with username query.
This commit is contained in:
+76
-1
@@ -24,9 +24,10 @@ from functools import wraps
|
|||||||
from threading import BoundedSemaphore, Lock
|
from threading import BoundedSemaphore, Lock
|
||||||
from flask import Flask, jsonify, request, Response, send_from_directory, session
|
from flask import Flask, jsonify, request, Response, send_from_directory, session
|
||||||
|
|
||||||
from . import auth, config, db, fetcher_client, placeholder
|
from . import auth, config, db, fetcher_client, placeholder, processor
|
||||||
from .themes import THEMES
|
from .themes import THEMES
|
||||||
from .utils import is_valid_username, settings_size_ok
|
from .utils import is_valid_username, settings_size_ok
|
||||||
|
from .widgets import render_grade_widget
|
||||||
import json as _json
|
import json as _json
|
||||||
|
|
||||||
log = logging.getLogger("generator.api")
|
log = logging.getLogger("generator.api")
|
||||||
@@ -400,6 +401,12 @@ def sanitize_settings(body: dict) -> dict:
|
|||||||
@app.route("/", defaults={"path": ""})
|
@app.route("/", defaults={"path": ""})
|
||||||
@app.route("/<path:path>")
|
@app.route("/<path:path>")
|
||||||
def spa(path: str):
|
def spa(path: str):
|
||||||
|
# Drop-in shortcut: `/?username=X` (or `/api/?username=X`) force-renders
|
||||||
|
# just the developer profile (grade) widget for that user and returns the
|
||||||
|
# SVG directly. No SPA, no composite — the single widget that README
|
||||||
|
# embeds care about. `/api/<u>` and friends keep working below.
|
||||||
|
if path in ("", "api", "api/") and request.args.get("username"):
|
||||||
|
return _serve_profile_widget(request.args.get("username", ""))
|
||||||
if path.startswith("api/"):
|
if path.startswith("api/"):
|
||||||
return jsonify({"error": "not found"}), 404
|
return jsonify({"error": "not found"}), 404
|
||||||
if path:
|
if path:
|
||||||
@@ -645,6 +652,74 @@ def _placeholder_response(variant: str, username: str, theme: str = "dark") -> R
|
|||||||
"X-Content-Type-Options": "nosniff"})
|
"X-Content-Type-Options": "nosniff"})
|
||||||
|
|
||||||
|
|
||||||
|
def _serve_profile_widget(username: str) -> Response:
|
||||||
|
"""Force-generate and return the developer profile (grade) widget SVG.
|
||||||
|
|
||||||
|
Powers the `/?username=X` and `/api/?username=X` shortcuts. Unlike the
|
||||||
|
cached `/api/<u>` composite path, this one will auto-enroll a new user
|
||||||
|
(subject to the daily cap) so a first-time visitor who pastes a
|
||||||
|
username in the URL gets a usable SVG back on the first request.
|
||||||
|
Only the grade widget is rendered; no composite, no other widgets.
|
||||||
|
"""
|
||||||
|
if not is_valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
|
username = username.lower()
|
||||||
|
if not _rate_limit("read"):
|
||||||
|
return jsonify({"error": "rate_limited"}), 429
|
||||||
|
|
||||||
|
settings_row = db.get_settings(username)
|
||||||
|
if settings_row is None:
|
||||||
|
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||||
|
return _placeholder_response("rate_limited", username)
|
||||||
|
defaults = {
|
||||||
|
"theme": "dark",
|
||||||
|
"enabled": config.ENABLED_WIDGETS,
|
||||||
|
"widget_order": config.WIDGET_ORDER,
|
||||||
|
}
|
||||||
|
db.enroll(username, defaults)
|
||||||
|
settings_row = db.get_settings(username)
|
||||||
|
if settings_row is None:
|
||||||
|
return _placeholder_response("building", username)
|
||||||
|
|
||||||
|
theme_raw = settings_row["settings"].get("theme", "dark")
|
||||||
|
theme = theme_raw if isinstance(theme_raw, str) and theme_raw in THEMES else "dark"
|
||||||
|
|
||||||
|
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
|
||||||
|
if not acquired:
|
||||||
|
resp = jsonify({"error": "busy"})
|
||||||
|
resp.status_code = 503
|
||||||
|
resp.headers["Retry-After"] = "5"
|
||||||
|
return resp
|
||||||
|
try:
|
||||||
|
result = fetcher_client.get_data(username)
|
||||||
|
payload = result.get("data") or {}
|
||||||
|
if payload.get("error") == "not_found":
|
||||||
|
return _placeholder_response("not_found", username, theme=theme)
|
||||||
|
grade = processor.compute_grade(
|
||||||
|
payload,
|
||||||
|
custom_tags=settings_row["settings"].get("custom_tags"),
|
||||||
|
)
|
||||||
|
ws = (settings_row["settings"].get("widget_settings") or {}).get("grade")
|
||||||
|
svg = render_grade_widget(grade, theme, settings=ws)
|
||||||
|
except Exception:
|
||||||
|
log.exception("profile widget render failed for %s", username)
|
||||||
|
return _placeholder_response("building", username, theme=theme)
|
||||||
|
finally:
|
||||||
|
_GENERATE_SEMAPHORE.release()
|
||||||
|
|
||||||
|
db.touch_last_requested(username)
|
||||||
|
return Response(
|
||||||
|
svg,
|
||||||
|
mimetype="image/svg+xml",
|
||||||
|
headers={
|
||||||
|
"X-Widget-Status": "ready",
|
||||||
|
"Cache-Control": "public, max-age=300",
|
||||||
|
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/settings", methods=["GET"])
|
@app.route("/api/<username>/settings", methods=["GET"])
|
||||||
@rate_limited("read")
|
@rate_limited("read")
|
||||||
def get_settings(username: str):
|
def get_settings(username: str):
|
||||||
|
|||||||
@@ -32,6 +32,58 @@ def test_health(client):
|
|||||||
assert r.get_json()["service"] == "generator"
|
assert r.get_json()["service"] == "generator"
|
||||||
|
|
||||||
|
|
||||||
|
def test_root_with_username_param_force_renders_grade_widget(client, monkeypatch):
|
||||||
|
"""`GET /?username=<u>` auto-enrolls and returns just the grade widget SVG,
|
||||||
|
force-generated from fresh fetcher data. No composite, no other widgets."""
|
||||||
|
from src.models import GradeData
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"src.api.fetcher_client.get_data",
|
||||||
|
lambda u: {"data": {"user": {}, "repos": [], "events": []}, "payload_hash": "h"},
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"src.api.processor.compute_grade",
|
||||||
|
lambda *a, **kw: GradeData(grade="A", score=88.0, stats={}, tags=[]),
|
||||||
|
)
|
||||||
|
monkeypatch.setattr("src.api.render_grade_widget", lambda *a, **kw: "<svg id='grade'/>")
|
||||||
|
r = client.get("/?username=alice")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.mimetype == "image/svg+xml"
|
||||||
|
assert r.headers["X-Widget-Status"] == "ready"
|
||||||
|
assert dbmod.get_settings("alice") is not None
|
||||||
|
body = r.data.decode()
|
||||||
|
assert "<svg" in body
|
||||||
|
assert "composite" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_with_username_param_also_works(client, monkeypatch):
|
||||||
|
"""Same shortcut is available at `/api/?username=<u>` so the /api prefix
|
||||||
|
stays consistent for callers that expect it."""
|
||||||
|
from src.models import GradeData
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"src.api.fetcher_client.get_data",
|
||||||
|
lambda u: {"data": {"user": {}, "repos": [], "events": []}, "payload_hash": "h"},
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"src.api.processor.compute_grade",
|
||||||
|
lambda *a, **kw: GradeData(grade="A", score=88.0, stats={}, tags=[]),
|
||||||
|
)
|
||||||
|
monkeypatch.setattr("src.api.render_grade_widget", lambda *a, **kw: "<svg id='grade'/>")
|
||||||
|
r = client.get("/api/?username=bob")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.mimetype == "image/svg+xml"
|
||||||
|
assert r.headers["X-Widget-Status"] == "ready"
|
||||||
|
|
||||||
|
|
||||||
|
def test_root_without_username_serves_spa(client):
|
||||||
|
"""Plain `/` still returns the SPA (or the 'frontend not built' fallback
|
||||||
|
in test, where static assets aren't bundled)."""
|
||||||
|
r = client.get("/")
|
||||||
|
# Either 200 (static built) or 503 (not built) — the important thing is we
|
||||||
|
# don't accidentally route to the grade-widget handler.
|
||||||
|
assert r.status_code in (200, 503)
|
||||||
|
assert r.mimetype != "image/svg+xml"
|
||||||
|
|
||||||
|
|
||||||
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client):
|
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client):
|
||||||
"""The SVG endpoint is for README embeds — enrollment is frontend-driven
|
"""The SVG endpoint is for README embeds — enrollment is frontend-driven
|
||||||
through /data or /api/enroll, so GET /api/<u> does not auto-enroll."""
|
through /data or /api/enroll, so GET /api/<u> does not auto-enroll."""
|
||||||
|
|||||||
Reference in New Issue
Block a user