File size: 2,292 Bytes
e92417d
 
 
8893529
e92417d
8893529
e92417d
363bda3
e92417d
 
 
 
363bda3
e92417d
 
 
 
8893529
e92417d
 
 
 
 
 
 
363bda3
8893529
 
 
 
 
 
e92417d
8893529
 
 
 
 
e92417d
 
 
 
8893529
 
 
 
 
 
 
 
e87131b
 
 
 
e92417d
e87131b
e92417d
 
 
 
 
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
"""GET/POST comments for an article."""
from typing import Optional

from fastapi import APIRouter, Header, HTTPException

from auth import get_author_from_bearer
from database import supabase
from models import Comment

router = APIRouter(tags=["comments"])


@router.get("/articles/{article_id}/comments", response_model=list[Comment])
def list_comments(article_id: str):
    """List comments for an article, oldest first."""
    result = (
        supabase.table("comments")
        .select("id, article_id, body, author, created_at")
        .eq("article_id", article_id)
        .order("created_at", desc=False)
        .execute()
    )
    return result.data


@router.post("/articles/{article_id}/comments", response_model=Comment, status_code=201)
def create_comment(
    article_id: str,
    payload: dict,
    authorization: Optional[str] = Header(None),
):
    """Add a comment. Requires an account: sign in with Hugging Face (send author in body) or with app account (Authorization: Bearer <token>)."""
    body = (payload.get("body") or "").strip()
    author = get_author_from_bearer(authorization)
    if not author:
        author = (payload.get("author") or "").strip() or None
        if payload.get("username"):
            author = author or (payload.get("username") or "").strip()
    if not body:
        raise HTTPException(status_code=400, detail="body required")
    if len(body) > 2000:
        raise HTTPException(status_code=400, detail="body max 2000 characters")
    if not author:
        raise HTTPException(
            status_code=401,
            detail="Sign in to comment. Use Hugging Face (when on HF) or create an account / sign in.",
        )
    user_id = (payload.get("user_id") or "").strip() or None
    avatar_url = (payload.get("avatar_url") or "").strip() or None
    row = {"article_id": article_id, "body": body, "author": author}
    if user_id:
        row["user_id"] = user_id
    if avatar_url:
        row["avatar_url"] = avatar_url
    try:
        result = supabase.table("comments").insert(row).execute()
        if not result.data:
            raise HTTPException(status_code=500, detail="Failed to insert comment")
        return result.data[0]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))