From b85c780c3d60adc5dafda372558026484da9b2a2 Mon Sep 17 00:00:00 2001 From: Alzer Del Zeyger <75466035+Dx-Alz-xD@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:01:49 +0530 Subject: [PATCH 1/2] feat(papers): count and show views and downloads of each paper each paper now stores how often it was viewed and downloaded. opening the paper page or the card preview counts a view, and a download that worked counts a download, from the card, the viewer or the zip. one visitor counts once an hour per paper, and the counts show on the cards and under the paper title --- src/app/api/paper-counts/route.ts | 34 +++++++++++++++++++ src/app/paper/[id]/page.tsx | 11 +++++- src/components/Card.tsx | 12 ++++++- src/components/PaperCountsLine.tsx | 37 ++++++++++++++++++++ src/components/newPdfViewer.tsx | 8 +++-- src/context/filterContext.tsx | 4 +++ src/db/papers.ts | 2 ++ src/interface.ts | 9 +++++ src/lib/services/paper-counts.ts | 54 ++++++++++++++++++++++++++++++ src/lib/utils/download.ts | 4 ++- src/lib/utils/paper-counts.ts | 44 ++++++++++++++++++++++++ src/lib/utils/rate-limiter.ts | 2 +- 12 files changed, 215 insertions(+), 6 deletions(-) create mode 100644 src/app/api/paper-counts/route.ts create mode 100644 src/components/PaperCountsLine.tsx create mode 100644 src/lib/services/paper-counts.ts create mode 100644 src/lib/utils/paper-counts.ts diff --git a/src/app/api/paper-counts/route.ts b/src/app/api/paper-counts/route.ts new file mode 100644 index 0000000..1672992 --- /dev/null +++ b/src/app/api/paper-counts/route.ts @@ -0,0 +1,34 @@ +import { Types } from "mongoose"; +import { z } from "zod"; +import { countPaperActivity } from "@/lib/services/paper-counts"; +import { getClientIp } from "@/lib/utils/rate-limiter"; +import { success, failure } from "@/lib/utils/response"; + +export const dynamic = "force-dynamic"; + +const paperActivity = z.object({ + kind: z.enum(["view", "download"]), + paperIds: z + .array(z.string().refine((id) => Types.ObjectId.isValid(id))) + .min(1) + .max(100), +}); + +export async function POST(req: Request) { + try { + const body: unknown = await req.json().catch(() => null); + const activity = paperActivity.safeParse(body); + + if (!activity.success) { + return failure("send a kind of view or download and up to 100 paper ids", 400); + } + + const { kind, paperIds } = activity.data; + const counts = await countPaperActivity(kind, [...new Set(paperIds)], getClientIp(req)); + + return success(counts); + } catch (error) { + console.error(error); + return failure("could not update the paper counts", 500); + } +} diff --git a/src/app/paper/[id]/page.tsx b/src/app/paper/[id]/page.tsx index a000208..18c6f28 100644 --- a/src/app/paper/[id]/page.tsx +++ b/src/app/paper/[id]/page.tsx @@ -8,6 +8,7 @@ import { type Metadata } from "next"; import { redirect } from "next/navigation"; import { PaperProvider } from "@/context/PaperContext"; import PDFViewer from "@/components/newPdfViewer"; +import PaperCountsLine from "@/components/PaperCountsLine"; export async function generateMetadata({ params, @@ -159,11 +160,19 @@ const PaperPage = async ({ params }: { params: { id: string } }) => { ) : ( <> -

+

{paper.subject} {paper.exam} {paper.slot} {paper.year}

+
+ +
{ downloadInProgress.current = true; setIsDownloading(true); try { - await downloadFile(getSecureUrl(paper.file_url), generateFileName(paper)); + const downloaded = await downloadFile(getSecureUrl(paper.file_url), generateFileName(paper)); + if (downloaded) void sendPaperActivity("download", [paper._id]); } finally { downloadInProgress.current = false; setIsDownloading(false); @@ -112,6 +115,12 @@ const Card = ({ paper, onSelect, isSelected, isShow=true }: CardProps) => { {paper.semester} {paper.school && {paper.school}} + @@ -121,6 +130,7 @@ const Card = ({ paper, onSelect, isSelected, isShow=true }: CardProps) => { onClick={(e) => { e.stopPropagation(); setPreviewOpen(true); + void sendPaperActivity("view", [paper._id]); }} /> diff --git a/src/components/PaperCountsLine.tsx b/src/components/PaperCountsLine.tsx new file mode 100644 index 0000000..d8f6906 --- /dev/null +++ b/src/components/PaperCountsLine.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useEffect } from "react"; +import { cn } from "@/lib/utils"; +import { describeCount, sendPaperActivity, usePaperCounts } from "@/lib/utils/paper-counts"; + +const viewedOnThisPage = new Set(); + +interface PaperCountsLineProps { + paperId: string; + views?: number; + downloads?: number; + countView?: boolean; + className?: string; +} + +export default function PaperCountsLine({ + paperId, + views = 0, + downloads = 0, + countView = false, + className, +}: PaperCountsLineProps) { + const counts = usePaperCounts(paperId, { views, downloads }); + + useEffect(() => { + if (!countView || viewedOnThisPage.has(paperId)) return; + viewedOnThisPage.add(paperId); + void sendPaperActivity("view", [paperId]); + }, [countView, paperId]); + + return ( + + {describeCount(counts.views, "view")} ยท {describeCount(counts.downloads, "download")} + + ); +} diff --git a/src/components/newPdfViewer.tsx b/src/components/newPdfViewer.tsx index fd8560e..5237e51 100644 --- a/src/components/newPdfViewer.tsx +++ b/src/components/newPdfViewer.tsx @@ -17,6 +17,8 @@ import { Button } from "./ui/button"; import ShareButton from "./ShareButton"; import ReportButton from "./ReportButton"; import { useTheme } from "next-themes"; +import { sendPaperActivity } from "@/lib/utils/paper-counts"; +import { usePaper } from "@/context/PaperContext"; interface ControlProps { documentId: string; @@ -465,6 +467,7 @@ export default function PDFViewer({ onReadingModeChange, }: PdfViewerProps) { const { engine, isLoading } = usePdfiumEngine(); + const { paperId } = usePaper(); const { isMobile, isSmall } = useBreakpoint(); const { resolvedTheme } = useTheme(); const [isFullscreen, setIsFullscreen] = useState(false); @@ -505,12 +508,13 @@ export default function PDFViewer({ posthog.capture("paper_downloaded", { paper_name: name, }); - await downloadFile(url, `${name}.pdf`); + const downloaded = await downloadFile(url, `${name}.pdf`); + if (downloaded) void sendPaperActivity("download", [paperId]); } finally { downloadInProgress.current = false; setIsDownloading(false); } - }, [url, name]); + }, [url, name, paperId]); const toggleFullscreen = useCallback(() => { if (!document.fullscreenElement) { diff --git a/src/context/filterContext.tsx b/src/context/filterContext.tsx index e4df4ad..73824a3 100644 --- a/src/context/filterContext.tsx +++ b/src/context/filterContext.tsx @@ -19,6 +19,7 @@ import posthog from "posthog-js"; import JSZip from "jszip"; import { toast } from "react-hot-toast"; import { getSecureUrl, generateFileName } from "@/lib/utils/download"; +import { sendPaperActivity } from "@/lib/utils/paper-counts"; interface FilterState { selectedExams: string[]; @@ -164,6 +165,7 @@ export const FilterProvider: React.FC = ({ ).map((id) => selectedPapers.find((paper) => paper._id === id)) as IPaper[]; let failedCount = 0; + const zippedPaperIds: string[] = []; // Different papers can share a generated name (e.g. same subject/exam/slot/year // from different campuses). JSZip overwrites entries with the same path, so // append " (1)", " (2)", ... to keep every paper in the zip. @@ -188,6 +190,7 @@ export const FilterProvider: React.FC = ({ const blob = await response.blob(); const filename = getUniqueName(generateFileName(paper)); zip.file(filename, blob); + zippedPaperIds.push(paper._id); } catch (err) { failedCount += 1; console.error(`Failed to fetch ${paper.file_url}`, err); @@ -223,6 +226,7 @@ export const FilterProvider: React.FC = ({ a.click(); a.remove(); URL.revokeObjectURL(url); + void sendPaperActivity("download", zippedPaperIds); posthog.capture("papers_bulk_downloaded", { download_count: uniquePapers.length - failedCount, diff --git a/src/db/papers.ts b/src/db/papers.ts index 3d1fb03..6b2016c 100644 --- a/src/db/papers.ts +++ b/src/db/papers.ts @@ -78,6 +78,8 @@ const paperSchema = new Schema({ enum: ["SCOPE","SITE","SENSE","SMEC","SCE","SELECT","SAS","SSL","VITBS","SBST","SCORE","SCHEME","SHINE","V-SIGN","V-SMART","V-SPARC","VAIAL","HOT"], }, answer_key_included: { type: Boolean, default: false }, + views: { type: Number, default: 0 }, + downloads: { type: Number, default: 0 }, }); export const PaperAdmin: Model = diff --git a/src/interface.ts b/src/interface.ts index 03b3c93..895a393 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -18,6 +18,8 @@ export interface PaperResponse { slot: string; exam: string; school?: string; + views?: number; + downloads?: number; } export interface IAdminPaper { @@ -122,6 +124,13 @@ export interface IPaper { subject: string; year: string; answer_key_included?: boolean; + views?: number; + downloads?: number; +} + +export interface PaperCounts { + views: number; + downloads: number; } export interface Filters { diff --git a/src/lib/services/paper-counts.ts b/src/lib/services/paper-counts.ts new file mode 100644 index 0000000..4ffb68b --- /dev/null +++ b/src/lib/services/paper-counts.ts @@ -0,0 +1,54 @@ +import { Ratelimit } from "@upstash/ratelimit"; +import Paper from "@/db/papers"; +import { type PaperCounts } from "@/interface"; +import { connectToDatabase } from "@/lib/database/mongoose"; +import { redis } from "@/lib/utils/redis"; + +export type PaperActivity = "view" | "download"; + +const countedField = { view: "views", download: "downloads" } as const; + +const upstashConfigured = Boolean(process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN); + +const oncePerHour = + redis && upstashConfigured + ? new Ratelimit({ redis, limiter: Ratelimit.fixedWindow(1, "1 h"), prefix: "paper-counts" }) + : null; + +async function firstThisHour(key: string) { + if (!oncePerHour) return true; + const { success } = await oncePerHour.limit(key); + return success; +} + +export async function countPaperActivity( + kind: PaperActivity, + paperIds: string[], + visitor: string, +): Promise> { + await connectToDatabase(); + + const firstTimes = await Promise.all( + paperIds.map((paperId) => firstThisHour(`${visitor}::${kind}::${paperId}`)), + ); + const newlyCounted = paperIds.filter((_, index) => firstTimes[index]); + + if (newlyCounted.length > 0) { + await Paper.updateMany( + { _id: { $in: newlyCounted } }, + { $inc: { [countedField[kind]]: 1 } }, + ); + } + + const papers = await Paper.find( + { _id: { $in: paperIds } }, + { views: 1, downloads: 1 }, + ).lean(); + + return Object.fromEntries( + papers.map((paper) => [ + String(paper._id), + { views: paper.views ?? 0, downloads: paper.downloads ?? 0 }, + ]), + ); +} diff --git a/src/lib/utils/download.ts b/src/lib/utils/download.ts index a623503..3170b9f 100644 --- a/src/lib/utils/download.ts +++ b/src/lib/utils/download.ts @@ -14,7 +14,7 @@ export const generateFileName = (paper: IPaper): string => { export const downloadFile = async ( url: string, filename: string, -): Promise => { +): Promise => { try { const response = await axios.get(url, { responseType: "blob" }); const blob = new Blob([response.data]); @@ -23,6 +23,7 @@ export const downloadFile = async ( link.download = filename; link.click(); window.URL.revokeObjectURL(link.href); + return true; } catch (error) { console.error("Download failed (File missing or network error):", error); if (typeof navigator !== "undefined" && !navigator.onLine) { @@ -30,5 +31,6 @@ export const downloadFile = async ( } else { toast.error("This paper is no longer available on the server."); } + return false; } }; \ No newline at end of file diff --git a/src/lib/utils/paper-counts.ts b/src/lib/utils/paper-counts.ts new file mode 100644 index 0000000..cde48a5 --- /dev/null +++ b/src/lib/utils/paper-counts.ts @@ -0,0 +1,44 @@ +import axios from "axios"; +import { useEffect, useState } from "react"; +import { type ApiResponse, type PaperCounts } from "@/interface"; +import { chunkArray } from "@/lib/utils/array"; + +const countsChanged = "paperCountsChanged"; + +export async function sendPaperActivity(kind: "view" | "download", paperIds: string[]) { + for (const batch of chunkArray(paperIds, 100)) { + try { + const response = await axios.post>>( + "/api/paper-counts", + { kind, paperIds: batch }, + ); + const counts = response.data.data; + if (counts) { + window.dispatchEvent(new CustomEvent(countsChanged, { detail: counts })); + } + } catch { + return; + } + } +} + +export function usePaperCounts(paperId: string, initial: PaperCounts) { + const [counts, setCounts] = useState(initial); + + useEffect(() => { + const takeFresh = (event: Event) => { + const fresh = (event as CustomEvent>).detail[paperId]; + if (fresh) setCounts(fresh); + }; + window.addEventListener(countsChanged, takeFresh); + return () => window.removeEventListener(countsChanged, takeFresh); + }, [paperId]); + + return counts; +} + +const compact = new Intl.NumberFormat("en", { notation: "compact" }); + +export function describeCount(count: number, word: string) { + return `${compact.format(count)} ${word}${count === 1 ? "" : "s"}`; +} diff --git a/src/lib/utils/rate-limiter.ts b/src/lib/utils/rate-limiter.ts index 0d3f260..b5f6f16 100644 --- a/src/lib/utils/rate-limiter.ts +++ b/src/lib/utils/rate-limiter.ts @@ -2,7 +2,7 @@ import { redis } from "@/lib/utils/redis"; import { Ratelimit } from "@upstash/ratelimit"; import { CustomError } from "./error"; -function getClientIp(req: Request & { ip?: string}): string { +export function getClientIp(req: Request & { ip?: string}): string { const xff = req.headers.get("x-forwarded-for"); if (typeof xff === "string" && xff.length > 0) { return xff.split(",")[0]?.trim()??""; From c8dff8d79651095be0e66e10e0a55ae59df23dee Mon Sep 17 00:00:00 2001 From: Alzer Del Zeyger <75466035+Dx-Alz-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:43:36 +0530 Subject: [PATCH 2/2] fix(papers): rate limit the counts endpoint and count visitors behind one ip /api/paper-counts now goes through the middleware like the other routes that use upstash, at 120 requests a minute per ip the browser keeps a random visitor id in localStorage and sends it with each count, so people on the same campus wifi are counted separately instead of as one ip. each visitor counts once an hour per paper, and one ip can add at most 50 views or downloads of a paper an hour, so made up visitor ids cannot inflate a count. a request without a visitor id is counted once an hour per ip, as before --- src/app/api/paper-counts/route.ts | 10 +++++++-- src/lib/services/paper-counts.ts | 36 +++++++++++++++++++++---------- src/lib/utils/paper-counts.ts | 17 ++++++++++++++- src/lib/utils/ratelimit.ts | 2 ++ src/middleware.ts | 12 +++++++++-- 5 files changed, 61 insertions(+), 16 deletions(-) diff --git a/src/app/api/paper-counts/route.ts b/src/app/api/paper-counts/route.ts index 1672992..f4ebff6 100644 --- a/src/app/api/paper-counts/route.ts +++ b/src/app/api/paper-counts/route.ts @@ -12,6 +12,7 @@ const paperActivity = z.object({ .array(z.string().refine((id) => Types.ObjectId.isValid(id))) .min(1) .max(100), + visitorId: z.string().uuid().optional(), }); export async function POST(req: Request) { @@ -23,8 +24,13 @@ export async function POST(req: Request) { return failure("send a kind of view or download and up to 100 paper ids", 400); } - const { kind, paperIds } = activity.data; - const counts = await countPaperActivity(kind, [...new Set(paperIds)], getClientIp(req)); + const { kind, paperIds, visitorId } = activity.data; + const counts = await countPaperActivity( + kind, + [...new Set(paperIds)], + getClientIp(req), + visitorId, + ); return success(counts); } catch (error) { diff --git a/src/lib/services/paper-counts.ts b/src/lib/services/paper-counts.ts index 4ffb68b..45924c1 100644 --- a/src/lib/services/paper-counts.ts +++ b/src/lib/services/paper-counts.ts @@ -8,28 +8,42 @@ export type PaperActivity = "view" | "download"; const countedField = { view: "views", download: "downloads" } as const; -const upstashConfigured = Boolean(process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN); +const visitorsPerAddress = 50; -const oncePerHour = - redis && upstashConfigured - ? new Ratelimit({ redis, limiter: Ratelimit.fixedWindow(1, "1 h"), prefix: "paper-counts" }) - : null; +const oncePerVisitor = redis + ? new Ratelimit({ redis, limiter: Ratelimit.fixedWindow(1, "1 h"), prefix: "paper-counts" }) + : null; -async function firstThisHour(key: string) { - if (!oncePerHour) return true; - const { success } = await oncePerHour.limit(key); - return success; +const capPerAddress = redis + ? new Ratelimit({ + redis, + limiter: Ratelimit.fixedWindow(visitorsPerAddress, "1 h"), + prefix: "paper-counts-address", + }) + : null; + +async function shouldCount(kind: PaperActivity, paperId: string, ip: string, visitorId?: string) { + if (!oncePerVisitor || !capPerAddress) return true; + + const visitor = visitorId ? `${ip}::${visitorId}` : ip; + const firstForVisitor = await oncePerVisitor.limit(`${visitor}::${kind}::${paperId}`); + if (!firstForVisitor.success) return false; + if (!visitorId) return true; + + const underCap = await capPerAddress.limit(`${ip}::${kind}::${paperId}`); + return underCap.success; } export async function countPaperActivity( kind: PaperActivity, paperIds: string[], - visitor: string, + ip: string, + visitorId?: string, ): Promise> { await connectToDatabase(); const firstTimes = await Promise.all( - paperIds.map((paperId) => firstThisHour(`${visitor}::${kind}::${paperId}`)), + paperIds.map((paperId) => shouldCount(kind, paperId, ip, visitorId)), ); const newlyCounted = paperIds.filter((_, index) => firstTimes[index]); diff --git a/src/lib/utils/paper-counts.ts b/src/lib/utils/paper-counts.ts index cde48a5..f8ce38a 100644 --- a/src/lib/utils/paper-counts.ts +++ b/src/lib/utils/paper-counts.ts @@ -4,13 +4,28 @@ import { type ApiResponse, type PaperCounts } from "@/interface"; import { chunkArray } from "@/lib/utils/array"; const countsChanged = "paperCountsChanged"; +const visitorIdKey = "paperCountsVisitorId"; +const uuidShape = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function getVisitorId() { + try { + const saved = window.localStorage.getItem(visitorIdKey); + if (saved && uuidShape.test(saved)) return saved; + const fresh = window.crypto.randomUUID(); + window.localStorage.setItem(visitorIdKey, fresh); + return fresh; + } catch { + return undefined; + } +} export async function sendPaperActivity(kind: "view" | "download", paperIds: string[]) { + const visitorId = getVisitorId(); for (const batch of chunkArray(paperIds, 100)) { try { const response = await axios.post>>( "/api/paper-counts", - { kind, paperIds: batch }, + { kind, paperIds: batch, visitorId }, ); const counts = response.data.data; if (counts) { diff --git a/src/lib/utils/ratelimit.ts b/src/lib/utils/ratelimit.ts index 183daf8..abb4a89 100644 --- a/src/lib/utils/ratelimit.ts +++ b/src/lib/utils/ratelimit.ts @@ -14,3 +14,5 @@ export const aiUploadRatelimit = allow(5, "900 s"); export const paperRequestRatelimit = allow(5, "900 s"); export const subscribeRatelimit = allow(3, "1 h"); + +export const paperCountsRatelimit = allow(120, "60 s"); diff --git a/src/middleware.ts b/src/middleware.ts index 5bf8cdb..3ff6e46 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,17 +1,18 @@ import { type NextRequest, NextResponse } from "next/server"; import { aiUploadRatelimit, + paperCountsRatelimit, paperRequestRatelimit, subscribeRatelimit, } from "./lib/utils/ratelimit"; import { failure } from "@/lib/utils/response" export const config = { - matcher: ["/api/upload", "/api/request", "/api/subscribe"], + matcher: ["/api/upload", "/api/request", "/api/subscribe", "/api/paper-counts"], }; export default async function middleware(request: NextRequest) { - if (!aiUploadRatelimit || !paperRequestRatelimit || !subscribeRatelimit) { + if (!aiUploadRatelimit || !paperRequestRatelimit || !subscribeRatelimit || !paperCountsRatelimit) { if (process.env.NODE_ENV === "production") { return failure("rate limiting is not configured", 503); } @@ -42,6 +43,13 @@ export default async function middleware(request: NextRequest) { } } + if (pathname === "/api/paper-counts") { + const { success } = await paperCountsRatelimit.limit(ip); + if (!success) { + return failure("too many view and download updates, try again in a minute", 429); + } + } + return NextResponse.next(); }