import logging
from datetime import datetime, timedelta
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from devplacepy.database import get_table, get_daily_topic
from devplacepy.templating import templates
from devplacepy.utils import get_current_user, require_user, time_ago
logger = logging.getLogger(__name__)
router = APIRouter()
def get_feed_posts(user, tab: str = "all", topic: str = None):
posts_table = get_table("posts")
users_table = get_table("users")
query = "1=1"
params = {}
if topic:
query += " AND topic = :topic"
params["topic"] = topic
if tab == "following":
follows = get_table("follows")
following = [f["following_uid"] for f in follows.find(follower_uid=user["uid"])]
if following:
placeholders = ",".join(f":uid_{i}" for i in range(len(following)))
query += f" AND user_uid IN ({placeholders})"
for i, uid in enumerate(following):
params[f"uid_{i}"] = uid
else:
return []
order = "created_at DESC"
if tab == "trending":
order = "stars DESC, created_at DESC"
posts = list(posts_table.find(**params, _limit=50))
posts.sort(key=lambda p: p.get("created_at", ""), reverse=True)
if tab == "trending":
posts.sort(key=lambda p: int(p.get("stars", 0)), reverse=True)
result = []
for post in posts:
author = users_table.find_one(uid=post["user_uid"])
comment_count = len(list(get_table("comments").find(post_uid=post["uid"])))
result.append({
"post": post,
"author": author,
"time_ago": time_ago(post["created_at"]),
"comment_count": comment_count,
})
return result
@router.get("", response_class=HTMLResponse)
async def feed_page(request: Request, tab: str = "all", topic: str = None):
user = require_user(request)
posts = get_feed_posts(user, tab, topic)
users_table = get_table("users")
total_members = len(list(users_table.all()))
posts_table = get_table("posts")
today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0).isoformat()
posts_today = len(list(posts_table.find(created_at={">=": today_start})))
total_projects = len(list(get_table("projects").all()))
top_authors = list(users_table.find(order_by=["-stars"], _limit=5))
daily_topic = get_daily_topic()
return templates.TemplateResponse("feed.html", {
"request": request,
"user": user,
"posts": posts,
"current_tab": tab,
"current_topic": topic,
"total_members": total_members,
"posts_today": posts_today,
"total_projects": total_projects,
"top_authors": top_authors,
"daily_topic": daily_topic,
})