Skip to content

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

refactor: improve dataroom download

Marc Seitz27f5998acf92
diff --git a/components/datarooms/actions/download-dataroom.tsx b/components/datarooms/actions/download-dataroom.tsx
index ea1c6cf7..108aaa0c 100644
--- a/components/datarooms/actions/download-dataroom.tsx
+++ b/components/datarooms/actions/download-dataroom.tsx
@@ -1,68 +1,49 @@
import { useState } from "react";
import { DownloadIcon } from "lucide-react";
-import { toast } from "sonner";
+import { DownloadProgressModal } from "@/components/datarooms/download-progress-modal";
import { ResponsiveButton } from "@/components/ui/responsive-button";
export default function DownloadDataroomButton({
teamId,
dataroomId,
+ dataroomName,
}: {
teamId: string;
dataroomId: string;
+ dataroomName?: string;
}) {
- const [isLoading, setIsLoading] = useState(false);
+ const [showDownloadModal, setShowDownloadModal] = useState(false);
- const downloadDataroom = async () => {
- setIsLoading(true);
- try {
- toast.promise(
- fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- }),
- {
- loading: "Downloading dataroom...",
- success: async (response) => {
- 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);
+ const openDownloadModal = () => {
+ // Open the modal - it will show existing downloads and allow starting new ones
+ setShowDownloadModal(true);
+ };
- return "Dataroom downloaded successfully.";
- },
- error: (error) => {
- console.log(error);
- return (
- error.message || "An error occurred while downloading dataroom."
- );
- },
- },
- );
- } catch (error) {
- console.error(error);
- } finally {
- setIsLoading(false);
- }
+ const handleCloseDownloadModal = () => {
+ setShowDownloadModal(false);
};
+
return (
- <ResponsiveButton
- icon={<DownloadIcon className="h-4 w-4" />}
- text="Download"
- onClick={downloadDataroom}
- variant="outline"
- size="sm"
- loading={isLoading}
- />
+ <>
+ <ResponsiveButton
+ icon={<DownloadIcon className="h-4 w-4" />}
+ text="Download"
+ onClick={openDownloadModal}
+ variant="outline"
+ size="sm"
+ />
+
+ {/* Download Progress Modal */}
+ <DownloadProgressModal
+ isOpen={showDownloadModal}
+ onClose={handleCloseDownloadModal}
+ jobId={null}
+ dataroomName={dataroomName}
+ teamId={teamId}
+ dataroomId={dataroomId}
+ />
+ </>
);
}
diff --git a/components/datarooms/download-progress-modal.tsx b/components/datarooms/download-progress-modal.tsx
new file mode 100644
index 00000000..ddaa2c56
--- /dev/null
+++ b/components/datarooms/download-progress-modal.tsx
@@ -0,0 +1,601 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import {
+ AlertCircle,
+ CheckCircle2,
+ Download,
+ FileArchive,
+ Loader2,
+ Plus,
+ XCircle,
+} from "lucide-react";
+
+import { DownloadJob } from "@/lib/redis-download-job-store";
+import { cn } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Progress } from "@/components/ui/progress";
+
+export interface DownloadJobStatus {
+ id: string;
+ status: "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
+ progress: number;
+ totalFiles: number;
+ processedFiles: number;
+ downloadUrls?: string[];
+ error?: string;
+ isReady: boolean;
+ dataroomName: string;
+ createdAt: string;
+ completedAt?: string;
+ expiresAt?: string;
+}
+
+interface DownloadProgressModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ jobId: string | null;
+ dataroomName?: string;
+ // For team member downloads (uses next-auth session)
+ teamId: string;
+ dataroomId: string;
+}
+
+export function DownloadProgressModal({
+ isOpen,
+ onClose,
+ jobId,
+ dataroomName,
+ teamId,
+ dataroomId,
+}: DownloadProgressModalProps) {
+ const [status, setStatus] = useState<DownloadJobStatus | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [isPolling, setIsPolling] = useState(false);
+ const [existingDownloads, setExistingDownloads] = useState<DownloadJob[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [showNewDownload, setShowNewDownload] = useState(false);
+ const [isStartingDownload, setIsStartingDownload] = useState(false);
+ const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
+
+ // Cleanup interval on component unmount
+ useEffect(() => {
+ return () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
+ };
+ }, []);
+
+ // Fetch existing downloads when modal opens
+ useEffect(() => {
+ if (!isOpen || !teamId || !dataroomId) return;
+
+ const fetchExistingDownloads = async () => {
+ try {
+ setLoading(true);
+
+ const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/jobs`;
+
+ const response = await fetch(endpoint, {
+ method: "GET",
+ credentials: "include",
+ });
+
+ if (response.ok) {
+ const downloads = await response.json();
+ setExistingDownloads(downloads);
+
+ // If we have a current jobId, show the new download view
+ if (jobId) {
+ setShowNewDownload(true);
+ }
+ } else {
+ console.error("Failed to fetch existing downloads");
+ }
+ } catch (error) {
+ console.error("Error fetching existing downloads:", error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ fetchExistingDownloads();
+ }, [isOpen, dataroomId, teamId, jobId]);
+
+ const fetchStatus = useCallback(
+ async (statusJobId: string) => {
+ if (!statusJobId || !teamId || !dataroomId) return;
+
+ try {
+ const url = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${statusJobId}`;
+
+ const response = await fetch(url, {
+ credentials: "include",
+ });
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to fetch download status");
+ }
+ const data = await response.json();
+ setStatus(data);
+ setError(null);
+
+ // Stop polling when job is completed or failed
+ if (data.status === "COMPLETED" || data.status === "FAILED") {
+ setIsPolling(false);
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "An error occurred");
+ setIsPolling(false);
+ }
+ },
+ [teamId, dataroomId],
+ );
+
+ // Start polling when we have a jobId and showNewDownload is true
+ useEffect(() => {
+ if (isOpen && jobId && showNewDownload) {
+ setIsPolling(true);
+ setStatus(null);
+ setError(null);
+ fetchStatus(jobId);
+
+ // Start polling interval
+ pollIntervalRef.current = setInterval(() => fetchStatus(jobId), 2000);
+ }
+
+ return () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ };
+ }, [isOpen, jobId, showNewDownload, fetchStatus]);
+
+ const startNewDownload = async () => {
+ if (!teamId || !dataroomId) {
+ setError("Missing required parameters to start download");
+ return;
+ }
+
+ setIsStartingDownload(true);
+ setShowNewDownload(true);
+
+ try {
+ const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`;
+
+ const response = await fetch(endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to start download");
+ }
+
+ if (data.jobId) {
+ // Start polling for this job
+ setStatus({
+ id: data.jobId,
+ status: data.status || "PENDING",
+ progress: 0,
+ totalFiles: 0,
+ processedFiles: 0,
+ isReady: false,
+ dataroomName: dataroomName || "",
+ createdAt: new Date().toISOString(),
+ });
+ setIsPolling(true);
+
+ const statusUrl = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${data.jobId}`;
+
+ pollIntervalRef.current = setInterval(async () => {
+ const statusResponse = await fetch(statusUrl, {
+ credentials: "include",
+ });
+ if (statusResponse.ok) {
+ const statusData = await statusResponse.json();
+ setStatus(statusData);
+
+ if (
+ statusData.status === "COMPLETED" ||
+ statusData.status === "FAILED"
+ ) {
+ setIsPolling(false);
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ }
+ }
+ }, 2000);
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "An error occurred");
+ setShowNewDownload(false);
+ } finally {
+ setIsStartingDownload(false);
+ }
+ };
+
+ const handleDownload = (url: string) => {
+ const link = document.createElement("a");
+ link.href = url;
+ link.rel = "noopener noreferrer";
+ document.body.appendChild(link);
+ link.click();
+ setTimeout(() => {
+ document.body.removeChild(link);
+ }, 100);
+ };
+
+ const handleDownloadAll = async (urls: string[]) => {
+ // Download files sequentially with longer delays to avoid browser blocking
+ // Browsers typically block rapid automatic downloads as a security measure
+ console.log("Downloading all files:", urls);
+ for (let i = 0; i < urls.length; i++) {
+ handleDownload(urls[i]);
+ // Wait 1.5 seconds between downloads to avoid browser blocking
+ if (i < urls.length - 1) {
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ }
+ }
+ };
+
+ const handleClose = () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ setStatus(null);
+ setError(null);
+ setIsPolling(false);
+ setShowNewDownload(false);
+ setExistingDownloads([]);
+ setLoading(true);
+ onClose();
+ };
+
+ const getStatusIcon = (jobStatus?: string) => {
+ switch (jobStatus) {
+ case "PENDING":
+ return (
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ );
+ case "PROCESSING":
+ return <FileArchive className="h-4 w-4 animate-pulse text-primary" />;
+ case "COMPLETED":
+ return <CheckCircle2 className="h-4 w-4 text-green-500" />;
+ case "FAILED":
+ return <XCircle className="h-4 w-4 text-destructive" />;
+ default:
+ return (
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ );
+ }
+ };
+
+ const getStatusColor = (jobStatus: string) => {
+ switch (jobStatus) {
+ case "COMPLETED":
+ return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300";
+ case "PROCESSING":
+ return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300";
+ case "PENDING":
+ return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300";
+ case "FAILED":
+ return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300";
+ default:
+ return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300";
+ }
+ };
+
+ const formatDate = (dateString: string) => {
+ return new Date(dateString).toLocaleString();
+ };
+
+ const formatExpirationTime = (expiresAt?: string) => {
+ if (!expiresAt) return null;
+
+ const expires = new Date(expiresAt);
+ const now = new Date();
+ const diffMs = expires.getTime() - now.getTime();
+ const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
+ const diffDays = Math.floor(diffHours / 24);
+
+ if (diffDays > 0) {
+ return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
+ } else if (diffHours > 0) {
+ return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
+ }
+ return "less than an hour";
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ Download {dataroomName || status?.dataroomName || "Dataroom"}
+ </DialogTitle>
+ <DialogDescription>
+ {showNewDownload
+ ? status?.status === "COMPLETED"
+ ? "Your files are ready to download."
+ : "Please wait while we prepare your files..."
+ : "View previous downloads or start a new one."}
+ </DialogDescription>
+ </DialogHeader>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
+ </div>
+ ) : showNewDownload ? (
+ // Show download progress
+ <div className="flex flex-col items-center space-y-4 py-6">
+ {/* Status Icon */}
+ <div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted">
+ {status?.status === "COMPLETED" ? (
+ <CheckCircle2 className="h-8 w-8 text-green-500" />
+ ) : status?.status === "FAILED" ? (
+ <XCircle className="h-8 w-8 text-destructive" />
+ ) : (
+ <FileArchive className="h-8 w-8 animate-pulse text-primary" />
+ )}
+ </div>
+
+ {/* Status Message */}
+ <p
+ className={cn(
+ "text-center text-sm",
+ status?.status === "FAILED"
+ ? "text-destructive"
+ : "text-muted-foreground",
+ )}
+ >
+ {!status
+ ? "Starting download..."
+ : status.status === "PENDING"
+ ? "Preparing your download..."
+ : status.status === "PROCESSING"
+ ? `Processing ${status.processedFiles} of ${status.totalFiles} files...`
+ : status.status === "COMPLETED"
+ ? status.downloadUrls && status.downloadUrls.length > 1
+ ? `Your download is ready! ${status.downloadUrls.length} ZIP files have been created.`
+ : "Your download is ready!"
+ : status.error || "Download failed. Please try again."}
+ </p>
+
+ {/* Progress Bar */}
+ {(status?.status === "PROCESSING" ||
+ status?.status === "PENDING") && (
+ <div className="w-full space-y-2">
+ <Progress
+ value={status?.progress || 0}
+ text={`${status?.progress || 0}%`}
+ className="h-4"
+ />
+ <p className="text-center text-xs text-muted-foreground">
+ {status?.totalFiles
+ ? `${status.processedFiles || 0} / ${status.totalFiles} files`
+ : "Calculating..."}
+ </p>
+ </div>
+ )}
+
+ {/* Download Links */}
+ {status?.status === "COMPLETED" && status.downloadUrls && (
+ <div className="w-full space-y-3">
+ {status.downloadUrls.length === 1 ? (
+ <Button
+ className="w-full"
+ onClick={() => handleDownload(status.downloadUrls![0])}
+ >
+ <Download className="mr-2 h-4 w-4" />
+ Download ZIP
+ </Button>
+ ) : (
+ <>
+ {status.downloadUrls.length <= 3 ? (
+ <Button
+ className="w-full"
+ onClick={() => handleDownloadAll(status.downloadUrls!)}
+ >
+ <Download className="mr-2 h-4 w-4" />
+ Download All ({status.downloadUrls.length} files)
+ </Button>
+ ) : (
+ <p className="text-center text-xs text-muted-foreground">
+ Your download has been split into{" "}
+ {status.downloadUrls.length} parts. Download each part
+ below:
+ </p>
+ )}
+ <div className="space-y-2">
+ {status.downloadUrls.length <= 3 && (
+ <p className="text-xs text-muted-foreground">
+ Or download individually:
+ </p>
+ )}
+ <div className="max-h-48 space-y-1 overflow-y-auto">
+ {status.downloadUrls.map((url, index) => (
+ <Button
+ key={index}
+ variant={
+ status.downloadUrls!.length > 3
+ ? "default"
+ : "outline"
+ }
+ size="sm"
+ className="w-full justify-start"
+ onClick={() => handleDownload(url)}
+ >
+ <FileArchive className="mr-2 h-3 w-3" />
+ Part {index + 1} of {status.downloadUrls!.length}
+ </Button>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Expiration Notice */}
+ {status.expiresAt && (
+ <div className="flex items-center justify-center gap-1 text-xs text-muted-foreground">
+ <AlertCircle className="h-3 w-3" />
+ <span>
+ Download expires in{" "}
+ {formatExpirationTime(status.expiresAt)}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Error State */}
+ {status?.status === "FAILED" && (
+ <Button
+ variant="outline"
+ onClick={() => setShowNewDownload(false)}
+ >
+ Back to Downloads
+ </Button>
+ )}
+
+ {/* Back button for processing state */}
+ {(status?.status === "PROCESSING" ||
+ status?.status === "PENDING") && (
+ <DialogFooter className="w-full sm:justify-center">
+ <p className="text-xs text-muted-foreground">
+ You can close this dialog. We&apos;ll notify you when your
+ download is ready.
+ </p>
+ </DialogFooter>
+ )}
+
+ {/* Loading Error */}
+ {error && (
+ <div className="flex items-center gap-2 text-sm text-destructive">
+ <AlertCircle className="h-4 w-4" />
+ <span>{error}</span>
+ </div>
+ )}
+ </div>
+ ) : (
+ // Show existing downloads and new download option
+ <div className="space-y-4 py-2">
+ {existingDownloads.length > 0 ? (
+ <div className="space-y-3">
+ <h4 className="text-sm font-medium">Recent Downloads</h4>
+ <div className="max-h-64 space-y-2 overflow-y-auto">
+ {existingDownloads.map((download) => (
+ <div
+ key={download.id}
+ className="flex items-center justify-between rounded-md border p-3"
+ >
+ <div className="flex-1 space-y-1">
+ <div className="flex items-center gap-2">
+ {getStatusIcon(download.status)}
+ <span
+ className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${getStatusColor(download.status)}`}
+ >
+ {download.status}
+ </span>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {formatDate(download.createdAt)}
+ </div>
+ {download.totalFiles > 0 && (
+ <div className="text-xs text-muted-foreground">
+ {download.totalFiles} files
+ {download.downloadUrls &&
+ download.downloadUrls.length > 1 &&
+ ` (${download.downloadUrls.length} ZIPs)`}
+ </div>
+ )}
+ {download.expiresAt && (
+ <div className="flex items-center gap-1 text-xs text-muted-foreground">
+ <AlertCircle className="h-3 w-3" />
+ Expires in{" "}
+ {formatExpirationTime(download.expiresAt)}
+ </div>
+ )}
+ {download.error && (
+ <p className="text-xs text-destructive">
+ {download.error}
+ </p>
+ )}
+ </div>
+ {download.status === "COMPLETED" &&
+ download.downloadUrls &&
+ download.downloadUrls.length > 0 && (
+ <Button
+ size="sm"
+ onClick={() =>
+ download.downloadUrls!.length === 1
+ ? handleDownload(download.downloadUrls![0])
+ : handleDownloadAll(download.downloadUrls!)
+ }
+ >
+ <Download className="mr-1 h-3 w-3" />
+ {download.downloadUrls.length === 1
+ ? "Download"
+ : `Download (${download.downloadUrls.length})`}
+ </Button>
+ )}
+ {(download.status === "PENDING" ||
+ download.status === "PROCESSING") && (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {download.progress}%
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <div className="py-4 text-center text-sm text-muted-foreground">
+ No previous downloads found
+ </div>
+ )}
+
+ <div className="border-t pt-4">
+ <Button
+ className="w-full"
+ onClick={startNewDownload}
+ disabled={isStartingDownload}
+ >
+ {isStartingDownload ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="mr-2 h-4 w-4" />
+ )}
+ Start New Download
+ </Button>
+ </div>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/emails/download-ready.tsx b/components/emails/download-ready.tsx
new file mode 100644
index 00000000..2a5d1cdc
--- /dev/null
+++ b/components/emails/download-ready.tsx
@@ -0,0 +1,105 @@
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Html,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+import { Footer } from "./shared/footer";
+
+function formatExpirationTime(expiresAt?: string): string {
+ if (!expiresAt) return "3 days";
+
+ const expires = new Date(expiresAt);
+ const now = new Date();
+ const diffMs = expires.getTime() - now.getTime();
+ const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
+ const diffDays = Math.floor(diffHours / 24);
+
+ if (diffDays > 0) {
+ return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
+ } else if (diffHours > 0) {
+ return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
+ }
+ return "less than an hour";
+}
+
+export default function DownloadReady({
+ dataroomName = "Dataroom",
+ downloadUrl = "https://app.papermark.com",
+ email = "[email protected]",
+ expiresAt,
+}: {
+ dataroomName?: string;
+ downloadUrl?: string;
+ email: string;
+ expiresAt?: string;
+}) {
+ const expirationTime = formatExpirationTime(expiresAt);
+
+ return (
+ <Html>
+ <Head />
+ <Preview>Your {dataroomName} download is ready</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 w-[465px] p-5">
+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ Your download of <strong>{dataroomName}</strong> is ready!
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ Click the button below to download your files. You&apos;ll need to
+ be logged in to your Papermark account to access the download.
+ </Text>
+
+ <Section className="my-8 text-center">
+ <Button
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ href={downloadUrl}
+ style={{ padding: "12px 20px" }}
+ >
+ Download Files
+ </Button>
+ </Section>
+
+ <Text className="text-sm leading-6 text-black">
+ Download details:
+ </Text>
+ <ul className="break-all text-sm leading-6 text-black">
+ <li className="text-sm leading-6 text-black">
+ Dataroom: {dataroomName}
+ </li>
+ <li className="text-sm leading-6 text-black">
+ Expires: in {expirationTime}
+ </li>
+ </ul>
+ <Text className="text-sm leading-6 text-black">
+ Best,
+ <br />
+ The Papermark Team
+ </Text>
+ <Footer
+ footerText={
+ <>
+ This email was intended for{" "}
+ <span className="text-black">{email}</span>. If you were not
+ expecting this email, you can ignore this email. If you have
+ any feedback or questions about this email, simply reply to
+ it.
+ </>
+ }
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/lib/emails/send-download-ready-email.ts b/lib/emails/send-download-ready-email.ts
new file mode 100644
index 00000000..c29952e7
--- /dev/null
+++ b/lib/emails/send-download-ready-email.ts
@@ -0,0 +1,35 @@
+import { sendEmail } from "@/lib/resend";
+
+import DownloadReady from "@/components/emails/download-ready";
+
+export const sendDownloadReadyEmail = async ({
+ to,
+ dataroomName,
+ downloadUrl,
+ expiresAt,
+}: {
+ to: string;
+ dataroomName: string;
+ downloadUrl: string;
+ expiresAt?: string;
+}) => {
+ const emailTemplate = DownloadReady({
+ dataroomName,
+ downloadUrl,
+ email: to,
+ expiresAt,
+ });
+
+ try {
+ await sendEmail({
+ to,
+ subject: `Your ${dataroomName} download is ready`,
+ react: emailTemplate,
+ test: process.env.NODE_ENV === "development",
+ system: true,
+ });
+ } catch (e) {
+ console.error("Error sending download ready email:", e);
+ throw e;
+ }
+};
diff --git a/lib/redis-download-job-store.ts b/lib/redis-download-job-store.ts
new file mode 100644
index 00000000..9bf79943
--- /dev/null
+++ b/lib/redis-download-job-store.ts
@@ -0,0 +1,156 @@
+import { nanoid } from "@/lib/utils";
+
+import { redis } from "./redis";
+
+export type DownloadJobStatus =
+ | "PENDING"
+ | "PROCESSING"
+ | "COMPLETED"
+ | "FAILED";
+
+export interface DownloadJob {
+ id: string;
+ type: "bulk" | "folder";
+ status: DownloadJobStatus;
+ dataroomId: string;
+ dataroomName: string;
+ totalFiles: number;
+ processedFiles: number;
+ progress: number; // 0-100
+ downloadUrls?: string[]; // Multiple ZIPs if large (S3 presigned URLs auto-expire)
+ error?: string;
+ teamId: string;
+ userId: string;
+ triggerRunId?: string; // Trigger.dev run ID for cancellation
+ createdAt: string;
+ updatedAt: string;
+ completedAt?: string;
+ expiresAt?: string; // When download links expire
+ emailNotification?: boolean;
+ emailAddress?: string;
+}
+
+const JOB_PREFIX = "download_job:";
+const TEAM_JOBS_PREFIX = "team_download_jobs:";
+const JOB_TTL = 60 * 60 * 24 * 3; // 3 days - Redis handles cleanup via TTL
+
+export class RedisDownloadJobStore {
+ private getJobKey(jobId: string): string {
+ return `${JOB_PREFIX}${jobId}`;
+ }
+
+ private getTeamJobsKey(teamId: string): string {
+ return `${TEAM_JOBS_PREFIX}${teamId}`;
+ }
+
+ async createJob(
+ jobData: Omit<DownloadJob, "id" | "createdAt" | "updatedAt">,
+ ): Promise<DownloadJob> {
+ const jobId = nanoid();
+ const now = new Date().toISOString();
+
+ const job: DownloadJob = {
+ ...jobData,
+ id: jobId,
+ createdAt: now,
+ updatedAt: now,
+ };
+
+ const jobKey = this.getJobKey(jobId);
+ const teamJobsKey = this.getTeamJobsKey(jobData.teamId);
+
+ // Store job data with TTL (Redis handles cleanup)
+ await redis.setex(jobKey, JOB_TTL, JSON.stringify(job));
+
+ // Add to team's job list (sorted by creation time)
+ await redis.zadd(teamJobsKey, { score: Date.now(), member: jobId });
+ await redis.expire(teamJobsKey, JOB_TTL);
+
+ return job;
+ }
+
+ async getJob(jobId: string): Promise<DownloadJob | null> {
+ const jobKey = this.getJobKey(jobId);
+ const jobData = await redis.get(jobKey);
+
+ if (!jobData) {
+ return null;
+ }
+
+ try {
+ // Check if data is already an object (Redis client auto-parsed)
+ if (typeof jobData === "object") {
+ return jobData as DownloadJob;
+ }
+ // Otherwise parse the JSON string
+ return JSON.parse(jobData as string);
+ } catch (error) {
+ console.error("Error parsing download job data:", error);
+ return null;
+ }
+ }
+
+ async updateJob(
+ jobId: string,
+ updates: Partial<DownloadJob>,
+ ): Promise<DownloadJob | null> {
+ const job = await this.getJob(jobId);
+ if (!job) {
+ return null;
+ }
+
+ const updatedJob: DownloadJob = {
+ ...job,
+ ...updates,
+ updatedAt: new Date().toISOString(),
+ };
+
+ const jobKey = this.getJobKey(jobId);
+ await redis.setex(jobKey, JOB_TTL, JSON.stringify(updatedJob));
+
+ return updatedJob;
+ }
+
+ private async getTeamJobs(
+ teamId: string,
+ limit: number = 20,
+ ): Promise<DownloadJob[]> {
+ const teamJobsKey = this.getTeamJobsKey(teamId);
+
+ // Get job IDs sorted by creation time (newest first)
+ const jobIds = await redis.zrange(teamJobsKey, 0, limit - 1, { rev: true });
+
+ if (!jobIds.length) {
+ return [];
+ }
+
+ // Get all job data
+ const jobs = await Promise.all(
+ (jobIds as string[]).map((jobId: string) => this.getJob(jobId)),
+ );
+
+ // Filter out null values (expired jobs)
+ return jobs.filter(
+ (job: DownloadJob | null): job is DownloadJob => job !== null,
+ );
+ }
+
+ async getDataroomJobs(
+ dataroomId: string,
+ teamId: string,
+ limit: number = 10,
+ ): Promise<DownloadJob[]> {
+ const teamJobs = await this.getTeamJobs(teamId, limit * 2); // Get more to filter
+
+ // Filter jobs by dataroom
+ return teamJobs
+ .filter((job) => {
+ const matchesDataroom = job.dataroomId === dataroomId;
+ const matchStatus = job.status !== "FAILED";
+ return matchesDataroom && matchStatus;
+ })
+ .slice(0, limit);
+ }
+}
+
+export const downloadJobStore = new RedisDownloadJobStore();
diff --git a/lib/trigger/bulk-download.ts b/lib/trigger/bulk-download.ts
new file mode 100644
index 00000000..245a4455
--- /dev/null
+++ b/lib/trigger/bulk-download.ts
@@ -0,0 +1,534 @@
+import { logger, task } from "@trigger.dev/sdk/v3";
+
+import { sendDownloadReadyEmail } from "@/lib/emails/send-download-ready-email";
+import { downloadJobStore } from "@/lib/redis-download-job-store";
+
+// Maximum files per batch (Lambda payload limit)
+const MAX_FILES_PER_BATCH = 500;
+// Maximum size for a single ZIP file (500MB to stay within Vercel's 5min timeout)
+// Lambda needs time to: read from S3 + create ZIP + upload to S3
+// Conservative estimate: ~500MB can be processed in ~2-3 minutes
+const MAX_ZIP_SIZE_BYTES = 500 * 1024 * 1024;
+
+/**
+ * Generate a UTC timestamp in the format: "20260202T131428Z"
+ * @returns Formatted UTC timestamp
+ */
+function generateTimestamp(): string {
+ return new Date()
+ .toISOString()
+ .replace(/[-:]/g, "")
+ .replace(/\.\d{3}/, "");
+}
+
+/**
+ * Generate a zip filename in the format: "Dataroom Name-20260202T131428Z"
+ * @param dataroomName - The name of the dataroom
+ * @param timestamp - The UTC timestamp (shared across all parts)
+ * @param partNumber - The part number (1-indexed) (optional)
+ * @returns Formatted zip filename without extension
+ */
+function generateZipFileName(
+ dataroomName: string,
+ timestamp: string,
+ partNumber?: number,
+): string {
+ // Zero-pad part number to 3 digits
+ const paddedPart = partNumber?.toString().padStart(3, "0") ?? "";
+
+ return `${dataroomName}-${timestamp}${paddedPart ? `-${paddedPart}` : ""}`;
+}
+
+export type BulkDownloadPayload = {
+ jobId: string;
+ dataroomId: string;
+ dataroomName: string;
+ teamId: string;
+ folderStructure: {
+ [key: string]: {
+ name: string;
+ path: string;
+ files: {
+ name: string;
+ key: string;
+ type?: string;
+ numPages?: number;
+ needsWatermark?: boolean;
+ size?: number; // File size in bytes
+ }[];
+ };
+ };
+ fileKeys: string[];
+ sourceBucket: string;
+ watermarkConfig?: {
+ enabled: boolean;
+ config?: any;
+ viewerData?: {
+ email?: string | null;
+ date?: string;
+ time?: string;
+ link?: string | null;
+ ipAddress?: string;
+ };
+ };
+ viewId?: string;
+ viewerId?: string;
+ viewerEmail?: string;
+ linkId?: string;
+ userId?: string;
+ emailNotification?: boolean;
+ emailAddress?: string;
+};
+
+export const bulkDownloadTask = task({
+ id: "bulk-download",
+ retry: { maxAttempts: 2 },
+ machine: { preset: "large-1x" }, // 4 vCPU, 8GB RAM for orchestration
+ run: async (payload: BulkDownloadPayload) => {
+ const {
+ jobId,
+ dataroomId,
+ dataroomName,
+ teamId,
+ folderStructure,
+ fileKeys,
+ sourceBucket,
+ watermarkConfig,
+ viewId,
+ viewerEmail,
+ emailNotification,
+ emailAddress,
+ } = payload;
+
+ logger.info("Starting bulk download task", {
+ jobId,
+ dataroomId,
+ dataroomName,
+ totalFiles: fileKeys.length,
+ });
+
+ // Generate timestamp once for all parts of this download
+ const downloadTimestamp = generateTimestamp();
+
+ try {
+ // Update job status to processing
+ await downloadJobStore.updateJob(jobId, {
+ status: "PROCESSING",
+ processedFiles: 0,
+ progress: 0,
+ });
+
+ // For small datarooms, process in a single batch
+ if (fileKeys.length <= MAX_FILES_PER_BATCH) {
+ logger.info("Processing as single batch", {
+ jobId,
+ fileCount: fileKeys.length,
+ });
+
+ const downloadUrl = await processDownloadBatch({
+ teamId,
+ folderStructure,
+ fileKeys,
+ sourceBucket,
+ watermarkConfig,
+ dataroomName,
+ zipPartNumber: 1,
+ totalParts: 1,
+ zipFileName: generateZipFileName(dataroomName, downloadTimestamp),
+ });
+
+ // Update job with completed status
+ const completedJob = await downloadJobStore.updateJob(jobId, {
+ status: "COMPLETED",
+ processedFiles: fileKeys.length,
+ progress: 100,
+ downloadUrls: [downloadUrl],
+ completedAt: new Date().toISOString(),
+ expiresAt: new Date(
+ Date.now() + 3 * 24 * 60 * 60 * 1000,
+ ).toISOString(), // 3 days
+ });
+
+ // Send email notification if requested
+ if (emailNotification && emailAddress && completedJob) {
+ await sendEmailNotification({
+ emailAddress,
+ dataroomName,
+ jobId,
+ teamId,
+ dataroomId,
+ expiresAt: completedJob.expiresAt,
+ });
+ }
+
+ logger.info("Bulk download task completed successfully", {
+ jobId,
+ downloadUrls: [downloadUrl],
+ });
+
+ return {
+ success: true,
+ jobId,
+ downloadUrls: [downloadUrl],
+ };
+ }
+
+ // For large datarooms, split into batches
+ logger.info("Processing as multiple batches", {
+ jobId,
+ fileCount: fileKeys.length,
+ maxFilesPerBatch: MAX_FILES_PER_BATCH,
+ maxSizePerBatch: `${MAX_ZIP_SIZE_BYTES / (1024 * 1024)}MB`,
+ });
+
+ // Split files into batches
+ const batches = splitFilesIntoBatches(folderStructure, fileKeys);
+ const totalBatches = batches.length;
+ const downloadUrls: string[] = [];
+
+ logger.info("Created file batches", {
+ jobId,
+ totalBatches,
+ batchDetails: batches.map((b, i) => ({
+ batch: i + 1,
+ files: b.fileKeys.length,
+ sizeBytes: b.totalSize,
+ sizeMB: Math.round(b.totalSize / (1024 * 1024)),
+ })),
+ });
+
+ // Process each batch sequentially (to avoid Lambda concurrency issues)
+ for (let i = 0; i < batches.length; i++) {
+ const batch = batches[i];
+ const batchNumber = i + 1;
+
+ logger.info(`Processing batch ${batchNumber}/${totalBatches}`, {
+ jobId,
+ batchNumber,
+ fileCount: batch.fileKeys.length,
+ });
+
+ try {
+ const downloadUrl = await processDownloadBatch({
+ teamId,
+ folderStructure: batch.folderStructure,
+ fileKeys: batch.fileKeys,
+ sourceBucket,
+ watermarkConfig,
+ dataroomName,
+ zipPartNumber: batchNumber,
+ totalParts: totalBatches,
+ zipFileName: generateZipFileName(
+ dataroomName,
+ downloadTimestamp,
+ batchNumber,
+ ),
+ });
+
+ downloadUrls.push(downloadUrl);
+
+ // Calculate progress
+ const processedFiles = batches
+ .slice(0, batchNumber)
+ .reduce((sum, b) => sum + b.fileKeys.length, 0);
+ const progress = Math.round((batchNumber / totalBatches) * 100);
+
+ // Update job progress
+ await downloadJobStore.updateJob(jobId, {
+ processedFiles,
+ progress,
+ });
+
+ logger.info(`Batch ${batchNumber} completed`, {
+ jobId,
+ batchNumber,
+ downloadUrl,
+ progress,
+ });
+ } catch (batchError) {
+ logger.error(`Batch ${batchNumber} failed`, {
+ jobId,
+ batchNumber,
+ error:
+ batchError instanceof Error
+ ? batchError.message
+ : String(batchError),
+ });
+ throw batchError;
+ }
+ }
+
+ // Update job with completed status
+ const completedJob = await downloadJobStore.updateJob(jobId, {
+ status: "COMPLETED",
+ processedFiles: fileKeys.length,
+ progress: 100,
+ downloadUrls,
+ completedAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(), // 3 days
+ });
+
+ // Send email notification if requested
+ if (emailNotification && emailAddress && completedJob) {
+ await sendEmailNotification({
+ emailAddress,
+ dataroomName,
+ jobId,
+ teamId,
+ dataroomId,
+ expiresAt: completedJob.expiresAt,
+ });
+ }
+
+ logger.info("Bulk download task completed successfully", {
+ jobId,
+ totalBatches,
+ downloadUrls,
+ });
+
+ return {
+ success: true,
+ jobId,
+ downloadUrls,
+ };
+ } catch (error) {
+ logger.error("Bulk download task failed", {
+ jobId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+
+ // Update job status to failed
+ await downloadJobStore.updateJob(jobId, {
+ status: "FAILED",
+ error: error instanceof Error ? error.message : String(error),
+ });
+
+ throw error;
+ }
+ },
+});
+
+interface ProcessDownloadBatchParams {
+ teamId: string;
+ folderStructure: BulkDownloadPayload["folderStructure"];
+ fileKeys: string[];
+ sourceBucket: string;
+ watermarkConfig?: BulkDownloadPayload["watermarkConfig"];
+ dataroomName: string;
+ zipPartNumber: number;
+ totalParts: number;
+ zipFileName: string;
+ expirationHours?: number;
+}
+
+async function processDownloadBatch({
+ teamId,
+ folderStructure,
+ fileKeys,
+ sourceBucket,
+ watermarkConfig,
+ dataroomName,
+ zipPartNumber,
+ totalParts,
+ zipFileName,
+ expirationHours = 72,
+}: ProcessDownloadBatchParams): Promise<string> {
+ const baseUrl = process.env.NEXTAUTH_URL || "https://app.papermark.com";
+ const internalApiKey = process.env.INTERNAL_API_KEY;
+
+ if (!internalApiKey) {
+ throw new Error("INTERNAL_API_KEY is not configured");
+ }
+
+ const response = await fetch(`${baseUrl}/api/jobs/process-download-batch`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${internalApiKey}`,
+ },
+ body: JSON.stringify({
+ teamId,
+ sourceBucket,
+ fileKeys,
+ folderStructure,
+ watermarkConfig: watermarkConfig || { enabled: false },
+ zipPartNumber,
+ totalParts,
+ dataroomName,
+ zipFileName,
+ expirationHours,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(`API error: ${errorData.error || response.statusText}`);
+ }
+
+ const data = await response.json();
+ return data.downloadUrl;
+}
+
+interface FileBatch {
+ folderStructure: BulkDownloadPayload["folderStructure"];
+ fileKeys: string[];
+ totalSize: number;
+}
+
+interface FileInfo {
+ key: string;
+ folderPath: string;
+ size: number;
+ file: BulkDownloadPayload["folderStructure"][string]["files"][number];
+}
+
+function splitFilesIntoBatches(
+ folderStructure: BulkDownloadPayload["folderStructure"],
+ fileKeys: string[],
+): FileBatch[] {
+ const batches: FileBatch[] = [];
+
+ // Build a list of files with their info
+ const filesWithInfo: FileInfo[] = [];
+ for (const [path, folder] of Object.entries(folderStructure)) {
+ for (const file of folder.files) {
+ if (file.key && fileKeys.includes(file.key)) {
+ filesWithInfo.push({
+ key: file.key,
+ folderPath: path,
+ size: file.size || 0, // Default to 0 if size unknown
+ file,
+ });
+ }
+ }
+ }
+
+ // Check if we have size information for most files
+ const filesWithSize = filesWithInfo.filter((f) => f.size > 0);
+ const hasSizeInfo = filesWithSize.length > filesWithInfo.length * 0.5; // At least 50% have size
+
+ if (hasSizeInfo) {
+ // Size-based batching
+ let currentBatch: FileInfo[] = [];
+ let currentBatchSize = 0;
+
+ for (const fileInfo of filesWithInfo) {
+ const fileSize = fileInfo.size || 10 * 1024 * 1024; // Estimate 10MB for unknown sizes
+
+ // If adding this file would exceed limit, start a new batch
+ // Also enforce max file count per batch to avoid Lambda payload limits
+ if (
+ currentBatch.length > 0 &&
+ (currentBatchSize + fileSize > MAX_ZIP_SIZE_BYTES ||
+ currentBatch.length >= MAX_FILES_PER_BATCH)
+ ) {
+ batches.push(buildBatchFromFiles(currentBatch, folderStructure));
+ currentBatch = [];
+ currentBatchSize = 0;
+ }
+
+ currentBatch.push(fileInfo);
+ currentBatchSize += fileSize;
+ }
+
+ // Don't forget the last batch
+ if (currentBatch.length > 0) {
+ batches.push(buildBatchFromFiles(currentBatch, folderStructure));
+ }
+ } else {
+ // Fallback to count-based batching if no size info
+ for (let i = 0; i < filesWithInfo.length; i += MAX_FILES_PER_BATCH) {
+ const batchFiles = filesWithInfo.slice(i, i + MAX_FILES_PER_BATCH);
+ batches.push(buildBatchFromFiles(batchFiles, folderStructure));
+ }
+ }
+
+ return batches;
+}
+
+function buildBatchFromFiles(
+ files: FileInfo[],
+ folderStructure: BulkDownloadPayload["folderStructure"],
+): FileBatch {
+ const batchFolderStructure: BulkDownloadPayload["folderStructure"] = {};
+ const batchFileKeys: string[] = [];
+ let totalSize = 0;
+
+ for (const fileInfo of files) {
+ batchFileKeys.push(fileInfo.key);
+ totalSize += fileInfo.size || 0;
+
+ // Initialize folder if not exists in batch
+ if (!batchFolderStructure[fileInfo.folderPath]) {
+ batchFolderStructure[fileInfo.folderPath] = {
+ name: folderStructure[fileInfo.folderPath].name,
+ path: folderStructure[fileInfo.folderPath].path,
+ files: [],
+ };
+ }
+
+ batchFolderStructure[fileInfo.folderPath].files.push(fileInfo.file);
+ }
+
+ // Ensure all parent folders are included
+ for (const path of Object.keys(batchFolderStructure)) {
+ const pathParts = path.split("/").filter(Boolean);
+ let currentPath = "";
+
+ for (const part of pathParts) {
+ currentPath += "/" + part;
+ if (!batchFolderStructure[currentPath] && folderStructure[currentPath]) {
+ batchFolderStructure[currentPath] = {
+ name: folderStructure[currentPath].name,
+ path: folderStructure[currentPath].path,
+ files: [], // Empty files array for intermediate folders
+ };
+ }
+ }
+ }
+
+ return {
+ folderStructure: batchFolderStructure,
+ fileKeys: batchFileKeys,
+ totalSize,
+ };
+}
+
+async function sendEmailNotification({
+ emailAddress,
+ dataroomName,
+ jobId,
+ teamId,
+ dataroomId,
+ expiresAt,
+}: {
+ emailAddress: string;
+ dataroomName: string;
+ jobId: string;
+ teamId: string;
+ dataroomId: string;
+ expiresAt?: string;
+}): Promise<void> {
+ try {
+ // Link to the dataroom documents page where user can see and download their files
+ const baseUrl = process.env.NEXTAUTH_URL || "https://app.papermark.com";
+ const downloadUrl = `${baseUrl}/datarooms/${dataroomId}/documents`;
+
+ await sendDownloadReadyEmail({
+ to: emailAddress,
+ dataroomName,
+ downloadUrl,
+ expiresAt,
+ });
+ logger.info("Download ready email sent", {
+ jobId,
+ emailAddress,
+ downloadUrl,
+ });
+ } catch (error) {
+ logger.error("Failed to send download ready email", {
+ jobId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/pages/api/jobs/process-download-batch.ts b/pages/api/jobs/process-download-batch.ts
new file mode 100644
index 00000000..9259ef82
--- /dev/null
+++ b/pages/api/jobs/process-download-batch.ts
@@ -0,0 +1,98 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getTeamStorageConfigById } from "@/ee/features/storage/config";
+import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
+
+import { getLambdaClientForTeam } from "@/lib/files/aws-client";
+
+// Internal API endpoint for processing download batches
+// Called by Trigger.dev task - authenticated via shared secret
+export const config = {
+ maxDuration: 300, // 5 minutes for Lambda invocation
+};
+
+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`);
+ }
+
+ // Extract the API Key from the Authorization header
+ const authHeader = req.headers.authorization;
+ const token = authHeader?.split(" ")[1]; // Assuming the format is "Bearer [token]"
+
+ // Check if the API Key matches
+ if (token !== process.env.INTERNAL_API_KEY) {
+ res.status(401).json({ message: "Unauthorized" });
+ return;
+ }
+
+ try {
+ const {
+ teamId,
+ sourceBucket,
+ fileKeys,
+ folderStructure,
+ watermarkConfig,
+ zipPartNumber,
+ totalParts,
+ dataroomName,
+ zipFileName,
+ expirationHours,
+ } = req.body;
+
+ if (!teamId || !sourceBucket || !fileKeys || !folderStructure) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ // Get Lambda client and storage config using team credentials
+ const [client, storageConfig] = await Promise.all([
+ getLambdaClientForTeam(teamId),
+ getTeamStorageConfigById(teamId),
+ ]);
+
+ const params = {
+ FunctionName: storageConfig.lambdaFunctionName,
+ InvocationType: InvocationType.RequestResponse,
+ Payload: JSON.stringify({
+ sourceBucket,
+ fileKeys,
+ folderStructure,
+ watermarkConfig: watermarkConfig || { enabled: false },
+ zipPartNumber,
+ totalParts,
+ dataroomName,
+ zipFileName,
+ expirationHours,
+ }),
+ };
+
+ const command = new InvokeCommand(params);
+ const response = await client.send(command);
+
+ if (!response.Payload) {
+ throw new Error("Lambda response payload is undefined or empty");
+ }
+
+ const decodedPayload = new TextDecoder().decode(response.Payload);
+ const payload = JSON.parse(decodedPayload);
+
+ // Check for Lambda errors
+ if (payload.errorMessage) {
+ throw new Error(`Lambda error: ${payload.errorMessage}`);
+ }
+
+ const body = JSON.parse(payload.body);
+
+ return res.status(200).json({ downloadUrl: body.downloadUrl });
+ } catch (error) {
+ console.error("Error processing download batch:", error);
+ return res.status(500).json({
+ error: "Failed to process download batch",
+ details: (error as Error).message,
+ });
+ }
+}
diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.ts
index 0f8f2651..9db18e42 100644
--- a/pages/api/links/download/bulk.ts
+++ b/pages/api/links/download/bulk.ts
@@ -178,8 +178,6 @@ export default async function handle(
);
}
- // Don't update DATAROOM_VIEW downloadedAt - we'll show the grouped bulk download entry instead
-
// Create individual document views for each document being downloaded
const downloadableDocuments = downloadDocuments.filter(
(doc) =>
@@ -189,7 +187,6 @@ export default async function handle(
);
// For bulk downloads, only store metadata if there are less than 100 documents
- // to avoid storing huge JSON objects
const downloadMetadata =
downloadableDocuments.length < 100
? {
@@ -353,11 +350,12 @@ export default async function handle(
return res.status(404).json({ error: "No files to download" });
}
+ // Send Slack notification
if (view.dataroom?.teamId) {
try {
await notifyDocumentDownload({
teamId: view.dataroom.teamId,
- documentId: undefined, // Bulk download, no specific document
+ documentId: undefined,
dataroomId: view.dataroom.id,
linkId,
viewerEmail: view.viewerEmail ?? undefined,
@@ -379,6 +377,14 @@ export default async function handle(
getTeamStorageConfigById(teamId),
]);
+ // Generate zip filename: "Dataroom Name-20260203T143813Z"
+ const now = new Date();
+ const timestamp = now
+ .toISOString()
+ .replace(/[-:]/g, "")
+ .replace(/\.\d{3}/, ""); // Results in: 20260203T143813Z
+ const zipFileName = `${view.dataroom!.name}-${timestamp}`;
+
const params = {
FunctionName: storageConfig.lambdaFunctionName,
InvocationType: InvocationType.RequestResponse,
@@ -386,6 +392,8 @@ export default async function handle(
sourceBucket: storageConfig.bucket,
fileKeys: fileKeys,
folderStructure: folderStructure,
+ dataroomName: view.dataroom!.name,
+ zipFileName,
watermarkConfig: view.link.enableWatermark
? {
enabled: true,
@@ -414,7 +422,6 @@ export default async function handle(
if (response.Payload) {
const decodedPayload = new TextDecoder().decode(response.Payload);
-
const payload = JSON.parse(decodedPayload);
const { downloadUrl } = JSON.parse(payload.body);
@@ -430,6 +437,7 @@ export default async function handle(
});
}
} catch (error) {
+ console.error("Error starting bulk download:", error);
return res.status(500).json({
message: "Internal Server Error",
error: (error as Error).message,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/[jobId].ts b/pages/api/teams/[teamId]/datarooms/[id]/download/[jobId].ts
new file mode 100644
index 00000000..e08af91f
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/[jobId].ts
@@ -0,0 +1,93 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+
+import prisma from "@/lib/prisma";
+import { downloadJobStore } from "@/lib/redis-download-job-store";
+import { CustomUser } from "@/lib/types";
+
+// Status polling endpoint for download progress modal
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const {
+ teamId,
+ id: dataroomId,
+ jobId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ jobId: string;
+ };
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ // Verify user has access to the team
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ select: { teamId: true },
+ });
+
+ if (!teamAccess) {
+ return res
+ .status(403)
+ .json({ error: "Unauthorized to access this team" });
+ }
+
+ // Fetch the job from Redis
+ const job = await downloadJobStore.getJob(jobId);
+
+ if (!job) {
+ return res
+ .status(404)
+ .json({ error: "Download job not found or expired" });
+ }
+
+ // Verify the job belongs to this team and dataroom
+ if (job.teamId !== teamId || job.dataroomId !== dataroomId) {
+ return res
+ .status(403)
+ .json({ error: "Job does not belong to this dataroom" });
+ }
+
+ // Return full status for polling
+ return res.status(200).json({
+ id: job.id,
+ status: job.status,
+ progress: job.progress,
+ totalFiles: job.totalFiles,
+ processedFiles: job.processedFiles,
+ downloadUrls: job.status === "COMPLETED" ? job.downloadUrls : undefined,
+ error: job.status === "FAILED" ? job.error : undefined,
+ isReady: job.status === "COMPLETED" && !!job.downloadUrls?.length,
+ dataroomName: job.dataroomName,
+ createdAt: job.createdAt,
+ completedAt: job.completedAt,
+ expiresAt: job.expiresAt,
+ });
+ } catch (error) {
+ console.error("Error fetching download:", error);
+ return res.status(500).json({
+ error: "Failed to fetch download",
+ details: (error as Error).message,
+ });
+ }
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
index 67bf29cf..0193620c 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
@@ -2,15 +2,15 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getTeamStorageConfigById } from "@/ee/features/storage/config";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
import { getServerSession } from "next-auth";
-import { getLambdaClientForTeam } from "@/lib/files/aws-client";
import prisma from "@/lib/prisma";
+import { downloadJobStore } from "@/lib/redis-download-job-store";
+import { bulkDownloadTask } from "@/lib/trigger/bulk-download";
import { CustomUser } from "@/lib/types";
export const config = {
- maxDuration: 300,
+ maxDuration: 60, // Reduced since we're just triggering the async task
};
export default async function handler(
@@ -27,23 +27,21 @@ export default async function handler(
id: string;
};
+ const userId = (session.user as CustomUser).id;
+
if (req.method === "POST") {
try {
- const team = await prisma.team.findUnique({
+ const teamAccess = await prisma.userTeam.findUnique({
where: {
- id: teamId,
- users: {
- some: {
- userId: (session.user as CustomUser).id,
- },
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
},
},
- select: {
- id: true,
- },
+ select: { teamId: true },
});
- if (!team) {
+ if (!teamAccess) {
return res.status(403).end("Unauthorized to access this team");
}
@@ -53,6 +51,8 @@ export default async function handler(
teamId: teamId,
},
select: {
+ id: true,
+ name: true,
folders: {
select: {
id: true,
@@ -75,6 +75,7 @@ export default async function handler(
storageType: true,
originalFile: true,
contentType: true,
+ fileSize: true,
},
take: 1,
},
@@ -84,9 +85,11 @@ export default async function handler(
},
},
});
+
if (!dataroom) {
return res.status(404).end("Dataroom not found");
}
+
let downloadFolders = dataroom.folders;
let downloadDocuments = dataroom.documents;
@@ -95,7 +98,7 @@ export default async function handler(
[key: string]: {
name: string;
path: string;
- files: { name: string; key: string }[];
+ files: { name: string; key: string; size?: number }[];
};
} = {};
const fileKeys: string[] = [];
@@ -105,10 +108,12 @@ export default async function handler(
{ name: folder.name, id: folder.id },
]),
);
+
const addFileToStructure = (
path: string,
fileName: string,
fileKey: string,
+ fileSize?: number,
) => {
const pathParts = path.split("/").filter(Boolean);
let currentPath = "";
@@ -138,9 +143,14 @@ export default async function handler(
files: [],
};
}
- folderStructure[path].files.push({ name: fileName, key: fileKey });
+ folderStructure[path].files.push({
+ name: fileName,
+ key: fileKey,
+ size: fileSize,
+ });
fileKeys.push(fileKey);
};
+
downloadDocuments
.filter((doc) => !doc.folderId)
.filter((doc) => doc.document.versions[0].type !== "notion")
@@ -151,8 +161,12 @@ export default async function handler(
doc.document.name,
doc.document.versions[0].originalFile ??
doc.document.versions[0].file,
+ doc.document.versions[0].fileSize
+ ? Number(doc.document.versions[0].fileSize)
+ : undefined,
),
);
+
downloadFolders.forEach((folder) => {
const folderDocs = downloadDocuments
.filter((doc) => doc.folderId === folder.id)
@@ -168,6 +182,9 @@ export default async function handler(
doc.document.name,
doc.document.versions[0].originalFile ??
doc.document.versions[0].file,
+ doc.document.versions[0].fileSize
+ ? Number(doc.document.versions[0].fileSize)
+ : undefined,
),
);
@@ -177,42 +194,73 @@ export default async function handler(
}
});
- // Get team-specific Lambda client and storage config
- const client = await getLambdaClientForTeam(teamId);
+ if (fileKeys.length === 0) {
+ return res.status(404).json({ error: "No files to download" });
+ }
+
+ // Get team-specific storage config
const storageConfig = await getTeamStorageConfigById(teamId);
- const params = {
- FunctionName: storageConfig.lambdaFunctionName,
- InvocationType: InvocationType.RequestResponse,
- Payload: JSON.stringify({
- sourceBucket: storageConfig.bucket,
- fileKeys: fileKeys,
- folderStructure: folderStructure,
- }),
- };
+ // Get user email for notification
+ const user = await prisma.user.findUnique({
+ where: { id: userId },
+ select: { email: true },
+ });
- try {
- const command = new InvokeCommand(params);
- const response = await client.send(command);
+ // Create download job in Redis
+ const job = await downloadJobStore.createJob({
+ type: "bulk",
+ status: "PENDING",
+ dataroomId: dataroom.id,
+ dataroomName: dataroom.name,
+ totalFiles: fileKeys.length,
+ processedFiles: 0,
+ progress: 0,
+ teamId: teamId,
+ userId: userId,
+ emailNotification: !!user?.email,
+ emailAddress: user?.email ?? undefined,
+ });
- if (response.Payload) {
- const decodedPayload = new TextDecoder().decode(response.Payload);
+ // Trigger the async bulk download task
+ const handle = await bulkDownloadTask.trigger(
+ {
+ jobId: job.id,
+ dataroomId: dataroom.id,
+ dataroomName: dataroom.name,
+ teamId: teamId,
+ folderStructure: folderStructure,
+ fileKeys: fileKeys,
+ sourceBucket: storageConfig.bucket,
+ watermarkConfig: { enabled: false }, // No watermark for team member downloads
+ userId: userId,
+ emailNotification: !!user?.email,
+ emailAddress: user?.email ?? undefined,
+ },
+ {
+ idempotencyKey: job.id,
+ tags: [
+ `team_${teamId}`,
+ `dataroom_${dataroom.id}`,
+ `job_${job.id}`,
+ `user_${userId}`,
+ ],
+ },
+ );
- const payload = JSON.parse(decodedPayload);
- const { downloadUrl } = JSON.parse(payload.body);
+ // Update job with trigger run ID
+ await downloadJobStore.updateJob(job.id, {
+ triggerRunId: handle.id,
+ });
- 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,
- });
- }
+ // Return job ID immediately (async response)
+ return res.status(202).json({
+ jobId: job.id,
+ status: "PENDING",
+ message: "Download started. You will be notified when ready.",
+ });
} catch (error) {
+ console.error("Error starting bulk download:", error);
return res.status(500).json({
message: "Internal Server Error",
error: (error as Error).message,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/jobs.ts b/pages/api/teams/[teamId]/datarooms/[id]/download/jobs.ts
new file mode 100644
index 00000000..e69ab95b
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/jobs.ts
@@ -0,0 +1,86 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+
+import prisma from "@/lib/prisma";
+import { downloadJobStore } from "@/lib/redis-download-job-store";
+import { CustomUser } from "@/lib/types";
+
+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;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ if (req.method === "GET") {
+ try {
+ // Verify team access
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ select: { teamId: true },
+ });
+
+ if (!teamAccess) {
+ return res.status(403).end("Unauthorized to access this team");
+ }
+
+ // Get download jobs for this dataroom
+ const jobs = await downloadJobStore.getDataroomJobs(
+ dataroomId,
+ teamId,
+ 10,
+ );
+
+ // Filter to only show relevant jobs for this user
+ const userJobs = jobs.filter((job) => {
+ // Show user's own jobs
+ if (job.userId === userId) {
+ // Always show pending/processing jobs
+ if (job.status === "PENDING" || job.status === "PROCESSING") {
+ return true;
+ }
+
+ // Show completed jobs that haven't expired
+ if (job.status === "COMPLETED" && job.expiresAt) {
+ return new Date(job.expiresAt) > new Date();
+ }
+
+ // Show failed jobs from the last hour
+ if (job.status === "FAILED") {
+ const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
+ return new Date(job.createdAt) > oneHourAgo;
+ }
+ }
+
+ return false;
+ });
+
+ return res.status(200).json(userJobs);
+ } catch (error) {
+ console.error("Error fetching download jobs:", error);
+ return res.status(500).json({
+ error: "Failed to fetch download jobs",
+ details: (error as Error).message,
+ });
+ }
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/datarooms/[id]/documents/[...name].tsx b/pages/datarooms/[id]/documents/[...name].tsx
index a7c7df2b..c76233a7 100644
--- a/pages/datarooms/[id]/documents/[...name].tsx
+++ b/pages/datarooms/[id]/documents/[...name].tsx
@@ -63,6 +63,7 @@ export default function Documents() {
<DownloadDataroomButton
teamId={teamInfo?.currentTeam?.id!}
dataroomId={dataroom?.id!}
+ dataroomName={dataroom?.name}
/>
</div>
<div className="flex items-center justify-end gap-x-2">
diff --git a/pages/datarooms/[id]/documents/index.tsx b/pages/datarooms/[id]/documents/index.tsx
index 11ba7237..0c1e82be 100644
--- a/pages/datarooms/[id]/documents/index.tsx
+++ b/pages/datarooms/[id]/documents/index.tsx
@@ -57,6 +57,7 @@ export default function Documents() {
<DownloadDataroomButton
teamId={teamInfo?.currentTeam?.id!}
dataroomId={dataroom?.id!}
+ dataroomName={dataroom?.name}
/>
</div>
<div className="flex items-center justify-end gap-x-2">