Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: viewer mode for dataroom
Marc Seitz52c9e207dcf3
diff --git a/components/view/DataroomViewer.tsx b/components/view/DataroomViewer.tsxnew file mode 100644index 00000000..a58edb0c--- /dev/null+++ b/components/view/DataroomViewer.tsx@@ -0,0 +1,126 @@+import {+ Brand,+ Dataroom,+ DataroomDocument,+ DataroomFolder,+} from "@prisma/client";+import Nav from "./nav";+import { Button } from "../ui/button";+import FolderCard from "./dataroom/folder-card";+import DocumentCard from "./dataroom/document-card";+import { useState } from "react";+import { ScrollArea } from "../ui/scroll-area";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+} from "../ui/breadcrumb";+import Link from "next/link";++type DRDocument = {+ dataroomDocumentId: string;+ folderId: string | null;+ id: string;+ name: string;+ versions: {+ id: string;+ versionNumber: number;+ hasPages: boolean;+ }[];+};++export default function DataroomViewer({+ brand,+ viewId,+ dataroomViewId,+ dataroom,+ setViewType,+ setDocumentData,+}: {+ brand: Brand;+ viewId: string;+ dataroomViewId: string;+ dataroom: any;+ setViewType: React.Dispatch<React.SetStateAction<"DOCUMENT" | "DATAROOM">>;+ setDocumentData: React.Dispatch<+ React.SetStateAction<{+ id: string;+ name: string;+ hasPages: boolean;+ documentVersionId: string;+ documentVersionNumber: number;+ } | null>+ >;+}) {+ const [folderId, setFolderId] = useState<string | null>(null);+ const { documents, folders } = dataroom as {+ documents: DRDocument[];+ folders: DataroomFolder[];+ };+ console.log("documents, ", documents);+ return (+ <>+ <Nav brand={brand} viewId={viewId} />+ <div+ style={{ height: "calc(100vh - 64px)" }}+ className="flex items-center relative bg-white dark:bg-black"+ >+ <div className="flex justify-center mx-auto relative h-full w-full">+ <ScrollArea className="flex-grow " showScrollbar>+ <div className="relative overflow-hidden mx-2 sm:mx-3 md:mx-5 lg:mx-7 xl:mx-10 mt-4 md:mt-5 lg:mt-8 mb-10 space-y-8 p-3 w-1/2">+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem key={"root"}>+ <BreadcrumbLink asChild>+ <BreadcrumbLink onClick={() => setFolderId(null)}>+ Home+ </BreadcrumbLink>+ </BreadcrumbLink>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ <div className="space-y-4">+ {/* Folders list */}+ <ul role="list" className="space-y-4">+ {folders+ ? folders+ .filter((folder) => folder.parentId === folderId)+ .map((folder) => {+ return (+ <FolderCard+ key={folder.id}+ folder={folder}+ dataroomId={dataroom?.id}+ setFolderId={setFolderId}+ />+ );+ })+ : null}+ </ul>++ {/* Documents list */}+ <ul role="list" className="space-y-4">+ {documents+ ? documents+ .filter((doc) => doc.folderId === folderId)+ .map((document: DRDocument) => {+ return (+ <DocumentCard+ key={document.id}+ document={document}+ setViewType={setViewType}+ setDocumentData={setDocumentData}+ />+ );+ })+ : null}+ </ul>+ </div>+ </div>+ </ScrollArea>+ </div>+ </div>+ </>+ );+}diff --git a/components/view/PagesViewer.tsx b/components/view/PagesViewer.tsxindex 59692ad5..d4c22114 100644--- a/components/view/PagesViewer.tsx+++ b/components/view/PagesViewer.tsx@@ -20,16 +20,20 @@ export default function PagesViewer({feedbackEnabled,versionNumber,brand,+ dataroomId,+ setDocumentData,}: {pages: { file: string; pageNumber: string; embeddedLinks: string[] }[];linkId: string;documentId: string;viewId: string;- assistantEnabled: boolean;+ assistantEnabled?: boolean;allowDownload: boolean;feedbackEnabled: boolean;versionNumber: number;brand?: Brand;+ dataroomId?: string;+ setDocumentData?: (data: any) => void;}) {const router = useRouter();const numPages = pages.length;@@ -140,6 +144,7 @@ export default function PagesViewer({duration: duration,pageNumber: pageNumberRef.current,versionNumber: versionNumber,+ dataroomId: dataroomId,}),headers: {"Content-Type": "application/json",@@ -168,6 +173,8 @@ export default function PagesViewer({viewId={viewId}linkId={linkId}embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}+ isDataroom={dataroomId ? true : false}+ setDocumentData={setDocumentData}/><divstyle={{ height: "calc(100vh - 64px)" }}diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxnew file mode 100644index 00000000..ba0cb761--- /dev/null+++ b/components/view/dataroom/dataroom-view.tsx@@ -0,0 +1,239 @@+import React, { useEffect, useRef, useState } from "react";+import AccessForm, {+ DEFAULT_ACCESS_FORM_DATA,+ DEFAULT_ACCESS_FORM_TYPE,+} from "@/components/view/access-form";+import { usePlausible } from "next-plausible";+import { toast } from "sonner";+import LoadingSpinner from "@/components/ui/loading-spinner";+import EmailVerificationMessage from "../email-verification-form";++import { Brand } from "@prisma/client";+import { useRouter } from "next/router";+import { useAnalytics } from "@/lib/analytics";+import DataroomViewer from "../DataroomViewer";+import PagesViewer from "../PagesViewer";+import { LinkWithDataroom } from "@/pages/view/d/[linkId]";++export type DEFAULT_DOCUMENT_VIEW_TYPE = {+ viewId: string;+ dataroomViewId?: string;+ file: string | null;+ pages: { file: string; pageNumber: string; embeddedLinks: string[] }[] | null;+};++export default function DataroomView({+ link,+ userEmail,+ userId,+ isProtected,+ brand,+ token,+ verifiedEmail,+}: {+ link: LinkWithDataroom;+ userEmail: string | null | undefined;+ userId: string | null | undefined;+ isProtected: boolean;+ brand?: Brand;+ token?: string;+ verifiedEmail?: string;+}) {+ const { linkType, dataroom, emailProtected, password: linkPassword } = link;++ const plausible = usePlausible();+ const analytics = useAnalytics();+ const router = useRouter();++ const didMount = useRef<boolean>(false);+ const [submitted, setSubmitted] = useState<boolean>(false);+ const [isLoading, setIsLoading] = useState<boolean>(false);+ const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({+ viewId: "",+ file: null,+ pages: null,+ });+ const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(+ DEFAULT_ACCESS_FORM_DATA,+ );+ const [verificationRequested, setVerificationRequested] =+ useState<boolean>(false);+ const [documentData, setDocumentData] = useState<{+ id: string;+ name: string;+ hasPages: boolean;+ documentVersionId: string;+ documentVersionNumber: number;+ } | null>(null);++ const [viewType, setViewType] = useState<"DOCUMENT" | "DATAROOM">("DATAROOM");++ const handleSubmission = async (): Promise<void> => {+ setIsLoading(true);+ const response = await fetch("/api/views-dataroom", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...data,+ email: data.email || verifiedEmail || userEmail,+ linkId: link.id,+ documentId: documentData?.id,+ documentName: documentData?.name,+ // ownerId: documentData?.ownerId,+ userId: userId || null,+ documentVersionId: documentData?.documentVersionId,+ hasPages: documentData?.hasPages,+ token: token || null,+ verifiedEmail: verifiedEmail || null,+ dataroomId: dataroom?.id,+ linkType: linkType,+ dataroomViewId: viewData.dataroomViewId ?? null,+ viewType: viewType,+ }),+ });++ if (response.ok) {+ const fetchData = await response.json();++ if (fetchData.type === "email-verification") {+ setVerificationRequested(true);+ setIsLoading(false);+ } else {+ const { viewId, file, pages } = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;+ plausible("documentViewed"); // track the event+ analytics.identify(+ userEmail ?? verifiedEmail ?? data.email ?? undefined,+ );+ analytics.capture("Link Viewed", {+ linkId: link.id,+ documentId: documentData?.id,+ dataroomId: dataroom?.id,+ linkType: linkType,+ viewerId: viewId,+ viewerEmail: data.email || verifiedEmail || userEmail,+ });+ setViewData((prev) => ({+ viewId,+ dataroomViewId:+ viewType === "DATAROOM" ? viewId : prev.dataroomViewId,+ file,+ pages,+ }));+ setSubmitted(true);+ setVerificationRequested(false);+ setIsLoading(false);+ }+ } else {+ const { message } = await response.json();+ toast.error(message);+ setIsLoading(false);+ }+ };++ const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (+ event: React.FormEvent,+ ): Promise<void> => {+ event.preventDefault();+ await handleSubmission();+ };++ // If token is present, run handle submit which will verify token and get document+ // If link is not submitted and does not have email / password protection, show the access form+ useEffect(() => {+ console.log("viewData", viewData);+ if (!didMount.current) {+ if ((!submitted && !isProtected) || token || viewData.dataroomViewId) {+ handleSubmission();+ }+ didMount.current = true;+ }+ }, [submitted, isProtected, token, viewData.dataroomViewId]);++ useEffect(() => {+ console.log("documentData", documentData);+ // Ensure we're not running this logic on initial mount, but only when `documentData` changes thereafter+ if (didMount.current) {+ if (documentData !== null) {+ // Call handleSubmission or any other logic that needs to run when a document is selected+ handleSubmission();+ }+ }++ setViewData((prev) => ({+ ...prev,+ pages: null,+ file: null,+ viewId: "",+ }));+ // This effect is specifically for handling changes to `documentData` post-mount+ }, [documentData]);++ // Components to render when email is submitted but verification is pending+ if (verificationRequested) {+ return (+ <EmailVerificationMessage+ onSubmitHandler={handleSubmit}+ data={data}+ isLoading={isLoading}+ />+ );+ }++ // If link is not submitted and does not have email / password protection, show the access form+ if (!submitted && isProtected) {+ return (+ <AccessForm+ data={data}+ email={userEmail}+ setData={setData}+ onSubmitHandler={handleSubmit}+ requireEmail={emailProtected}+ requirePassword={!!linkPassword}+ isLoading={isLoading}+ />+ );+ }++ if (isLoading) {+ return (+ <div className="h-screen flex items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }+ return (+ <div className="bg-gray-950">+ {submitted ? (+ documentData && viewData.pages ? (+ <PagesViewer+ pages={viewData.pages}+ viewId={viewData.viewId}+ linkId={link.id}+ documentId={documentData.id}+ allowDownload={link.allowDownload!}+ feedbackEnabled={link.enableFeedback!}+ versionNumber={documentData.documentVersionNumber}+ brand={brand}+ dataroomId={dataroom.id}+ setDocumentData={setDocumentData}+ />+ ) : (+ <DataroomViewer+ brand={brand!}+ viewId={viewData.viewId}+ dataroomViewId={viewData.dataroomViewId!}+ dataroom={dataroom}+ setDocumentData={setDocumentData}+ setViewType={setViewType}+ />+ )+ ) : (+ <div className="h-screen flex items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ )}+ </div>+ );+}diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsxnew file mode 100644index 00000000..f5548de0--- /dev/null+++ b/components/view/dataroom/document-card.tsx@@ -0,0 +1,99 @@+import { nFormatter, timeAgo } from "@/lib/utils";+import Link from "next/link";+import { type DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";+import { TeamContextType } from "@/context/team-context";+import BarChart from "@/components/shared/icons/bar-chart";+import Image from "next/image";+import NotionIcon from "@/components/shared/icons/notion";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { TrashIcon, MoreVertical, FolderInputIcon } from "lucide-react";+import { mutate } from "swr";+import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";+import Check from "@/components/shared/icons/check";+import Copy from "@/components/shared/icons/copy";+import { useEffect, useRef, useState } from "react";+import { useTheme } from "next-themes";+import { MoveToFolderModal } from "@/components/documents/move-folder-modal";+import { type DataroomFolderDocument } from "@/lib/swr/use-dataroom";++type DRDocument = {+ dataroomDocumentId: string;+ id: string;+ name: string;+ versions: {+ id: string;+ versionNumber: number;+ hasPages: boolean;+ }[];+};++type DocumentsCardProps = {+ document: DRDocument;+ setViewType: (type: "DOCUMENT" | "DATAROOM") => void;+ setDocumentData: (data: {+ id: string;+ name: string;+ hasPages: boolean;+ documentVersionId: string;+ documentVersionNumber: number;+ }) => void;+};+export default function DocumentCard({+ document,+ setViewType,+ setDocumentData,+}: DocumentsCardProps) {+ const { theme, systemTheme } = useTheme();+ const isLight =+ theme === "light" || (theme === "system" && systemTheme === "light");++ return (+ <>+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-200 dark:ring-gray-700 transition-all hover:ring-gray-300 hover:dark:ring-gray-500 hover:bg-secondary sm:p-4 flex justify-between items-center">+ <div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">+ <div className="w-8 mx-0.5 sm:mx-1 text-center flex justify-center items-center">+ <Image+ src={`/_icons/pdf${isLight ? "-light" : ""}.svg`}+ alt="File icon"+ width={50}+ height={50}+ />+ </div>++ <div className="flex-col">+ <div className="flex items-center">+ <h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">+ <Link+ href="#"+ onClick={() => {+ setViewType("DOCUMENT");+ setDocumentData({+ id: document.id,+ name: document.name,+ hasPages: document.versions[0].hasPages,+ documentVersionId: document.versions[0].id,+ documentVersionNumber: document.versions[0].versionNumber,+ });+ }}+ className="truncate w-full"+ >+ <span>{document.name}</span>+ <span className="absolute inset-0" />+ </Link>+ </h2>+ </div>+ </div>+ </div>+ </li>+ </>+ );+}diff --git a/components/view/dataroom/folder-card.tsx b/components/view/dataroom/folder-card.tsxnew file mode 100644index 00000000..917f92b7--- /dev/null+++ b/components/view/dataroom/folder-card.tsx@@ -0,0 +1,53 @@+import { timeAgo } from "@/lib/utils";+import Link from "next/link";+import { TeamContextType } from "@/context/team-context";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { MoreVertical, FolderIcon } from "lucide-react";+import { useRef } from "react";+import { FolderWithCount } from "@/lib/swr/use-documents";+import { DataroomFolderWithCount } from "@/lib/swr/use-dataroom";+import { DataroomFolder } from "@prisma/client";++type FolderCardProps = {+ folder: DataroomFolder;+ dataroomId: string;+ setFolderId: (id: string) => void;+};+export default function FolderCard({+ folder,+ dataroomId,+ setFolderId,+}: FolderCardProps) {+ return (+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-400 dark:ring-gray-500 transition-all hover:ring-gray-500 hover:dark:ring-gray-400 hover:bg-secondary sm:p-4 flex justify-between items-center">+ <div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">+ <div className="w-8 mx-0.5 sm:mx-1 text-center flex justify-center items-center">+ <FolderIcon className="w-8 h-8 " strokeWidth={1} />+ </div>++ <div className="flex-col">+ <div className="flex items-center">+ <h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">+ <Link+ href="#"+ onClick={() => setFolderId(folder.id)}+ className="truncate w-full"+ >+ <span>{folder.name}</span>+ <span className="absolute inset-0" />+ </Link>+ </h2>+ </div>+ </div>+ </div>+ </li>+ );+}diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex 42d17eeb..1fcba0ee 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -25,6 +25,8 @@ export default function Nav({linkId,type,embeddedLinks,+ isDataroom,+ setDocumentData,}: {pageNumber?: number;numPages?: number;@@ -35,6 +37,8 @@ export default function Nav({viewId?: string;linkId?: string;type?: "pdf" | "notion";+ isDataroom?: boolean;+ setDocumentData?: (data: any) => void;}) {const downloadFile = async () => {if (!allowDownload || type === "notion") return;@@ -68,7 +72,7 @@ export default function Nav({><div className="mx-auto px-2 sm:px-6 lg:px-8"><div className="relative flex h-16 items-center justify-between">- <div className="flex flex-1 items-stretch justify-start">+ <div className="flex flex-1 justify-start items-center"><div className="flex flex-shrink-0 items-center relative h-8 w-36">{brand && brand.logo ? (<Image@@ -89,6 +93,17 @@ export default function Nav({</Link>)}</div>+ {isDataroom && setDocumentData ? (+ <div>+ <Button+ onClick={() => setDocumentData(null)}+ className="text-white text-sm font-medium"+ variant="link"+ >+ Dataroom Home+ </Button>+ </div>+ ) : null}</div><div className="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0 space-x-4">{embeddedLinks && embeddedLinks.length > 0 ? (diff --git a/pages/api/links/[id]/dataroom.ts b/pages/api/links/[id]/dataroom.tsnew file mode 100644index 00000000..5a43770d--- /dev/null+++ b/pages/api/links/[id]/dataroom.ts@@ -0,0 +1,106 @@+import { NextApiRequest, NextApiResponse } from "next";+import prisma from "@/lib/prisma";+import { getServerSession } from "next-auth/next";+import { hashPassword } from "@/lib/utils";+import { CustomUser } from "@/lib/types";+import { authOptions } from "../../auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/links/:id/dataroom+ const { id } = req.query as { id: string };++ try {+ console.time("get-link");+ const link = await prisma.link.findUnique({+ where: {+ id: id,+ },+ select: {+ id: true,+ expiresAt: true,+ emailProtected: true,+ emailAuthenticated: true,+ allowDownload: true,+ enableFeedback: true,+ password: true,+ isArchived: true,+ enableCustomMetatag: true,+ metaTitle: true,+ metaDescription: true,+ metaImage: true,+ linkType: true,+ dataroom: {+ select: {+ id: true,+ name: true,+ teamId: true,+ documents: {+ select: {+ id: true,+ folderId: true,+ document: {+ select: {+ id: true,+ name: true,+ versions: {+ where: { isPrimary: true },+ select: {+ id: true,+ versionNumber: true,+ type: true,+ hasPages: true,+ file: true,+ },+ take: 1,+ },+ },+ },+ },+ },+ folders: true,+ },+ },+ },+ });++ console.timeEnd("get-link");++ if (!link) {+ return res.status(404).json({ error: "Link not found" });+ }++ if (link.isArchived) {+ return res.status(404).json({ error: "Link is archived" });+ }++ let brand = await prisma.brand.findFirst({+ where: {+ teamId: link.dataroom?.teamId!,+ },+ select: {+ logo: true,+ brandColor: true,+ },+ });++ if (!brand) {+ brand = null;+ }++ return res.status(200).json({ link, brand });+ } catch (error) {+ return res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ }++ // We only allow GET and PUT requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+}diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsnew file mode 100644index 00000000..43696503--- /dev/null+++ b/pages/api/views-dataroom.ts@@ -0,0 +1,308 @@+import { NextApiRequest, NextApiResponse } from "next";+import prisma from "@/lib/prisma";+import { checkPassword, log } from "@/lib/utils";+import { newId } from "@/lib/id-helper";+import { sendVerificationEmail } from "@/lib/emails/send-email-verification";+import { getFile } from "@/lib/files/get-file";+import sendNotification from "@/lib/api/notification-helper";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ // We only allow POST requests+ if (req.method !== "POST") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }+ // POST /api/views-dataroom+ const {+ linkId,+ documentId,+ dataroomId,+ userId,+ documentVersionId,+ documentName,+ hasPages,+ token,+ ownerId,+ verifiedEmail,+ linkType,+ dataroomViewId,+ viewType,+ ...data+ } = req.body as {+ linkId: string;+ documentId: string | undefined;+ dataroomId: string | undefined;+ userId: string | null;+ documentVersionId: string | undefined;+ documentName: string | undefined;+ hasPages: boolean | undefined;+ token: string | null;+ ownerId: string | null;+ verifiedEmail: string | null;+ linkType: string;+ dataroomViewId?: string;+ viewType: string;+ };++ const { email, password } = data as { email: string; password: string };++ // Fetch the link to verify the settings+ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ select: {+ emailProtected: true,+ enableNotification: true,+ emailAuthenticated: true,+ password: true,+ domainSlug: true,+ isArchived: true,+ slug: true,+ allowList: true,+ denyList: true,+ },+ });++ if (!link) {+ res.status(404).json({ message: "Link not found." });+ return;+ }++ if (link.isArchived) {+ res.status(404).json({ message: "Link is no longer available." });+ return;+ }++ // Check if email is required for visiting the link+ if (link.emailProtected) {+ if (!email || email.trim() === "") {+ res.status(400).json({ message: "Email is required." });+ return;+ }+ }++ // Check if password is required for visiting the link+ if (link.password) {+ if (!password || password.trim() === "") {+ res.status(400).json({ message: "Password is required." });+ return;+ }++ const isPasswordValid = await checkPassword(password, link.password);+ if (!isPasswordValid) {+ res.status(403).json({ message: "Invalid password." });+ return;+ }+ }++ // Check if email is allowed to visit the link+ if (link.allowList && link.allowList.length > 0) {+ // Extract the domain from the email address+ const emailDomain = email.substring(email.lastIndexOf("@"));++ // Determine if the email or its domain is allowed+ const isAllowed = link.allowList.some((allowed) => {+ return (+ allowed === email ||+ (allowed.startsWith("@") && emailDomain === allowed)+ );+ });++ // Deny access if the email is not allowed+ if (!isAllowed) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }+ }++ // Check if email is denied to visit the link+ if (link.denyList && link.denyList.length > 0) {+ // Extract the domain from the email address+ const emailDomain = email.substring(email.lastIndexOf("@"));++ // Determine if the email or its domain is denied+ const isDenied = link.denyList.some((denied) => {+ return (+ denied === email || (denied.startsWith("@") && emailDomain === denied)+ );+ });++ // Deny access if the email is denied+ if (isDenied) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }+ }++ // Check if email verification is required for visiting the link+ if (link.emailAuthenticated && !token) {+ const token = newId("email");+ const expiresAt = new Date();+ expiresAt.setHours(expiresAt.getHours() + 1); // token expires in 1 hour++ await prisma.verificationToken.create({+ data: {+ token,+ identifier: `${linkId}:${email}`,+ expires: expiresAt,+ },+ });++ // set the default verification url+ let verificationUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/view/${linkId}/?token=${token}&email=${encodeURIComponent(email)}`;++ if (link.domainSlug && link.slug) {+ // if custom domain is enabled, use the custom domain+ verificationUrl = `https://${link.domainSlug}/${link.slug}/?token=${token}&email=${encodeURIComponent(email)}`;+ }++ await sendVerificationEmail(email, verificationUrl);+ res.status(200).json({+ type: "email-verification",+ message: "Verification email sent.",+ });+ return;+ }++ let isEmailVerified: boolean = false;+ if (link.emailAuthenticated && token) {+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: token,+ identifier: `${linkId}:${verifiedEmail}`,+ },+ });++ if (!verification) {+ res.status(401).json({ message: "Unauthorized access" });+ return;+ }++ // Check the token's expiration date+ if (Date.now() > verification.expires.getTime()) {+ res.status(401).json({ message: "Access expired" });+ return;+ }++ isEmailVerified = true;+ }++ if (viewType === "DATAROOM") {+ try {+ console.time("create-view");+ const newDataroomView = await prisma.view.create({+ data: {+ linkId: linkId,+ viewerEmail: email,+ verified: isEmailVerified,+ dataroomId: dataroomId,+ },+ select: { id: true },+ });+ console.timeEnd("create-view");++ const returnObject = {+ message: "Dataroom View recorded",+ viewId: newDataroomView.id,+ file: null,+ pages: null,+ };++ return res.status(200).json(returnObject);+ } catch (error) {+ log({+ message: `Failed to record view for ${linkId}. \n\n ${error}`,+ type: "error",+ mention: true,+ });+ return res.status(500).json({ message: (error as Error).message });+ }+ }++ try {+ console.time("create-view");+ const newView = await prisma.view.create({+ data: {+ linkId: linkId,+ viewerEmail: email,+ documentId: documentId,+ verified: isEmailVerified,+ dataroomViewId: dataroomViewId,+ },+ select: { id: true },+ });+ console.timeEnd("create-view");++ // if document version has pages, then return pages+ // otherwise, return file from document version+ let documentPages, documentVersion;+ // let documentPagesPromise, documentVersionPromise;+ if (hasPages) {+ // get pages from document version+ console.time("get-pages");+ documentPages = await prisma.documentPage.findMany({+ where: { versionId: documentVersionId },+ orderBy: { pageNumber: "asc" },+ select: {+ file: true,+ storageType: true,+ pageNumber: true,+ embeddedLinks: true,+ },+ });++ documentPages = await Promise.all(+ documentPages.map(async (page) => {+ const { storageType, ...otherPage } = page;+ return {+ ...otherPage,+ file: await getFile({ data: page.file, type: storageType }),+ };+ }),+ );++ console.timeEnd("get-pages");+ } else {+ // get file from document version+ console.time("get-file");+ documentVersion = await prisma.documentVersion.findUnique({+ where: { id: documentVersionId },+ select: {+ file: true,+ storageType: true,+ },+ });++ if (!documentVersion) {+ res.status(404).json({ message: "Document version not found." });+ return;+ }++ documentVersion.file = await getFile({+ data: documentVersion.file,+ type: documentVersion.storageType,+ });+ console.timeEnd("get-file");+ }++ const returnObject = {+ message: "View recorded",+ viewId: newView.id,+ file: documentVersion ? documentVersion.file : null,+ pages: documentPages ? documentPages : null,+ };++ return res.status(200).json(returnObject);+ } catch (error) {+ log({+ message: `Failed to record view for ${linkId}. \n\n ${error}`,+ type: "error",+ mention: true,+ });+ return res.status(500).json({ message: (error as Error).message });+ }+}diff --git a/pages/view/d/[linkId]/index.tsx b/pages/view/d/[linkId]/index.tsxnew file mode 100644index 00000000..bc8d51cc--- /dev/null+++ b/pages/view/d/[linkId]/index.tsx@@ -0,0 +1,236 @@+import LoadingSpinner from "@/components/ui/loading-spinner";+import NotFound from "@/pages/404";+import { useSession } from "next-auth/react";++import { CustomUser } from "@/lib/types";+import { GetStaticPropsContext } from "next";+import { useRouter } from "next/router";+import { Brand, DataroomFolder, Link } from "@prisma/client";+import CustomMetatag from "@/components/view/custom-metatag";+import Head from "next/head";+import DataroomView from "@/components/view/dataroom/dataroom-view";++export interface LinkWithDataroom extends Link {+ dataroom: {+ id: string;+ name: string;+ teamId: string;+ documents: {+ id: string;+ folderId: string | null;+ document: {+ id: string;+ name: string;+ versions: {+ id: string;+ versionNumber: number;+ type: string;+ hasPages: boolean;+ file: string;+ }[];+ };+ }[];+ folders: DataroomFolder[];+ };+}++export const getStaticProps = async (context: GetStaticPropsContext) => {+ const { linkId } = context.params as { linkId: string };++ // Fetch the link+ const res = await fetch(+ `${process.env.NEXTAUTH_URL}/api/links/${linkId}/dataroom`,+ );++ if (!res.ok) {+ return { notFound: true };+ }+ const { link, brand } = (await res.json()) as {+ link: LinkWithDataroom;+ brand: Brand | null;+ };++ if (!link || !link.dataroom) {+ return {+ notFound: true,+ };+ }++ if (link.linkType === "DOCUMENT_LINK") {+ return {+ notFound: true,+ };+ }++ // iterate the link.documents and extract type and file and rest of the props+ let documents = [];+ for (const document of link.dataroom.documents) {+ const { type, file, ...versionWithoutTypeAndFile } =+ document.document.versions[0];++ const newDocument = {+ ...document.document,+ dataroomDocumentId: document.id,+ folderId: document.folderId,+ versions: [versionWithoutTypeAndFile],+ };++ documents.push(newDocument);+ }++ return {+ props: {+ // return link without file and type to avoid sending the file to the client+ link: {+ ...link,+ dataroom: { ...link.dataroom, documents: documents },+ },+ meta: {+ enableCustomMetatag: link.enableCustomMetatag || false,+ metaTitle: link.metaTitle,+ metaDescription: link.metaDescription,+ metaImage: link.metaImage,+ },+ brand, // pass brand to the client+ },+ revalidate: brand ? 10 : false,+ };+};++export async function getStaticPaths() {+ return {+ paths: [],+ fallback: true,+ };+}++export default function ViewPage({+ link,+ meta,+ brand,+}: {+ link: LinkWithDataroom;+ meta: {+ enableCustomMetatag: boolean;+ metaTitle: string | null;+ metaDescription: string | null;+ metaImage: string | null;+ } | null;+ brand?: Brand;+}) {+ const router = useRouter();+ const { token, email: verifiedEmail } = router.query as {+ token: string;+ email: string;+ };+ const { fId: folderId, dId: documentId } = router.query as {+ fId: string;+ dId: string;+ };+ const { data: session, status } = useSession();++ if (!link || status === "loading" || router.isFallback) {+ return (+ <>+ <Head>+ <meta+ property="og:url"+ key="og-url"+ content={`https://www.papermark.io/view/${router.query.linkId}`}+ />+ </Head>+ {meta && meta.enableCustomMetatag ? (+ <CustomMetatag+ title={meta.metaTitle}+ description={meta.metaDescription}+ imageUrl={meta.metaImage}+ />+ ) : null}+ <div className="h-screen flex items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ </>+ );+ }++ const {+ expiresAt,+ emailProtected,+ emailAuthenticated,+ password: linkPassword,+ isArchived,+ } = link;++ const { email: userEmail, id: userId } = (session?.user as CustomUser) || {};++ // If the link is expired, show a 404 page+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return (+ <NotFound message="Sorry, the link you're looking for is expired." />+ );+ }++ if (isArchived) {+ return (+ <NotFound message="Sorry, the link you're looking for is archived." />+ );+ }++ const { enableCustomMetatag, metaTitle, metaDescription, metaImage } = link;++ if (emailProtected || linkPassword) {+ return (+ <>+ <Head>+ <meta+ property="og:url"+ key="og-url"+ content={`https://www.papermark.io/view/${link.id}`}+ />+ </Head>+ {enableCustomMetatag ? (+ <CustomMetatag+ title={metaTitle}+ description={metaDescription}+ imageUrl={metaImage}+ />+ ) : null}+ <DataroomView+ link={link}+ userEmail={userEmail}+ userId={userId}+ isProtected={true}+ brand={brand}+ token={token}+ verifiedEmail={verifiedEmail}+ />+ </>+ );+ }++ return (+ <>+ <Head>+ <meta+ property="og:url"+ key="og-url"+ content={`https://www.papermark.io/view/${link.id}`}+ />+ </Head>+ {enableCustomMetatag ? (+ <CustomMetatag+ title={metaTitle}+ description={metaDescription}+ imageUrl={metaImage}+ />+ ) : null}+ <DataroomView+ link={link}+ userEmail={userEmail}+ userId={userId}+ isProtected={false}+ brand={brand}+ />+ </>+ );+}