Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Downalod dataroom
Ashish Viradiya2a7afd47a5f3
diff --git a/components/datarooms/dataroom-header.tsx b/components/datarooms/dataroom-header.tsxindex 1be3693d..84b71d73 100644--- a/components/datarooms/dataroom-header.tsx+++ b/components/datarooms/dataroom-header.tsx@@ -1,10 +1,18 @@+import { useRouter } from "next/router";+import { useState } from "react";+import { useTeam } from "@/context/team-context";+import { DownloadIcon } from "lucide-react";+import { toast } from "sonner";+import LinkSheet from "@/components/links/link-sheet";import { Button } from "@/components/ui/button";import { useDataroomLinks } from "@/lib/swr/use-dataroom";+import { ButtonTooltip } from "../ui/tooltip";+export const DataroomHeader = ({title,description,@@ -14,8 +22,12 @@ export const DataroomHeader = ({description: string;actions?: React.ReactNode[];}) => {+ const router = useRouter();+ const dataroomId = router.query.id as string;const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);const { links } = useDataroomLinks();+ const [loading, setLoading] = useState<boolean>(false);+ const teamInfo = useTeam();const actionRows: React.ReactNode[][] = [];if (actions) {@@ -24,6 +36,41 @@ export const DataroomHeader = ({}}+ const downloadDataroom = async () => {+ setLoading(true);+ try {+ toast.promise(+ fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/download/bulk`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ },+ ),+ {+ loading: "Downloading dataroom...",+ success: async (response) => {+ const { downloadUrl } = await response.json();+ window.open(downloadUrl, "_blank");+ return "Dataroom downloaded successfully.";+ },+ error: (error) => {+ console.log(error);+ return (+ error.message || "An error occurred while downloading dataroom."+ );+ },+ },+ );+ } catch (error) {+ console.error(error);+ } finally {+ setLoading(false);+ }+ };+return (<section className="mb-4"><div className="flex items-center justify-between">@@ -33,6 +80,16 @@ export const DataroomHeader = ({</h1></div><div className="flex items-center gap-x-1">+ <ButtonTooltip content="Download Dataroom" sideOffset={4}>+ <Button+ onClick={downloadDataroom}+ className="m-1 bg-gray-900 text-white hover:bg-gray-900/80"+ size="icon"+ loading={loading}+ >+ <DownloadIcon className="h-5 w-5" />+ </Button>+ </ButtonTooltip><Button onClick={() => setIsLinkSheetOpen(true)} key={1}>Share</Button>diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.tsnew file mode 100644index 00000000..ac95ecbd--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts@@ -0,0 +1,222 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";+import { ItemType, PrismaClient, ViewType } from "@prisma/client";+import { getServerSession } from "next-auth";++import { getLambdaClient } from "@/lib/files/aws-client";+import { CustomUser } from "@/lib/types";++const prisma = new PrismaClient();++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: dataroomId } = req.query as {+ teamId: string;+ id: string;+ };++ if (req.method === "POST") {+ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: (session.user as CustomUser).id,+ },+ },+ },+ select: {+ id: true,+ },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId: teamId,+ },+ select: {+ folders: {+ select: {+ id: true,+ name: true,+ path: true,+ },+ },+ documents: {+ select: {+ id: true,+ folderId: true,+ document: {+ select: {+ name: true,+ versions: {+ where: { isPrimary: true },+ select: {+ type: true,+ file: true,+ storageType: true,+ originalFile: true,+ contentType: true,+ },+ take: 1,+ },+ },+ },+ },+ },+ },+ });+ if (!dataroom) {+ return res.status(404).end("Dataroom not found");+ }+ let downloadFolders = dataroom.folders;+ let downloadDocuments = dataroom.documents;++ // Construct folderStructure and fileKeys+ const folderStructure: {+ [key: string]: {+ name: string;+ path: string;+ files: { name: string; key: string }[];+ };+ } = {};+ const fileKeys: string[] = [];+ const folderMap = new Map(+ downloadFolders.map((folder) => [+ folder.path,+ { name: folder.name, id: folder.id },+ ]),+ );+ const addFileToStructure = (+ path: string,+ fileName: string,+ fileKey: string,+ ) => {+ const pathParts = path.split("/").filter(Boolean);+ let currentPath = "";++ // Add folder information for each level of the path+ pathParts.forEach((part, index) => {+ currentPath += "/" + part;+ const folderInfo = folderMap.get(currentPath);+ if (!folderStructure[currentPath]) {+ folderStructure[currentPath] = {+ name: folderInfo ? folderInfo.name : part,+ path: currentPath,+ files: [],+ };+ }+ });++ // Add the file to the leaf folder+ if (!folderStructure[path]) {+ const folderInfo = folderMap.get(path) || {+ name: "Root",+ id: null,+ };+ folderStructure[path] = {+ name: folderInfo.name,+ path: path,+ files: [],+ };+ }+ folderStructure[path].files.push({ name: fileName, key: fileKey });+ fileKeys.push(fileKey);+ };+ downloadDocuments+ .filter((doc) => !doc.folderId)+ .filter((doc) => doc.document.versions[0].type !== "notion")+ .filter((doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB")+ .forEach((doc) =>+ addFileToStructure(+ "/",+ doc.document.name,+ doc.document.versions[0].originalFile ??+ doc.document.versions[0].file,+ ),+ );+ downloadFolders.forEach((folder) => {+ const folderDocs = downloadDocuments+ .filter((doc) => doc.folderId === folder.id)+ .filter((doc) => doc.document.versions[0].type !== "notion")+ .filter(+ (doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB",+ );++ folderDocs &&+ folderDocs.forEach((doc) =>+ addFileToStructure(+ folder.path,+ doc.document.name,+ doc.document.versions[0].originalFile ??+ doc.document.versions[0].file,+ ),+ );++ // If the folder is empty, ensure it's still added to the structure+ if (folderDocs && folderDocs.length === 0) {+ addFileToStructure(folder.path, "", "");+ }+ });+ console.log("downloadFolders", { folderStructure, fileKeys });++ const client = getLambdaClient();++ const params = {+ FunctionName: `bulk-download-zip-creator-${process.env.NODE_ENV === "development" ? "dev" : "prod"}`, // Use the name you gave your Lambda function+ InvocationType: InvocationType.RequestResponse,+ Payload: JSON.stringify({+ sourceBucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET,+ fileKeys: fileKeys,+ folderStructure: folderStructure,+ }),+ };++ try {+ const command = new InvokeCommand(params);+ const response = await client.send(command);++ if (response.Payload) {+ const decodedPayload = new TextDecoder().decode(response.Payload);++ const payload = JSON.parse(decodedPayload);+ const { downloadUrl } = JSON.parse(payload.body);++ res.status(200).json({ downloadUrl });+ } else {+ throw new Error("Payload is undefined or empty");+ }+ } catch (error) {+ console.error("Error invoking Lambda:", error);+ res.status(500).json({+ error: "Failed to generate download link",+ details: (error as Error).message,+ });+ }+ } catch (error) {+ return res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}