Skip to content

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

fix: bulk download if no files

Marc Seitz826ccc02736a
diff --git a/components/datarooms/groups/group-permissions.tsx b/components/datarooms/groups/group-permissions.tsx
index 01a7deae..826862de 100644
--- a/components/datarooms/groups/group-permissions.tsx
+++ b/components/datarooms/groups/group-permissions.tsx
@@ -23,6 +23,9 @@ import {
import { toast } from "sonner";
import { useDebounce } from "use-debounce";
+import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";
+import { cn } from "@/lib/utils";
+
import CloudDownloadOff from "@/components/shared/icons/cloud-download-off";
import { Button } from "@/components/ui/button";
import {
@@ -35,9 +38,6 @@ import {
} from "@/components/ui/table";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
-import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";
-import { cn } from "@/lib/utils";
-
// Update the FileOrFolder type to include permissions
type FileOrFolder = {
id: string;
@@ -453,11 +453,13 @@ export default function ExpandableTable({
// Ensure all parent folders are viewable if the item is being set to viewable
// and downloadable if the item is being set to downloadable
- if (updatedPermissions.view) {
+ if (updatedPermissions.view || updatedPermissions.download) {
parents.forEach((parent) => {
changes[parent.id] = {
- view: true, // Always enable view for parent folders
- download: parent.permissions.download, // Maintain existing download permission
+ view: true, // Always enable view for parent folders if child is viewable
+ download: updatedPermissions.download
+ ? true
+ : parent.permissions.download, // Always enable download for parent folders if child is downloadable
itemType: parent.itemType,
};
});
diff --git a/components/view/dataroom/folder-card.tsx b/components/view/dataroom/folder-card.tsx
index 746dbccd..3bb01379 100644
--- a/components/view/dataroom/folder-card.tsx
+++ b/components/view/dataroom/folder-card.tsx
@@ -58,7 +58,7 @@ export default function FolderCard({
}),
}),
{
- loading: "Downloading dataroom document...",
+ loading: "Downloading dataroom folder...",
success: async (response) => {
if (!response.ok) {
throw new Error("Failed to fetch download URL");
@@ -76,10 +76,10 @@ export default function FolderCard({
document.body.removeChild(link);
}, 100);
- return `Folder ${folder.name} downloaded successfully.`;
+ return `${folder.name} downloaded successfully.`;
},
error: (error) => {
- console.error("Error downloading file:", error);
+ console.error("Error downloading folder:", error);
return error.message || "An error occurred while downloading file.";
},
},
diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.ts
index b57a7c57..d785962f 100644
--- a/pages/api/links/download/bulk.ts
+++ b/pages/api/links/download/bulk.ts
@@ -161,24 +161,6 @@ export default async function handle(
]),
);
- // Helper function to add a file to the structure
- // const addFileToStructure = (
- // path: string,
- // fileName: string,
- // fileKey: string,
- // ) => {
- // const folderInfo = folderMap.get(path) || { name: "Root", id: null };
- // if (!folderStructure[path]) {
- // folderStructure[path] = {
- // name: folderInfo.name,
- // path: path,
- // files: [],
- // };
- // }
- // folderStructure[path].files.push({ name: fileName, key: fileKey });
- // fileKeys.push(fileKey);
- // };
-
const addFileToStructure = (
path: string,
fileName: string,
@@ -252,6 +234,10 @@ export default async function handle(
}
});
+ if (fileKeys.length === 0) {
+ return res.status(404).json({ error: "No files to download" });
+ }
+
const client = getLambdaClient();
const params = {
diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.ts
index 57224e7d..32a965ad 100644
--- a/pages/api/links/download/dataroom-folder.ts
+++ b/pages/api/links/download/dataroom-folder.ts
@@ -1,248 +1,270 @@
import { NextApiRequest, NextApiResponse } from "next";
+
import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
+import { ItemType, ViewType } from "@prisma/client";
+import slugify from "@sindresorhus/slugify";
+
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,
+ 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`);
+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" });
}
- 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" });
+ }
- 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 link does not allow download, we should not allow the download
+ if (!view.link.allowDownload) {
+ return res.status(403).json({ error: "Error downloading" });
+ }
- // if view does not exist, we should not allow the download
- if (!view) {
- return res.status(404).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 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 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 link is archived, we should not allow the download
- if (view.link.isArchived) {
- 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" });
+ }
- // 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" });
- }
+ const rootFolder = await prisma.dataroomFolder.findUnique({
+ where: {
+ id: folderId,
+ dataroomId,
+ },
+ select: { id: true, name: true, path: true },
+ });
- // 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" });
- }
+ if (!rootFolder) {
+ return res.status(404).json({ error: "Folder not found" });
+ }
- const rootFolder = await prisma.dataroomFolder.findUnique({
- where: {
- id: folderId,
- dataroomId,
+ 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,
},
- select: { id: true, name: true, path: true },
- });
+ },
+ },
+ },
+ });
+
+ // 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),
+ );
+ }
- if (!rootFolder) {
- return res.status(404).json({ error: "Folder not found" });
+ 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: [],
+ };
}
+ }
- const subfolders = await prisma.dataroomFolder.findMany({
- where: {
- dataroomId,
- path: { startsWith: rootFolder.path + "/" },
- },
- select: { id: true, name: true, path: true },
+ if (fileName && fileKey) {
+ folderStructure[currentPath].files.push({
+ name: fileName,
+ key: fileKey,
});
+ fileKeys.push(fileKey);
+ }
+ };
- 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,
- },
- },
- },
- },
- });
+ for (const folder of allFolders) {
+ const docs = allDocuments.filter((doc) => doc.folderId === folder.id);
+ if (docs.length === 0) {
+ addFileToStructure(folder.path, rootFolder, "", "");
+ continue;
+ }
- // 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: [],
- };
- }
+ 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 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,
- });
+ const rootPath = "/" + slugify(rootFolder.name);
+ if (!folderStructure[rootPath]) {
+ folderStructure[rootPath] = {
+ name: slugify(rootFolder.name),
+ path: rootPath,
+ files: [],
+ };
}
-}
\ No newline at end of file
+
+ 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,
+ });
+ }
+}