Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Add "report" button to document viewer to report abuse (#997)
RajuGangitla9af1596a5e39
diff --git a/components/NotionPage.tsx b/components/NotionPage.tsxindex aed3f4bf..976a158c 100644--- a/components/NotionPage.tsx+++ b/components/NotionPage.tsx@@ -267,6 +267,9 @@ export const NotionPage = ({setDocumentData={setDocumentData}type="notion"isPreview={isPreview}+ linkId={linkId}+ documentId={documentId}+ viewId={viewId}/><Portal containerId="view-breadcrump-portal">@@ -321,16 +324,16 @@ export const NotionPage = ({className: string;href: any;children:- | string- | number- | boolean- | React.ReactElement<- any,- string | React.JSXElementConstructor<any>- >- | React.ReactPortal- | null- | undefined;+ | string+ | number+ | boolean+ | React.ReactElement<+ any,+ string | React.JSXElementConstructor<any>+ >+ | React.ReactPortal+ | null+ | undefined;}) => {return (<divdiff --git a/components/ui/radio-group.tsx b/components/ui/radio-group.tsxnew file mode 100644index 00000000..43b43b48--- /dev/null+++ b/components/ui/radio-group.tsx@@ -0,0 +1,42 @@+import * as React from "react"+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"+import { Circle } from "lucide-react"++import { cn } from "@/lib/utils"++const RadioGroup = React.forwardRef<+ React.ElementRef<typeof RadioGroupPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>+>(({ className, ...props }, ref) => {+ return (+ <RadioGroupPrimitive.Root+ className={cn("grid gap-2", className)}+ {...props}+ ref={ref}+ />+ )+})+RadioGroup.displayName = RadioGroupPrimitive.Root.displayName++const RadioGroupItem = React.forwardRef<+ React.ElementRef<typeof RadioGroupPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>+>(({ className, ...props }, ref) => {+ return (+ <RadioGroupPrimitive.Item+ ref={ref}+ className={cn(+ "aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",+ className+ )}+ {...props}+ >+ <RadioGroupPrimitive.Indicator className="flex items-center justify-center">+ <Circle className="h-2.5 w-2.5 fill-current text-current" />+ </RadioGroupPrimitive.Indicator>+ </RadioGroupPrimitive.Item>+ )+})+RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName++export { RadioGroup, RadioGroupItem }diff --git a/components/ui/tooltip.tsx b/components/ui/tooltip.tsxindex 2f0bce95..916ae92d 100644--- a/components/ui/tooltip.tsx+++ b/components/ui/tooltip.tsx@@ -50,10 +50,12 @@ export const BadgeTooltip = ({export const ButtonTooltip = ({content,sideOffset = 0,+ className,children,}: {content: string;sideOffset?: number;+ className?: string;children: React.ReactNode;}) => {return (@@ -62,7 +64,7 @@ export const ButtonTooltip = ({<TooltipPortal><TooltipContentsideOffset={sideOffset}- className="bg-[#474e5a] px-2 py-1 text-white"+ className={cn("bg-[#474e5a] px-2 py-1 text-white", className)}><p>{content}</p></TooltipContent>diff --git a/components/view/PDFViewer.tsx b/components/view/PDFViewer.tsxindex 6759136d..730bd223 100644--- a/components/view/PDFViewer.tsx+++ b/components/view/PDFViewer.tsx@@ -169,6 +169,7 @@ export default function PDFViewer(props: any) {assistantEnabled={props.assistantEnabled}viewId={props.viewId}linkId={props.linkId}+ documentId={props.documentId}/><divhidden={loading}diff --git a/components/view/PagesViewer.tsx b/components/view/PagesViewer.tsxindex 04907f8d..e5e4f799 100644--- a/components/view/PagesViewer.tsx+++ b/components/view/PagesViewer.tsx@@ -258,6 +258,7 @@ export default function PagesViewer({brand={brand}viewId={viewId}linkId={linkId}+ documentId={documentId}documentName={documentName}embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}isDataroom={dataroomId ? true : false}@@ -312,9 +313,8 @@ export default function PagesViewer({return (<imgkey={index}- className={`mx-auto object-contain ${- pageNumber - 1 === index ? "block" : "hidden"- }`}+ className={`mx-auto object-contain ${pageNumber - 1 === index ? "block" : "hidden"+ }`}src={loadedImages[index]? page.file@@ -329,9 +329,8 @@ export default function PagesViewer({return (<Imagekey={index}- className={`mx-auto object-contain ${- pageNumber - 1 === index ? "block" : "hidden"- }`}+ className={`mx-auto object-contain ${pageNumber - 1 === index ? "block" : "hidden"+ }`}src={loadedImages[index] ? page.file : BlankImg}alt={`Page ${index + 1}`}priority={loadedImages[index] ? true : false}diff --git a/components/view/PagesViewerNew.tsx b/components/view/PagesViewerNew.tsxindex 2a755a71..a93b7498 100644--- a/components/view/PagesViewerNew.tsx+++ b/components/view/PagesViewerNew.tsx@@ -674,6 +674,7 @@ export default function PagesViewer({brand={brand}viewId={viewId}linkId={linkId}+ documentId={documentId}documentName={documentName}embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}isDataroom={dataroomId ? true : false}@@ -689,9 +690,8 @@ export default function PagesViewer({className={cn("relative flex items-center", isVertical && "h-dvh")}><div- className={`relative flex h-full w-full ${- isVertical ? "flex-col overflow-y-auto" : "flex-row"- }`}+ className={`relative flex h-full w-full ${isVertical ? "flex-col overflow-y-auto" : "flex-row"+ }`}ref={containerRef}><div@@ -699,181 +699,181 @@ export default function PagesViewer({onContextMenu={handleContextMenu}>{pageNumber <= numPagesWithAccountCreation &&- pages &&- loadedImages[pageNumber - 1]+ pages &&+ loadedImages[pageNumber - 1]? pages.map((page, index) => (- <TransformWrapper- key={index}- initialScale={scale}- initialPositionX={0}- initialPositionY={0}- disabled={isVertical && isMobile}- panning={{- lockAxisY: isVertical,- velocityDisabled: true,- wheelPanning: false,- }}- wheel={{ disabled: true }}- pinch={{ disabled: true }}- doubleClick={{ disabled: true }}- onZoom={(ref) => {- setScale(ref.state.scale);- }}- ref={(ref) => {- pinchRefs.current[index] = ref;- }}- customTransform={(x: number, y: number, scale: number) => {- // Keep the translateY value constant- if (isVertical) {- const transform = `translate(${x}px, ${index * y * -2}px) scale(${scale})`;- return transform;- }- const transform = `translate(${x}px, ${y}px) scale(${scale})`;+ <TransformWrapper+ key={index}+ initialScale={scale}+ initialPositionX={0}+ initialPositionY={0}+ disabled={isVertical && isMobile}+ panning={{+ lockAxisY: isVertical,+ velocityDisabled: true,+ wheelPanning: false,+ }}+ wheel={{ disabled: true }}+ pinch={{ disabled: true }}+ doubleClick={{ disabled: true }}+ onZoom={(ref) => {+ setScale(ref.state.scale);+ }}+ ref={(ref) => {+ pinchRefs.current[index] = ref;+ }}+ customTransform={(x: number, y: number, scale: number) => {+ // Keep the translateY value constant+ if (isVertical) {+ const transform = `translate(${x}px, ${index * y * -2}px) scale(${scale})`;return transform;- }}+ }+ const transform = `translate(${x}px, ${y}px) scale(${scale})`;+ return transform;+ }}+ >+ <TransformComponent+ wrapperClass={cn(+ !isVertical && "!h-full",+ isVertical+ ? "!overflow-x-clip !overflow-y-visible"+ : isMobile+ ? "!overflow-x-clip !overflow-y-clip"+ : "!overflow-x-visible !overflow-y-clip",+ )}+ contentClass={cn(+ !isVertical && "!h-full",+ isVertical && "!w-dvw !h-[calc(100dvh-64px)]",+ )}>- <TransformComponent- wrapperClass={cn(- !isVertical && "!h-full",- isVertical- ? "!overflow-x-clip !overflow-y-visible"- : isMobile- ? "!overflow-x-clip !overflow-y-clip"- : "!overflow-x-visible !overflow-y-clip",- )}- contentClass={cn(- !isVertical && "!h-full",- isVertical && "!w-dvw !h-[calc(100dvh-64px)]",+ <div+ key={index}+ className={cn(+ "relative my-auto w-full",+ pageNumber - 1 === index && !isVertical+ ? "block"+ : "hidden",+ isVertical && "flex justify-center",)}>- <div- key={index}+ <imgclassName={cn(- "relative my-auto w-full",- pageNumber - 1 === index && !isVertical- ? "block"- : "hidden",- isVertical && "flex justify-center",+ "!pointer-events-auto object-contain",+ isVertical && "h-auto",)}- >- <img- className={cn(- "!pointer-events-auto object-contain",- isVertical && "h-auto",- )}- style={{- maxHeight: "calc(100dvh - 64px)",- }}- // ref={(ref) => {- // imageRefs.current[index] = ref;- // }}- ref={(ref) => {- imageRefs.current[index] = ref;- if (ref) {- ref.onload = () =>- setImageDimensions((prev) => ({- ...prev,- [index]: {- width: ref.clientWidth,- height: ref.clientHeight,- },- }));- }+ style={{+ maxHeight: "calc(100dvh - 64px)",+ }}+ // ref={(ref) => {+ // imageRefs.current[index] = ref;+ // }}+ ref={(ref) => {+ imageRefs.current[index] = ref;+ if (ref) {+ ref.onload = () =>+ setImageDimensions((prev) => ({+ ...prev,+ [index]: {+ width: ref.clientWidth,+ height: ref.clientHeight,+ },+ }));+ }+ }}+ useMap={`#page-map-${index + 1}`}+ src={+ loadedImages[index]+ ? page.file+ : "https://www.papermark.io/_static/blank.gif"+ }+ alt={`Page ${index + 1}`}+ />++ {/* Add Watermark Component */}+ {watermarkConfig ? (+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress: ipAddress,}}- useMap={`#page-map-${index + 1}`}- src={- loadedImages[index]- ? page.file- : "https://www.papermark.io/_static/blank.gif"+ documentDimensions={+ imageDimensions[index] || { width: 0, height: 0 }}- alt={`Page ${index + 1}`}+ pageIndex={index}/>-- {/* Add Watermark Component */}- {watermarkConfig ? (- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,- }}- documentDimensions={- imageDimensions[index] || { width: 0, height: 0 }- }- pageIndex={index}- />- ) : null}-- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.includes(".gif"))- .map((link, index) => (- <area- key={index}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )}- href={link.href}- target="_blank"- rel="noopener noreferrer"- />- ))}- </map>- ) : null}-- {/** Automatically Render Overlays **/}- {page.pageLinks- ? page.pageLinks- .filter((link) => link.href.includes(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(+ ) : null}++ {page.pageLinks ? (+ <map name={`page-map-${index + 1}`}>+ {page.pageLinks+ .filter((link) => !link.href.includes(".gif"))+ .map((link, index) => (+ <area+ key={index}+ shape="rect"+ coords={scaleCoordinates(link.coords,getScaleFactor({naturalHeight: page.metadata.height,scaleFactor: page.metadata.scaleFactor,}),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href} // Assuming the href points to a GIF or overlay image- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none", // To ensure the overlay doesn't interfere with interaction- }}- />- );- })- : null}- </div>- </TransformComponent>- </TransformWrapper>- ))+ )}+ href={link.href}+ target="_blank"+ rel="noopener noreferrer"+ />+ ))}+ </map>+ ) : null}++ {/** Automatically Render Overlays **/}+ {page.pageLinks+ ? page.pageLinks+ .filter((link) => link.href.includes(".gif"))+ .map((link, linkIndex) => {+ const [x1, y1, x2, y2] = scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ }),+ )+ .split(",")+ .map(Number);++ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;++ return (+ <img+ key={`overlay-${index}-${linkIndex}`}+ src={link.href} // Assuming the href points to a GIF or overlay image+ alt={`Overlay ${index + 1}`}+ style={{+ position: "absolute",+ top: y1,+ left: x1,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ pointerEvents: "none", // To ensure the overlay doesn't interfere with interaction+ }}+ />+ );+ })+ : null}+ </div>+ </TransformComponent>+ </TransformWrapper>+ )): null}{enableQuestion &&- feedback &&- (isVertical || pageNumber === numPagesWithFeedback) ? (+ feedback &&+ (isVertical || pageNumber === numPagesWithFeedback) ? (<divclassName={cn("relative block h-dvh w-full")}style={{ height: "calc(100dvh - 64px)" }}@@ -889,8 +889,8 @@ export default function PagesViewer({) : null}{showStatsSlideWithAccountCreation &&- !isVertical &&- pageNumber === numPagesWithAccountCreation ? (+ !isVertical &&+ pageNumber === numPagesWithAccountCreation ? (<divclassName={cn("relative block h-dvh w-full")}style={{ height: "calc(100dvh - 64px)" }}diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex 84afad86..b078d133 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -8,6 +8,7 @@ import { Brand, DataroomBrand } from "@prisma/client";import {ArrowUpRight,Download,+ Flag,Minimize2Icon,Slash,ZoomInIcon,@@ -38,7 +39,9 @@ import {BreadcrumbSeparator,} from "../ui/breadcrumb";import { Button } from "../ui/button";+import { Separator } from "../ui/separator";import { TDocumentData } from "./dataroom/dataroom-view";+import ReportForm from "./report-form";export default function Nav({pageNumber,@@ -58,6 +61,7 @@ export default function Nav({isMobile,isPreview,hasWatermark,+ documentId,}: {pageNumber?: number;numPages?: number;@@ -76,6 +80,7 @@ export default function Nav({isMobile?: boolean;isPreview?: boolean;hasWatermark?: boolean;+ documentId?: string;}) {const downloadFile = async () => {if (isPreview) {@@ -243,6 +248,7 @@ export default function Nav({<Download className="h-5 w-5" /></Button>) : null}+{!(isVertical && isMobile) && documentRefs ? (<div className="flex gap-1"><Button@@ -303,6 +309,13 @@ export default function Nav({</span></div>) : null}+ {/* add a separator that doesn't use radix or shadcn */}+ <div className="h-6 w-px bg-gray-800" />+ <ReportForm+ linkId={linkId}+ documentId={documentId}+ viewId={viewId}+ /></div></div></div>diff --git a/components/view/report-form.tsx b/components/view/report-form.tsxnew file mode 100644index 00000000..b0b833c9--- /dev/null+++ b/components/view/report-form.tsx@@ -0,0 +1,156 @@+import { useState } from "react";++import { Flag } from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";++import { ButtonTooltip } from "../ui/tooltip";++export default function ReportForm({+ linkId,+ documentId,+ viewId,+}: {+ linkId: string | undefined;+ documentId: string | undefined;+ viewId: string | undefined;+}) {+ const [abuseType, setAbuseType] = useState("");+ const [loading, setLoading] = useState(false);+ const [open, setOpen] = useState(false);++ enum AbuseTypeEnum {+ "spam" = 1,+ "malware" = 2,+ "copyright" = 3,+ "harmful" = 4,+ "not-working" = 5,+ "other" = 6,+ }++ const handleSubmit = async () => {+ if (!abuseType) {+ toast.error("Please select an abuse type.");+ return;+ }++ const abuseTypeEnum =+ AbuseTypeEnum[abuseType as keyof typeof AbuseTypeEnum]; // Convert string to enum number++ setLoading(true);++ const response = await fetch("/api/report", {+ method: "POST",+ body: JSON.stringify({+ linkId: linkId,+ documentId: documentId,+ viewId: viewId,+ abuseType: abuseTypeEnum, // Send the numeric value of the abuse type+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const { message } = await response.json();+ toast.error(message);+ setOpen(false);+ setLoading(false);+ return;+ }++ toast.success("Report submitted successfully");+ setOpen(false);+ setLoading(false);+ };++ return (+ <>+ <Popover open={open} onOpenChange={setOpen}>+ <ButtonTooltip+ content="Report abuse"+ sideOffset={8}+ className="border-gray-800"+ >+ <PopoverTrigger asChild>+ <Button+ className="m-1 bg-gray-900 text-gray-300 hover:bg-gray-900/80 hover:text-gray-50"+ size="icon"+ title="Report abuse"+ >+ <Flag className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ </ButtonTooltip>+ <PopoverContent className="w-auto" align="end">+ <div className="flex max-w-xs flex-col gap-4">+ <div className="space-y-2">+ <h4 className="font-medium leading-none">Report an issue</h4>+ <p className="text-sm text-muted-foreground">+ See something inappropriate? We will take a look and, when+ appropriate, take action.+ </p>+ </div>+ <div className="flex flex-col space-y-4">+ <RadioGroup onValueChange={setAbuseType} className="grid gap-2">+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="spam" id="spam" />+ <Label htmlFor="spam" className="font-normal">+ Spam, Fraud, or Scam+ </Label>+ </div>+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="malware" id="malware" />+ <Label htmlFor="malware" className="font-normal">+ Malware or virus+ </Label>+ </div>+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="copyright" id="copyright" />+ <Label htmlFor="copyright" className="font-normal">+ Copyright violation+ </Label>+ </div>+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="harmful" id="harmful" />+ <Label htmlFor="harmful" className="font-normal">+ Harmful content+ </Label>+ </div>+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="not-working" id="not-working" />+ <Label htmlFor="not-working" className="font-normal">+ Content is not working properly+ </Label>+ </div>+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="other" id="other" />+ <Label htmlFor="other" className="font-normal">+ Other+ </Label>+ </div>+ </RadioGroup>+ <Button+ onClick={handleSubmit}+ disabled={!abuseType}+ loading={loading}+ size="sm"+ >+ Submit Report+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </>+ );+}diff --git a/components/view/viewer/advanced-excel-viewer.tsx b/components/view/viewer/advanced-excel-viewer.tsxindex 11177d4f..459ebde6 100644--- a/components/view/viewer/advanced-excel-viewer.tsx+++ b/components/view/viewer/advanced-excel-viewer.tsx@@ -113,12 +113,13 @@ export default function AdvancedExcelViewer({isPreview={isPreview}allowDownload={allowDownload}linkId={linkId}+ documentId={documentId}viewId={viewId}/><divstyle={{ height: "calc(100dvh - 64px)" }}className="mx-2 flex h-screen flex-col sm:mx-6 lg:mx-8"- // ref={containerRef}+ // ref={containerRef}><iframeclassName="h-full w-full"diff --git a/components/view/viewer/excel-viewer.tsx b/components/view/viewer/excel-viewer.tsxindex 04426d8c..addf26d1 100644--- a/components/view/viewer/excel-viewer.tsx+++ b/components/view/viewer/excel-viewer.tsx@@ -230,6 +230,7 @@ export default function ExcelViewer({isPreview={isPreview}allowDownload={allowDownload}linkId={linkId}+ documentId={documentId}viewId={viewId}/><div@@ -246,7 +247,7 @@ export default function ExcelViewer({className={cn("mb-1 rounded-none rounded-b-sm bg-[#f0f0f0] font-normal text-gray-950 hover:bg-gray-50",index === selectedSheetIndex &&- "bg-white font-medium text-black ring-1 ring-gray-500 hover:bg-white",+ "bg-white font-medium text-black ring-1 ring-gray-500 hover:bg-white",)}>{sheet.sheetName}diff --git a/components/view/viewer/image-viewer.tsx b/components/view/viewer/image-viewer.tsxindex 72d647e9..b3d212c4 100644--- a/components/view/viewer/image-viewer.tsx+++ b/components/view/viewer/image-viewer.tsx@@ -258,6 +258,7 @@ export default function ImageViewer({brand={brand}viewId={viewId}linkId={linkId}+ documentId={documentId}documentName={documentName}isDataroom={dataroomId ? true : false}setDocumentData={setDocumentData}diff --git a/lib/webstorage.ts b/lib/webstorage.tsindex d3a090ef..b455b365 100644--- a/lib/webstorage.ts+++ b/lib/webstorage.ts@@ -6,7 +6,6 @@export const localStorage = {getItem(key: string) {try {- // eslint-disable-next-linereturn window.localStorage.getItem(key);} catch (e) {// In case storage is restricted. Possible reasons@@ -16,7 +15,6 @@ export const localStorage = {},setItem(key: string, value: string) {try {- // eslint-disable-next-linewindow.localStorage.setItem(key, value);} catch (e) {// In case storage is restricted. Possible reasons@@ -27,7 +25,6 @@ export const localStorage = {},removeItem: (key: string) => {try {- // eslint-disable-next-linewindow.localStorage.removeItem(key);} catch (e) {return;diff --git a/package-lock.json b/package-lock.jsonindex 476a69f6..8210ed7e 100644--- a/package-lock.json+++ b/package-lock.json@@ -33,6 +33,7 @@"@radix-ui/react-popover": "^1.1.1","@radix-ui/react-portal": "^1.1.1","@radix-ui/react-progress": "^1.1.0",+ "@radix-ui/react-radio-group": "^1.2.1","@radix-ui/react-scroll-area": "^1.1.0","@radix-ui/react-select": "^2.1.1","@radix-ui/react-separator": "^1.1.0",@@ -4688,6 +4689,74 @@}}},+ "node_modules/@radix-ui/react-radio-group": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.2.1.tgz",+ "integrity": "sha512-kdbv54g4vfRjja9DNWPMxKvXblzqbpEC8kspEkZ6dVP7kQksGCn+iZHkcCz2nb00+lPdRvxrqy4WrvvV1cNqrQ==",+ "dependencies": {+ "@radix-ui/primitive": "1.1.0",+ "@radix-ui/react-compose-refs": "1.1.0",+ "@radix-ui/react-context": "1.1.1",+ "@radix-ui/react-direction": "1.1.0",+ "@radix-ui/react-presence": "1.1.1",+ "@radix-ui/react-primitive": "2.0.0",+ "@radix-ui/react-roving-focus": "1.1.0",+ "@radix-ui/react-use-controllable-state": "1.1.0",+ "@radix-ui/react-use-previous": "1.1.0",+ "@radix-ui/react-use-size": "1.1.0"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-context": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.1.tgz",+ "integrity": "sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-presence": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.1.tgz",+ "integrity": "sha512-IeFXVi4YS1K0wVZzXNrbaaUvIJ3qdY+/Ih4eHFhWA9SwGR9UDX7Ck8abvL57C4cv3wwMvUE0OG69Qc3NCcTe/A==",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.0",+ "@radix-ui/react-use-layout-effect": "1.1.0"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-roving-focus": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.0.tgz",diff --git a/package.json b/package.jsonindex 4aa320e8..e58e0662 100644--- a/package.json+++ b/package.json@@ -16,7 +16,7 @@"trigger:dev": "npx @trigger.dev/cli@latest dev","stripe:webhook": "pkgx stripe listen --forward-to localhost:3000/api/stripe/webhook","format": "prettier --write \"**/*.{js,jsx,ts,tsx,mdx}\"",- "dev:prisma":"npx prisma generate && npx prisma migrate deploy"+ "dev:prisma": "npx prisma generate && npx prisma migrate deploy"},"dependencies": {"@aws-sdk/client-lambda": "^3.658.1",@@ -43,6 +43,7 @@"@radix-ui/react-popover": "^1.1.1","@radix-ui/react-portal": "^1.1.1","@radix-ui/react-progress": "^1.1.0",+ "@radix-ui/react-radio-group": "^1.2.1","@radix-ui/react-scroll-area": "^1.1.0","@radix-ui/react-select": "^2.1.1","@radix-ui/react-separator": "^1.1.0",diff --git a/pages/api/report.ts b/pages/api/report.tsnew file mode 100644index 00000000..40fc0edd--- /dev/null+++ b/pages/api/report.ts@@ -0,0 +1,103 @@+import type { NextApiRequest, NextApiResponse } from "next";++import { waitUntil } from "@vercel/functions";+import { z } from "zod";++import prisma from "@/lib/prisma";+import { redis } from "@/lib/redis";++const bodyValidation = z.object({+ linkId: z.string(),+ documentId: z.string(),+ viewId: z.string(),+ abuseType: z.number().int().min(1).max(6),+});++export const config = {+ // in order to enable `waitUntil` function+ supportsResponseStreaming: true,+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const { linkId, documentId, viewId, abuseType } = req.body as {+ linkId: string;+ documentId: string;+ viewId: string;+ abuseType: number;+ };+ const result = bodyValidation.safeParse(req.body);+ if (!result.success) {+ return res.status(400).json({ message: "Invalid request" });+ }++ try {+ const view = await prisma.view.findUnique({+ where: {+ id: viewId,+ linkId,+ documentId,+ },+ select: { id: true },+ });++ if (!view) {+ return res.status(400).json({+ status: "error",+ message: "View not found",+ });+ }+ } catch (err) {+ console.error(err);++ return res.status(500).json({+ status: "error",+ message: (err as Error).message,+ });+ }++ try {+ // Create a unique Redis key to track reports for the documentId+ const reportKey = `report:doc_${documentId}`;+ const viewIdValue = `view_${viewId}`;++ // Check if the viewId has already reported for this documentId+ const hasReported = await redis.sismember(reportKey, viewIdValue);+ if (hasReported) {+ return res.status(400).json({+ status: "error",+ message: "You have already reported this document",+ });+ }++ // Perform all non-dependent Redis operations in parallel+ waitUntil(+ Promise.all([+ // Add the viewId to the Redis set for this documentId+ redis.sadd(reportKey, viewIdValue),++ // Increment the report count for the documentId+ redis.hincrby("reportCount", `doc_${documentId}`, 1),++ // Store the abuse type report under a Redis hash for future analysis+ redis.hset(`report:doc_${documentId}:details`, {+ [viewIdValue]: abuseType, // Store the abuseType as a number for this viewId+ }),+ ]),+ );++ return res.status(200).json({+ status: "success",+ message: "Report submitted successfully",+ });+ } catch (err) {+ console.error(err);++ return res.status(500).json({+ status: "error",+ message: (err as Error).message,+ });+ }+}