Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

Feat: Download specific folder / subfolder in dataroom (viewmode)

Ashish Viradiyab00eaee7740d
diff --git a/components/view/dataroom/folder-card.tsx b/components/view/dataroom/folder-card.tsx
index 9a2ca0cd..746dbccd 100644
--- a/components/view/dataroom/folder-card.tsx
+++ b/components/view/dataroom/folder-card.tsx
@@ -1,18 +1,91 @@
+import { useState } from "react";
+
import { DataroomFolder } from "@prisma/client";
-import { FolderIcon } from "lucide-react";
+import { Download, FolderIcon, MoreVerticalIcon } from "lucide-react";
+import { toast } from "sonner";
import { timeAgo } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+
type FolderCardProps = {
folder: DataroomFolder;
dataroomId: string;
setFolderId: (id: string) => void;
+ isPreview: boolean;
+ linkId: string;
+ viewId?: string;
+ allowDownload: boolean;
};
export default function FolderCard({
folder,
dataroomId,
setFolderId,
+ isPreview,
+ linkId,
+ viewId,
+ allowDownload,
}: FolderCardProps) {
+ const [open, setOpen] = useState(false);
+ const downloadDocument = async () => {
+ if (!allowDownload) {
+ toast.error("Downloading folders is not allowed.");
+ return;
+ }
+ if (isPreview) {
+ toast.error("You cannot download dataroom folders in preview mode.");
+ return;
+ }
+
+ toast.promise(
+ fetch(`/api/links/download/dataroom-folder`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ folderId: folder.id,
+ dataroomId,
+ viewId,
+ linkId,
+ }),
+ }),
+ {
+ loading: "Downloading dataroom document...",
+ success: async (response) => {
+ if (!response.ok) {
+ throw new Error("Failed to fetch download URL");
+ }
+
+ const { downloadUrl } = await response.json();
+
+ const link = document.createElement("a");
+ link.href = downloadUrl;
+ link.rel = "noopener noreferrer";
+ document.body.appendChild(link);
+ link.click();
+
+ setTimeout(() => {
+ document.body.removeChild(link);
+ }, 100);
+
+ return `Folder ${folder.name} downloaded successfully.`;
+ },
+ error: (error) => {
+ console.error("Error downloading file:", error);
+ return error.message || "An error occurred while downloading file.";
+ },
+ },
+ );
+ };
+
return (
<li className="group/row relative flex items-center justify-between rounded-lg border-0 p-3 ring-1 ring-gray-400 transition-all hover:bg-secondary hover:ring-gray-500 dark:bg-secondary dark:ring-gray-500 hover:dark:ring-gray-400 sm:p-4">
<div className="flex min-w-0 shrink items-center space-x-2 sm:space-x-4">
@@ -37,6 +110,37 @@ export default function FolderCard({
</div>
</div>
</div>
+ {allowDownload ? (
+ <div className="z-10">
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 p-0 text-gray-500 ring-1 ring-gray-100 hover:bg-gray-200 group-hover/row:text-foreground group-hover/row:ring-gray-300"
+ aria-label="Open menu"
+ >
+ <MoreVerticalIcon className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ downloadDocument();
+ setOpen(false);
+ }}
+ disabled={isPreview}
+ >
+ <Download className="h-4 w-4" />
+ Download
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : null}
</li>
);
}
diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsx
index 075bf07c..5a7ffc67 100644
--- a/components/view/viewer/dataroom-viewer.tsx
+++ b/components/view/viewer/dataroom-viewer.tsx
@@ -34,7 +34,9 @@ import { DocumentUploadModal } from "../dataroom/document-upload-modal";
import FolderCard from "../dataroom/folder-card";
import DataroomNav from "../dataroom/nav-dataroom";
-type FolderOrDocument = DataroomFolder | DataroomDocument;
+type FolderOrDocument =
+ | (DataroomFolder & { allowDownload: boolean })
+ | DataroomDocument;
export type DocumentVersion = {
id: string;
@@ -127,7 +129,28 @@ export default function DataroomViewer({
const mixedItems: FolderOrDocument[] = [
...(folders || [])
.filter((folder) => folder.parentId === folderId)
- .map((folder) => ({ ...folder, itemType: "folder" })),
+ .map((folder) => {
+ const folderDocuments = documents.filter(
+ (doc) => doc.folderId === folder.id,
+ );
+ const allDocumentsCanDownload =
+ folderDocuments.length > 0 &&
+ folderDocuments.every((doc) => {
+ const accessControl = accessControls.find(
+ (access) => access.itemId === doc.dataroomDocumentId,
+ );
+ return (
+ (accessControl?.canDownload ?? true) &&
+ doc.versions[0].type !== "notion"
+ );
+ });
+
+ return {
+ ...folder,
+ itemType: "folder",
+ allowDownload: allowDownload && allDocumentsCanDownload,
+ };
+ }),
...(documents || [])
.filter((doc) => doc.folderId === folderId)
.map((doc) => {
@@ -145,7 +168,7 @@ export default function DataroomViewer({
}),
];
return mixedItems.sort((a, b) => (a.orderIndex || 0) - (b.orderIndex || 0));
- }, [folders, documents, folderId, accessControls]);
+ }, [folders, documents, folderId, accessControls, allowDownload]);
const renderItem = (item: FolderOrDocument) => {
if ("versions" in item) {
@@ -167,6 +190,10 @@ export default function DataroomViewer({
folder={item}
dataroomId={dataroom?.id}
setFolderId={setFolderId}
+ isPreview={!!isPreview}
+ linkId={linkId}
+ viewId={viewId}
+ allowDownload={item.allowDownload}
/>
);
};
@@ -296,4 +323,4 @@ export default function DataroomViewer({
</div>
</>
);
-}
+}
\ No newline at end of file
diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.ts
new file mode 100644
index 00000000..57224e7d
--- /dev/null
+++ b/pages/api/links/download/dataroom-folder.ts
@@ -0,0 +1,248 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
+import { getLambdaClient } from "@/lib/files/aws-client";
+import prisma from "@/lib/prisma";
+import slugify from "@sindresorhus/slugify";
+import { ItemType, ViewType } from "@prisma/client";
+
+export const config = {
+ maxDuration: 180,
+};
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ try {
+ const { folderId, dataroomId, viewId, linkId } = req.body as {
+ folderId: string;
+ dataroomId: string;
+ viewId: string;
+ linkId: string;
+ };
+ if (!folderId) {
+ return res.status(400).json({ error: "folderId is required in request body" });
+ }
+
+ const view = await prisma.view.findUnique({
+ where: {
+ id: viewId,
+ linkId: linkId,
+ viewType: { equals: ViewType.DATAROOM_VIEW },
+ },
+ select: {
+ id: true,
+ viewedAt: true,
+ link: {
+ select: {
+ allowDownload: true,
+ expiresAt: true,
+ isArchived: true,
+ },
+ },
+ groupId: true,
+ },
+ });
+
+ // if view does not exist, we should not allow the download
+ if (!view) {
+ return res.status(404).json({ error: "Error downloading" });
+ }
+
+ // if link does not allow download, we should not allow the download
+ if (!view.link.allowDownload) {
+ return res.status(403).json({ error: "Error downloading" });
+ }
+
+ // if link is archived, we should not allow the download
+ if (view.link.isArchived) {
+ return res.status(403).json({ error: "Error downloading" });
+ }
+
+ // if link is expired, we should not allow the download
+ if (view.link.expiresAt && view.link.expiresAt < new Date()) {
+ return res.status(403).json({ error: "Error downloading" });
+ }
+
+ // if viewedAt is longer than 23 hours ago, we should not allow the download
+ if (
+ view.viewedAt &&
+ view.viewedAt < new Date(Date.now() - 23 * 60 * 60 * 1000)
+ ) {
+ return res.status(403).json({ error: "Error downloading" });
+ }
+
+ const rootFolder = await prisma.dataroomFolder.findUnique({
+ where: {
+ id: folderId,
+ dataroomId,
+ },
+ select: { id: true, name: true, path: true },
+ });
+
+ if (!rootFolder) {
+ return res.status(404).json({ error: "Folder not found" });
+ }
+
+ const subfolders = await prisma.dataroomFolder.findMany({
+ where: {
+ dataroomId,
+ path: { startsWith: rootFolder.path + "/" },
+ },
+ select: { id: true, name: true, path: true },
+ });
+
+ let allFolders = [rootFolder, ...subfolders];
+ let allDocuments = await prisma.dataroomDocument.findMany({
+ where: {
+ dataroomId,
+ folderId: {
+ in: allFolders.map((f) => f.id),
+ },
+ },
+ select: {
+ id: true,
+ folderId: true,
+ document: {
+ select: {
+ name: true,
+ versions: {
+ where: { isPrimary: true },
+ select: {
+ type: true,
+ file: true,
+ storageType: true,
+ originalFile: true,
+ },
+ take: 1,
+ },
+ },
+ },
+ },
+ });
+
+
+ // Check group permissions if groupId is provided
+ if (view?.groupId) {
+ const groupPermissions = await prisma.viewerGroupAccessControls.findMany({
+ where: { groupId: view.groupId, canDownload: true },
+ });
+
+ const permittedFolderIds = groupPermissions
+ .filter((permission) => permission.itemType === ItemType.DATAROOM_FOLDER)
+ .map((permission) => permission.itemId);
+ const permittedDocumentIds = groupPermissions
+ .filter((permission) => permission.itemType === ItemType.DATAROOM_DOCUMENT)
+ .map((permission) => permission.itemId);
+
+ allFolders = allFolders.filter((folder) =>
+ permittedFolderIds.includes(folder.id),
+ );
+ allDocuments = allDocuments.filter((doc) =>
+ permittedDocumentIds.includes(doc.id),
+ );
+ }
+
+ const folderStructure: {
+ [key: string]: {
+ name: string;
+ path: string;
+ files: { name: string; key: string }[];
+ };
+ } = {};
+
+ const fileKeys: string[] = [];
+
+ const addFileToStructure = (
+ fullPath: string,
+ rootFolder: { name: string; path: string },
+ fileName: string,
+ fileKey: string,
+ ) => {
+ let relativePath = "";
+ if (fullPath !== rootFolder.path) {
+ const pathRegex = new RegExp(`^${rootFolder.path}/(.*)$`);
+ const match = fullPath.match(pathRegex);
+ relativePath = match ? match[1] : "";
+ }
+
+ const pathParts = [slugify(rootFolder.name)];
+ if (relativePath) {
+ pathParts.push(...relativePath.split("/").filter(Boolean).map(part => slugify(part)));
+ }
+
+ let currentPath = "";
+ for (const part of pathParts) {
+ currentPath += "/" + part;
+ if (!folderStructure[currentPath]) {
+ folderStructure[currentPath] = {
+ name: part,
+ path: currentPath,
+ files: [],
+ };
+ }
+ }
+
+ if (fileName && fileKey) {
+ folderStructure[currentPath].files.push({ name: fileName, key: fileKey });
+ fileKeys.push(fileKey);
+ }
+ };
+
+ for (const folder of allFolders) {
+ const docs = allDocuments.filter((doc) => doc.folderId === folder.id);
+
+ if (docs.length === 0) {
+ addFileToStructure(folder.path, rootFolder, "", "");
+ continue;
+ }
+
+ for (const doc of docs) {
+ const version = doc.document.versions[0];
+ if (!version || version.type === "notion" || version.storageType === "VERCEL_BLOB") continue;
+
+ const fileKey = version.originalFile ?? version.file;
+ addFileToStructure(folder.path, rootFolder, doc.document.name, fileKey);
+ }
+ }
+
+ const rootPath = "/" + slugify(rootFolder.name);
+ if (!folderStructure[rootPath]) {
+ folderStructure[rootPath] = {
+ name: slugify(rootFolder.name),
+ path: rootPath,
+ files: [],
+ };
+ }
+
+ const client = getLambdaClient();
+ const params = {
+ FunctionName: `bulk-download-zip-creator-${process.env.NODE_ENV === "development" ? "dev" : "prod"}`,
+ InvocationType: InvocationType.RequestResponse,
+ Payload: JSON.stringify({
+ sourceBucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET,
+ fileKeys,
+ folderStructure,
+ }),
+ };
+
+ const command = new InvokeCommand(params);
+ const response = await client.send(command);
+
+ if (!response.Payload) throw new Error("Lambda returned empty payload");
+
+ const parsed = JSON.parse(new TextDecoder().decode(response.Payload));
+ const { downloadUrl } = JSON.parse(parsed.body);
+
+ res.status(200).json({ downloadUrl });
+ } catch (error) {
+ console.error("Download error:", error);
+ return res.status(500).json({
+ message: "Internal Server Error",
+ error: (error as Error).message,
+ });
+ }
+}
\ No newline at end of file
diff --git a/pages/room_ppreview_demo.tsx b/pages/room_ppreview_demo.tsx
index 65a6c28a..41b68137 100644
--- a/pages/room_ppreview_demo.tsx
+++ b/pages/room_ppreview_demo.tsx
@@ -125,6 +125,9 @@ export default function ViewPage() {
}}
dataroomId="1"
setFolderId={() => {}}
+ isPreview={false}
+ linkId="1"
+ allowDownload={false}
/>
<FolderCard
@@ -140,6 +143,9 @@ export default function ViewPage() {
}}
dataroomId="1"
setFolderId={() => {}}
+ isPreview={false}
+ linkId="1"
+ allowDownload={false}
/>
<DocumentCard