|
| 1 | +import { type NextRequest, NextResponse } from "next/server"; |
| 2 | +import { sql } from "@vercel/postgres"; |
| 3 | +import { verifySession } from "@/lib/auth/verify-session"; |
| 4 | + |
| 5 | +const DEFAULT_LIMIT = 20; |
| 6 | +const MAX_LIMIT = 100; |
| 7 | + |
| 8 | +export async function GET(request: NextRequest) { |
| 9 | + const session = await verifySession(request); |
| 10 | + if (!session.ok) return session.response; |
| 11 | + |
| 12 | + try { |
| 13 | + // Respect privacy setting |
| 14 | + const { rows: privacyRows } = await sql` |
| 15 | + SELECT show_watch_history FROM user_privacy_settings WHERE user_id = ${session.userId} LIMIT 1 |
| 16 | + `; |
| 17 | + if (privacyRows[0]?.show_watch_history === false) { |
| 18 | + return NextResponse.json( |
| 19 | + { error: "Watch history is disabled for this account" }, |
| 20 | + { status: 403 } |
| 21 | + ); |
| 22 | + } |
| 23 | + |
| 24 | + const params = request.nextUrl.searchParams; |
| 25 | + const cursor = params.get("cursor") ?? null; |
| 26 | + const limitRaw = Number(params.get("limit") ?? DEFAULT_LIMIT); |
| 27 | + const limit = Math.min(Math.max(1, limitRaw), MAX_LIMIT); |
| 28 | + |
| 29 | + const { rows } = cursor |
| 30 | + ? await sql` |
| 31 | + SELECT |
| 32 | + wh.id, |
| 33 | + wh.stream_id, |
| 34 | + u.username AS creator_username, |
| 35 | + wh.watched_at, |
| 36 | + wh.watch_duration_seconds, |
| 37 | + s.thumbnail_url |
| 38 | + FROM watch_history wh |
| 39 | + JOIN streams s ON s.id = wh.stream_id |
| 40 | + JOIN users u ON u.id = s.creator_id |
| 41 | + WHERE wh.user_id = ${session.userId} |
| 42 | + AND wh.watched_at < (SELECT watched_at FROM watch_history WHERE id = ${cursor} LIMIT 1) |
| 43 | + ORDER BY wh.watched_at DESC |
| 44 | + LIMIT ${limit + 1} |
| 45 | + ` |
| 46 | + : await sql` |
| 47 | + SELECT |
| 48 | + wh.id, |
| 49 | + wh.stream_id, |
| 50 | + u.username AS creator_username, |
| 51 | + wh.watched_at, |
| 52 | + wh.watch_duration_seconds, |
| 53 | + s.thumbnail_url |
| 54 | + FROM watch_history wh |
| 55 | + JOIN streams s ON s.id = wh.stream_id |
| 56 | + JOIN users u ON u.id = s.creator_id |
| 57 | + WHERE wh.user_id = ${session.userId} |
| 58 | + ORDER BY wh.watched_at DESC |
| 59 | + LIMIT ${limit + 1} |
| 60 | + `; |
| 61 | + |
| 62 | + const hasMore = rows.length > limit; |
| 63 | + const entries = rows.slice(0, limit); |
| 64 | + |
| 65 | + return NextResponse.json({ |
| 66 | + entries, |
| 67 | + nextCursor: hasMore ? entries[entries.length - 1].id : null, |
| 68 | + }); |
| 69 | + } catch (error) { |
| 70 | + console.error("[routes-f viewer/history GET]", error); |
| 71 | + return NextResponse.json({ error: "Failed to fetch watch history" }, { status: 500 }); |
| 72 | + } |
| 73 | +} |
0 commit comments