Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: improve bulk download
Marc Seitz3dcae4a8d342
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 9ae19d62..e2200ea5 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -216,7 +216,6 @@ export async function POST(request: NextRequest) {linkId,);- console.log("previewSession", previewSession);if (!previewSession) {return NextResponse.json({@@ -237,6 +236,7 @@ export async function POST(request: NextRequest) {link.dataroomId!,);+// If we have a dataroom session, use its verified statusif (dataroomSession) {isEmailVerified = dataroomSession.verified;@@ -669,7 +669,6 @@ export async function POST(request: NextRequest) {// ** DATAROOM_VIEW **if (viewType === "DATAROOM_VIEW") {- console.log("viewType is DATAROOM_VIEW");try {let newDataroomView: { id: string } | null = null;if (!isPreview) {@@ -796,9 +795,6 @@ export async function POST(request: NextRequest) {// if dataroomSession is not present, create a dataroom view firstif (!dataroomSession) {- console.log(- "no dataroom session present, creating new dataroom view",- );dataroomView = await prisma.view.create({data: { ...viewFields, viewType: "DATAROOM_VIEW" },select: { id: true },diff --git a/components/emails/download-ready.tsx b/components/emails/download-ready.tsxindex 2a5d1cdc..4fb137eb 100644--- a/components/emails/download-ready.tsx+++ b/components/emails/download-ready.tsx@@ -34,11 +34,13 @@ export default function DownloadReady({downloadUrl = "https://app.papermark.com",email = "[email protected]",expiresAt,+ isViewer = false,}: {dataroomName?: string;downloadUrl?: string;email: string;expiresAt?: string;+ isViewer?: boolean;}) {const expirationTime = formatExpirationTime(expiresAt);@@ -56,8 +58,9 @@ export default function DownloadReady({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'll need to- be logged in to your Papermark account to access the download.+ {isViewer+ ? "Click the button below to open your downloads page and get your files."+ : "Click the button below to download your files. You'll need to be logged in to your Papermark account to access the download."}</Text><Section className="my-8 text-center">diff --git a/components/view/dataroom/download-otp-verification.tsx b/components/view/dataroom/download-otp-verification.tsxnew file mode 100644index 00000000..ac9a9d39--- /dev/null+++ b/components/view/dataroom/download-otp-verification.tsx@@ -0,0 +1,154 @@+"use client";++import { useCallback, useEffect, useState } from "react";++import {+ InputOTP,+ InputOTPGroup,+ InputOTPSlot,+} from "@/components/ui/input-otp";+import { Button } from "@/components/ui/button";++const REGEXP_ONLY_DIGITS = "^\\d+$";++export interface DownloadOtpVerificationProps {+ linkId: string;+ viewId: string;+ email: string;+ onVerified: () => void;+ onCancel?: () => void;+ compact?: boolean;+ /** When true, send OTP email automatically on mount (e.g. when user just chose "Notify me" and clicked Start download). */+ sendOtpOnMount?: boolean;+}++const RESEND_COOLDOWN_SECONDS = 60;++export function DownloadOtpVerification({+ linkId,+ viewId,+ email,+ onVerified,+ onCancel,+ compact = false,+ sendOtpOnMount = false,+}: DownloadOtpVerificationProps) {+ const [code, setCode] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [isSending, setIsSending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [resendCooldown, setResendCooldown] = useState(0);+ const hasSentOnMountRef = { current: false };++ const sendOtp = useCallback(async () => {+ setIsSending(true);+ setError(null);+ try {+ const res = await fetch("/api/links/download/verify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify({ linkId, viewId, email }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ setError(data.error ?? "Failed to send code");+ return;+ }+ setResendCooldown(RESEND_COOLDOWN_SECONDS);+ } finally {+ setIsSending(false);+ }+ }, [linkId, viewId, email]);++ useEffect(() => {+ if (!sendOtpOnMount || hasSentOnMountRef.current) return;+ hasSentOnMountRef.current = true;+ sendOtp();+ }, [sendOtpOnMount, sendOtp]);++ const verifyOtp = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!code || code.length !== 6) return;+ setIsLoading(true);+ setError(null);+ try {+ const res = await fetch("/api/links/download/verify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify({ linkId, viewId, email, code }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ setError(data.error ?? "Invalid code");+ return;+ }+ onVerified();+ } finally {+ setIsLoading(false);+ }+ };++ useEffect(() => {+ if (resendCooldown <= 0) return;+ const t = setInterval(+ () => setResendCooldown((s) => Math.max(0, s - 1)),+ 1000,+ );+ return () => clearInterval(t);+ }, [resendCooldown]);++ return (+ <form onSubmit={verifyOtp} className="space-y-4">+ <p className="text-sm text-muted-foreground">+ We sent a 6-digit code to <strong>{email}</strong>. Enter it below to+ verify and receive download notifications.+ </p>+ <InputOTP+ maxLength={6}+ pattern={REGEXP_ONLY_DIGITS}+ value={code ?? ""}+ onChange={(v) => {+ setError(null);+ setCode(v || null);+ }}+ containerClassName="my-4"+ accentColor="#e5e5e5"+ >+ <InputOTPGroup className="[&>div]:border-input [&>div]:text-foreground [&>div]:caret-foreground">+ {[0, 1, 2, 3, 4, 5].map((index) => (+ <InputOTPSlot key={index} index={index} />+ ))}+ </InputOTPGroup>+ </InputOTP>+ {error ? (+ <p className="text-sm text-destructive">{error}</p>+ ) : null}+ <div className="flex flex-wrap items-center gap-2">+ <Button+ type="submit"+ disabled={!code || code.length !== 6 || isLoading}+ >+ {isLoading ? "Verifying..." : "Verify"}+ </Button>+ </div>+ <p className="text-sm text-muted-foreground">+ Didn't receive the email?{" "}+ <Button+ type="button"+ variant="link"+ className="h-auto p-0 text-sm font-normal text-muted-foreground underline"+ disabled={isSending || resendCooldown > 0}+ onClick={sendOtp}+ >+ {isSending+ ? "Sending..."+ : resendCooldown > 0+ ? `Resend code (${resendCooldown}s)`+ : "Resend code"}+ </Button>+ </p>+ </form>+ );+}diff --git a/components/view/dataroom/folder-card.tsx b/components/view/dataroom/folder-card.tsxindex 10c96cc3..2d5b83ac 100644--- a/components/view/dataroom/folder-card.tsx+++ b/components/view/dataroom/folder-card.tsx@@ -49,7 +49,7 @@ export default function FolderCard({folder.hierarchicalIndex,dataroomIndexEnabled || false,);- const downloadDocument = async () => {+ const openFolderDownloadModal = () => {if (!allowDownload) {toast.error("Downloading folders is not allowed.");return;@@ -59,45 +59,10 @@ export default function FolderCard({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,- }),+ window.dispatchEvent(+ new CustomEvent("viewer-download-modal-open", {+ detail: { folderId: folder.id, folderName: folder.name },}),- {- loading: "Downloading dataroom folder...",- 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.name} downloaded successfully.`;- },- error: (error) => {- console.error("Error downloading folder:", error);- return error.message || "An error occurred while downloading file.";- },- },);};@@ -149,7 +114,7 @@ export default function FolderCard({onClick={(e) => {e.preventDefault();e.stopPropagation();- downloadDocument();+ openFolderDownloadModal();setOpen(false);}}disabled={isPreview}diff --git a/components/view/dataroom/nav-dataroom.tsx b/components/view/dataroom/nav-dataroom.tsxindex 24460721..87e0694f 100644--- a/components/view/dataroom/nav-dataroom.tsx+++ b/components/view/dataroom/nav-dataroom.tsx@@ -1,6 +1,6 @@import Link from "next/link";-import React, { useEffect, useState } from "react";+import React, { useEffect, useMemo, useState } from "react";import { DataroomBrand } from "@prisma/client";import { BadgeInfoIcon, Download } from "lucide-react";@@ -18,6 +18,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";import { Button } from "../../ui/button";import { ConversationSidebar } from "../conversations/sidebar";+import { ViewerDownloadProgressModal } from "./viewer-download-progress-modal";const DEFAULT_BANNER_IMAGE = "/_static/papermark-banner.png";@@ -31,6 +32,7 @@ export default function DataroomNav({isPreview,dataroomId,viewerId,+ viewerEmail,conversationsEnabled,isTeamMember,}: {@@ -43,58 +45,56 @@ export default function DataroomNav({isPreview?: boolean;dataroomId?: string;viewerId?: string;+ viewerEmail?: string | null;conversationsEnabled?: boolean;isTeamMember?: boolean;}) {- const [loading, setLoading] = useState<boolean>(false);const [showConversations, setShowConversations] = useState<boolean>(false);+ const [showDownloadModal, setShowDownloadModal] = useState<boolean>(false);+ const [downloadModalJobId, setDownloadModalJobId] = useState<string | null>(null);+ const [downloadFolderId, setDownloadFolderId] = useState<string | null>(null);+ const [downloadFolderName, setDownloadFolderName] = useState<string | null>(null);++ // Derive downloads page URL from current path so it works for both+ // /view/<linkId>/downloads and /<slug>/downloads (custom domains)+ const downloadsPageUrl = useMemo(() => {+ if (typeof window === "undefined") return "/downloads";+ const path = window.location.pathname.replace(/\/+$/, "");+ return `${path}/downloads`;+ }, []);- const downloadDataroom = async () => {+ useEffect(() => {+ const handler = (e: CustomEvent<{ jobId?: string; folderId?: string; folderName?: string }>) => {+ setDownloadModalJobId(e.detail?.jobId ?? null);+ setDownloadFolderId(e.detail?.folderId ?? null);+ setDownloadFolderName(e.detail?.folderName ?? null);+ setShowDownloadModal(true);+ };+ window.addEventListener(+ "viewer-download-modal-open" as any,+ handler as EventListener,+ );+ return () =>+ window.removeEventListener(+ "viewer-download-modal-open" as any,+ handler as EventListener,+ );+ }, []);++ const openDownloadModal = () => {if (isPreview) {toast.error("You cannot download datarooms in preview mode.");return;}- if (!allowDownload) return;- setLoading(true);- try {- toast.promise(- fetch(`/api/links/download/bulk`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ linkId, viewId }),- }),- {- 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);-- 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);+ if (!allowDownload || !allowBulkDownload) return;+ if (!viewerEmail) {+ toast.error("Enter your email in the dataroom to download.");+ return;}+ setDownloadModalJobId(null);+ setDownloadFolderId(null);+ setDownloadFolderName(null);+ setShowDownloadModal(true);};useEffect(() => {@@ -176,13 +176,12 @@ export default function DataroomNav({View FAQ</Button>)}- {allowDownload && allowBulkDownload ? (+ {allowDownload && allowBulkDownload && viewerEmail ? (<ButtonTooltip content="Download Dataroom"><Button- onClick={downloadDataroom}+ onClick={openDownloadModal}className="m-1 bg-gray-900 text-white hover:bg-gray-900/80"size="icon"- loading={loading}><Download className="h-5 w-5" /></Button>@@ -218,6 +217,26 @@ export default function DataroomNav({</div>)}+ {linkId && viewerEmail && (+ <ViewerDownloadProgressModal+ isOpen={showDownloadModal}+ onClose={() => {+ setShowDownloadModal(false);+ setDownloadModalJobId(null);+ setDownloadFolderId(null);+ setDownloadFolderName(null);+ }}+ linkId={linkId}+ viewId={viewId ?? ""}+ viewerEmail={viewerEmail}+ dataroomName={dataroom?.name ?? ""}+ dataroomId={dataroomId}+ downloadsPageUrl={downloadsPageUrl}+ initialJobId={downloadModalJobId ?? undefined}+ folderId={downloadFolderId}+ folderName={downloadFolderName}+ />+ )}{conversationsEnabled && showConversations ? (<ConversationSidebardataroomId={dataroomId}diff --git a/components/view/dataroom/viewer-download-progress-modal.tsx b/components/view/dataroom/viewer-download-progress-modal.tsxnew file mode 100644index 00000000..bb4a80e1--- /dev/null+++ b/components/view/dataroom/viewer-download-progress-modal.tsx@@ -0,0 +1,414 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++import {+ AlertCircle,+ CheckCircle2,+ Download,+ FileArchive,+ Loader2,+ XCircle,+} from "lucide-react";++import { DownloadOtpVerification } from "./download-otp-verification";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Progress } from "@/components/ui/progress";++export type ViewerDownloadProgressModalProps = {+ isOpen: boolean;+ onClose: () => void;+ linkId: string;+ viewId: string;+ viewerEmail: string;+ dataroomName: string;+ dataroomId?: string;+ downloadsPageUrl: string;+ initialJobId?: string | null;+ /** When set, the modal downloads a single folder instead of the entire dataroom */+ folderId?: string | null;+ folderName?: string | null;+};++type Step = "choose" | "otp" | "progress" | "complete";++interface JobStatus {+ id: string;+ status: string;+ progress: number;+ totalFiles: number;+ processedFiles: number;+ downloadUrls?: string[];+ error?: string;+ isReady: boolean;+ dataroomName: string;+ createdAt: string;+ completedAt?: string;+ expiresAt?: string;+}++export function ViewerDownloadProgressModal({+ isOpen,+ onClose,+ linkId,+ viewId,+ viewerEmail,+ dataroomName,+ dataroomId,+ downloadsPageUrl,+ initialJobId,+ folderId,+ folderName,+}: ViewerDownloadProgressModalProps) {+ const isFolderDownload = !!folderId;+ const [step, setStep] = useState<Step>("choose");+ const [wantEmail, setWantEmail] = useState(false);+ const [verified, setVerified] = useState<boolean | null>(null);+ const [jobId, setJobId] = useState<string | null>(initialJobId ?? null);+ const [otpKey, setOtpKey] = useState(0);+ const [status, setStatus] = useState<JobStatus | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [isStarting, setIsStarting] = useState(false);+ const [isPolling, setIsPolling] = useState(false);+ const pollRef = useRef<NodeJS.Timeout | null>(null);++ const fetchVerified = useCallback(async () => {+ try {+ const res = await fetch(+ `/api/links/download/verify?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (res.ok) {+ const data = await res.json();+ setVerified(!!data.verified);+ return !!data.verified;+ }+ setVerified(false);+ return false;+ } catch {+ setVerified(false);+ return false;+ }+ }, [linkId]);++ useEffect(() => {+ if (!isOpen) return;+ setStep(initialJobId ? "progress" : "choose");+ setJobId(initialJobId ?? null);+ setStatus(null);+ setError(null);+ if (initialJobId) {+ setIsPolling(true);+ } else {+ fetchVerified();+ }+ }, [isOpen, initialJobId, fetchVerified]);++ const fetchStatus = useCallback(+ async (id: string) => {+ const res = await fetch(+ `/api/links/download/${id}?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw new Error(data.error ?? "Failed to fetch status");+ }+ return res.json();+ },+ [linkId],+ );++ useEffect(() => {+ if (!isOpen || !jobId || !isPolling) return;+ const poll = async () => {+ try {+ const data = await fetchStatus(jobId);+ setStatus(data);+ setError(null);+ if (data.status === "COMPLETED" || data.status === "FAILED") {+ setIsPolling(false);+ if (pollRef.current) {+ clearInterval(pollRef.current);+ pollRef.current = null;+ }+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : "Error");+ }+ };+ poll();+ pollRef.current = setInterval(poll, 2000);+ return () => {+ if (pollRef.current) {+ clearInterval(pollRef.current);+ pollRef.current = null;+ }+ };+ }, [isOpen, jobId, isPolling, fetchStatus]);++ const startDownload = async (withEmail: boolean) => {+ setIsStarting(true);+ setError(null);+ try {+ const endpoint = isFolderDownload+ ? "/api/links/download/dataroom-folder"+ : "/api/links/download/bulk";++ const body = isFolderDownload+ ? { folderId, dataroomId, viewId, linkId, emailNotification: withEmail }+ : { linkId, viewId, emailNotification: withEmail };++ const res = await fetch(endpoint, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ setError(data.error ?? "Failed to start download");+ return;+ }+ if (data.jobId) {+ setJobId(data.jobId);+ setStep("progress");+ setIsPolling(true);+ }+ } finally {+ setIsStarting(false);+ }+ };++ const handleStartClick = () => {+ if (wantEmail && verified === false) {+ setStep("otp");+ setOtpKey((k) => k + 1);+ return;+ }+ startDownload(!!wantEmail);+ };++ const handleOtpVerified = () => {+ setVerified(true);+ setStep("choose");+ // Defer bulk request so the browser has committed any Set-Cookie from the verify response+ setTimeout(() => {+ startDownload(true);+ }, 0);+ };++ const handleDownload = (url: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.rel = "noopener noreferrer";+ document.body.appendChild(a);+ a.click();+ setTimeout(() => document.body.removeChild(a), 100);+ };++ const handleDownloadAll = (urls: string[]) => {+ urls.forEach((url, i) => {+ setTimeout(() => handleDownload(url), i * 1500);+ });+ };++ const handleClose = () => {+ if (pollRef.current) {+ clearInterval(pollRef.current);+ pollRef.current = null;+ }+ setStep("choose");+ setJobId(null);+ setStatus(null);+ setError(null);+ setIsPolling(false);+ onClose();+ };++ 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" : ""}`;+ 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>+ {isFolderDownload+ ? `Download folder: ${folderName}`+ : `Download ${dataroomName || "Dataroom"}`}+ </DialogTitle>+ <DialogDescription>+ {step === "choose" &&+ "Start the download. You can optionally get an email when it's ready."}+ {step === "otp" && "Verify your email to receive download notifications."}+ {step === "progress" &&+ (status?.status === "COMPLETED"+ ? "Your files are ready to download."+ : "Preparing your files...")}+ </DialogDescription>+ </DialogHeader>++ {step === "choose" && (+ <div className="space-y-4 py-4">+ <label className="flex items-center gap-2 text-sm">+ <input+ type="checkbox"+ checked={wantEmail}+ onChange={(e) => setWantEmail(e.target.checked)}+ />+ Notify me by email when the download is ready+ </label>+ {wantEmail && verified === false && (+ <p className="text-xs text-muted-foreground">+ You’ll need to verify your email with a one-time code first.+ </p>+ )}+ <div className="flex gap-2">+ <Button+ onClick={handleStartClick}+ disabled={isStarting}+ >+ {isStarting ? "Starting..." : "Start download"}+ </Button>+ <Button variant="outline" onClick={handleClose}>+ Cancel+ </Button>+ </div>+ <p className="text-xs text-muted-foreground">+ <a+ href={downloadsPageUrl}+ className="underline"+ target="_blank"+ rel="noopener noreferrer"+ >+ View your downloads+ </a>+ </p>+ </div>+ )}++ {step === "otp" && (+ <DownloadOtpVerification+ key={otpKey}+ linkId={linkId}+ viewId={viewId}+ email={viewerEmail}+ onVerified={handleOtpVerified}+ sendOtpOnMount+ />+ )}++ {step === "progress" && (+ <div className="space-y-4 py-4">+ <div className="flex justify-center">+ {status?.status === "COMPLETED" ? (+ <CheckCircle2 className="h-10 w-10 text-green-500" />+ ) : status?.status === "FAILED" ? (+ <XCircle className="h-10 w-10 text-destructive" />+ ) : (+ <FileArchive className="h-10 w-10 animate-pulse text-primary" />+ )}+ </div>+ <p className="text-center text-sm text-muted-foreground">+ {!status+ ? "Starting..."+ : status.status === "PENDING"+ ? "Preparing..."+ : status.status === "PROCESSING"+ ? `Processing ${status.processedFiles} of ${status.totalFiles} files...`+ : status.status === "COMPLETED"+ ? "Your download is ready!"+ : status.error ?? "Download failed."}+ </p>+ {(status?.status === "PROCESSING" || status?.status === "PENDING") && (+ <Progress value={status?.progress ?? 0} className="h-2" />+ )}+ {status?.status === "COMPLETED" && status.downloadUrls && status.downloadUrls.length > 0 && (+ <div className="space-y-2">+ {status.downloadUrls.length === 1 ? (+ <Button+ className="w-full"+ onClick={() => handleDownload(status.downloadUrls![0])}+ >+ <Download className="mr-2 h-4 w-4" />+ Download ZIP+ </Button>+ ) : (+ <>+ <Button+ className="w-full"+ onClick={() => handleDownloadAll(status.downloadUrls!)}+ >+ <Download className="mr-2 h-4 w-4" />+ Download all ({status.downloadUrls.length} parts)+ </Button>+ <div className="max-h-32 space-y-1 overflow-y-auto">+ {status.downloadUrls.map((url, i) => (+ <Button+ key={i}+ variant="outline"+ size="sm"+ className="w-full justify-start"+ onClick={() => handleDownload(url)}+ >+ Part {i + 1}+ </Button>+ ))}+ </div>+ </>+ )}+ {status.expiresAt && (+ <p className="text-center text-xs text-muted-foreground">+ Expires in {formatExpirationTime(status.expiresAt)}+ </p>+ )}+ </div>+ )}+ {(status?.status === "PENDING" || status?.status === "PROCESSING") && (+ <DialogFooter>+ <p className="text-xs text-muted-foreground">+ You can close this. We’ll email you when it’s ready.+ </p>+ </DialogFooter>+ )}+ {status?.status === "FAILED" && (+ <Button variant="outline" onClick={() => setStep("choose")}>+ Try again+ </Button>+ )}+ <p className="text-xs text-muted-foreground">+ <a href={downloadsPageUrl} className="underline" target="_blank" rel="noopener noreferrer">+ Open downloads page+ </a>+ </p>+ {error && (+ <p className="text-sm text-destructive">{error}</p>+ )}+ </div>+ )}++ {error && step !== "progress" && (+ <p className="text-sm text-destructive">{error}</p>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsxindex c7345408..40586c27 100644--- a/components/view/viewer/dataroom-viewer.tsx+++ b/components/view/viewer/dataroom-viewer.tsx@@ -409,6 +409,7 @@ export default function DataroomViewer({isPreview={isPreview}dataroomId={dataroom?.id}viewerId={viewerId}+ viewerEmail={viewerEmail}conversationsEnabled={viewData.conversationsEnabled}isTeamMember={viewData.isTeamMember}/>diff --git a/lib/auth/dataroom-auth.ts b/lib/auth/dataroom-auth.tsindex 838b431c..deae5689 100644--- a/lib/auth/dataroom-auth.ts+++ b/lib/auth/dataroom-auth.ts@@ -14,6 +14,24 @@ import { getIpAddress } from "../utils/ip";const COOKIE_EXPIRATION_TIME = 23 * 60 * 60 * 1000; // 23 hours+/**+ * Normalize IP addresses so that IPv6 loopback (::1),+ * IPv4-mapped IPv6 (::ffff:127.0.0.1) and plain 127.0.0.1+ * all compare equal.+ */+function normalizeIp(ip: string): string {+ const trimmed = ip.trim();+ // Treat all localhost variants as 127.0.0.1+ if (trimmed === "::1" || trimmed === "::ffff:127.0.0.1") {+ return LOCALHOST_IP;+ }+ // Strip ::ffff: prefix from IPv4-mapped IPv6 addresses+ if (trimmed.startsWith("::ffff:")) {+ return trimmed.slice(7);+ }+ return trimmed;+}+// Define the Zod schema for session dataexport const DataroomSessionSchema = z.object({linkId: z.string(),@@ -45,7 +63,7 @@ async function createDataroomSession(viewId,viewerId,expiresAt,- ipAddress,+ ipAddress: normalizeIp(ipAddress),verified,};@@ -87,7 +105,7 @@ async function verifyDataroomSession(return null;}- const ipAddressValue = ipAddress(request) ?? LOCALHOST_IP;+ const ipAddressValue = normalizeIp(ipAddress(request) ?? LOCALHOST_IP);if (ipAddressValue !== sessionData.ipAddress) {await redis.del(`dataroom_session:${sessionToken}`);@@ -105,7 +123,6 @@ async function verifyDataroomSession(return sessionData;} catch (error) {- console.log("error", error);// If validation fails, delete invalid session and return nullawait redis.del(`dataroom_session:${sessionToken}`);return null;@@ -119,10 +136,28 @@ export async function verifyDataroomSessionInPagesRouter(): Promise<DataroomSession | null> {if (!dataroomId) return null;- // Get cookies from request headers+ const sessionData = await getDataroomSessionByLinkIdInPagesRouter(+ req,+ linkId,+ );+ if (!sessionData || sessionData.dataroomId !== dataroomId) return null;+ return sessionData;+}++/**+ * Get dataroom session by linkId only (e.g. for downloads page where dataroomId may not be in context).+ */+export async function getDataroomSessionByLinkIdInPagesRouter(+ req: NextApiRequest,+ linkId: string,+): Promise<DataroomSession | null> {+ if (!linkId) return null;+const cookies = parse(req.headers.cookie || "");const sessionToken = cookies[`pm_drs_${linkId}`];- if (!sessionToken) return null;+ if (!sessionToken) {+ return null;+ }const session = await redis.get(`dataroom_session:${sessionToken}`);if (!session) return null;@@ -137,29 +172,59 @@ export async function verifyDataroomSessionInPagesRouter(}// Get IP address from request- const ipAddressValue = getIpAddress(req.headers) ?? LOCALHOST_IP;-+ const ipAddressValue = normalizeIp(getIpAddress(req.headers) ?? LOCALHOST_IP);if (ipAddressValue !== sessionData.ipAddress) {await redis.del(`dataroom_session:${sessionToken}`);return null;}- // Check if the session is for the correct link and dataroom- if (- sessionData.linkId !== linkId ||- sessionData.dataroomId !== dataroomId- ) {+ if (sessionData.linkId !== linkId) {await redis.del(`dataroom_session:${sessionToken}`);return null;}return sessionData;} catch (error) {- console.log("error", error);// If validation fails, delete invalid session and return nullawait redis.del(`dataroom_session:${sessionToken}`);return null;}}+/**+ * Update the verified flag of an existing dataroom session (e.g. after OTP verification).+ * Caller must obtain sessionToken from the request cookie (pm_drs_{linkId}).+ */+export async function updateDataroomSessionVerified(+ sessionToken: string,+ verified: boolean,+): Promise<boolean> {+ if (!sessionToken) return false;++ const raw = await redis.get(`dataroom_session:${sessionToken}`);+ if (!raw) return false;++ try {+ const sessionData = DataroomSessionSchema.parse(+ typeof raw === "string" ? JSON.parse(raw) : raw,+ );+ if (sessionData.expiresAt < Date.now()) {+ await redis.del(`dataroom_session:${sessionToken}`);+ return false;+ }++ const updated: DataroomSession = { ...sessionData, verified };+ await redis.set(+ `dataroom_session:${sessionToken}`,+ JSON.stringify(updated),+ {+ pxat: sessionData.expiresAt,+ },+ );+ return true;+ } catch {+ return false;+ }+}+export { createDataroomSession, verifyDataroomSession };diff --git a/lib/emails/send-download-ready-email.ts b/lib/emails/send-download-ready-email.tsindex c29952e7..f81b1baa 100644--- a/lib/emails/send-download-ready-email.ts+++ b/lib/emails/send-download-ready-email.ts@@ -7,17 +7,20 @@ export const sendDownloadReadyEmail = async ({dataroomName,downloadUrl,expiresAt,+ isViewer,}: {to: string;dataroomName: string;downloadUrl: string;expiresAt?: string;+ isViewer?: boolean;}) => {const emailTemplate = DownloadReady({dataroomName,downloadUrl,email: to,expiresAt,+ isViewer: isViewer ?? false,});try {diff --git a/lib/redis-download-job-store.ts b/lib/redis-download-job-store.tsindex 9bf79943..b53b8e36 100644--- a/lib/redis-download-job-store.ts+++ b/lib/redis-download-job-store.ts@@ -21,6 +21,12 @@ export interface DownloadJob {error?: string;teamId: string;userId: string;+ /** Viewer download: link this job belongs to */+ linkId?: string;+ /** Viewer download: viewer record id */+ viewerId?: string;+ /** Viewer download: email used for job list and email notification */+ viewerEmail?: string;triggerRunId?: string; // Trigger.dev run ID for cancellationcreatedAt: string;updatedAt: string;@@ -28,10 +34,13 @@ export interface DownloadJob {expiresAt?: string; // When download links expireemailNotification?: boolean;emailAddress?: string;+ /** Folder download: name of the folder (when type === "folder") */+ folderName?: string;}const JOB_PREFIX = "download_job:";const TEAM_JOBS_PREFIX = "team_download_jobs:";+const VIEWER_JOBS_PREFIX = "viewer_download_jobs:";const JOB_TTL = 60 * 60 * 24 * 3; // 3 days - Redis handles cleanup via TTLexport class RedisDownloadJobStore {@@ -43,6 +52,10 @@ export class RedisDownloadJobStore {return `${TEAM_JOBS_PREFIX}${teamId}`;}+ private getViewerJobsKey(linkId: string, viewerEmail: string): string {+ return `${VIEWER_JOBS_PREFIX}${linkId}:${viewerEmail.toLowerCase()}`;+ }+async createJob(jobData: Omit<DownloadJob, "id" | "createdAt" | "updatedAt">,): Promise<DownloadJob> {@@ -66,6 +79,16 @@ export class RedisDownloadJobStore {await redis.zadd(teamJobsKey, { score: Date.now(), member: jobId });await redis.expire(teamJobsKey, JOB_TTL);+ // If viewer download, add to viewer index for getViewerJobs+ if (jobData.linkId && jobData.viewerEmail) {+ const viewerJobsKey = this.getViewerJobsKey(+ jobData.linkId,+ jobData.viewerEmail,+ );+ await redis.zadd(viewerJobsKey, { score: Date.now(), member: jobId });+ await redis.expire(viewerJobsKey, JOB_TTL);+ }+return job;}@@ -151,6 +174,32 @@ export class RedisDownloadJobStore {}).slice(0, limit);}++ /**+ * List download jobs for a viewer (link + email). Used on viewer downloads page.+ */+ async getViewerJobs(+ linkId: string,+ viewerEmail: string,+ limit: number = 20,+ ): Promise<DownloadJob[]> {+ const viewerJobsKey = this.getViewerJobsKey(linkId, viewerEmail);+ const jobIds = await redis.zrange(viewerJobsKey, 0, limit - 1, {+ rev: true,+ });++ if (!jobIds.length) {+ return [];+ }++ const jobs = await Promise.all(+ (jobIds as string[]).map((jobId: string) => this.getJob(jobId)),+ );++ return jobs.filter(+ (job: DownloadJob | null): job is DownloadJob => job !== null,+ );+ }}export const downloadJobStore = new RedisDownloadJobStore();diff --git a/lib/trigger/bulk-download.ts b/lib/trigger/bulk-download.tsindex 245a4455..ff9e0385 100644--- a/lib/trigger/bulk-download.ts+++ b/lib/trigger/bulk-download.ts@@ -1,10 +1,12 @@import { logger, task } from "@trigger.dev/sdk/v3";import { sendDownloadReadyEmail } from "@/lib/emails/send-download-ready-email";+import prisma from "@/lib/prisma";import { downloadJobStore } from "@/lib/redis-download-job-store";+import { constructLinkUrl } from "@/lib/utils/link-url";// Maximum files per batch (Lambda payload limit)-const MAX_FILES_PER_BATCH = 500;+const MAX_FILES_PER_BATCH = 10;// 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@@ -22,21 +24,22 @@ function generateTimestamp(): string {}/**- * 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+ * Generate a zip filename.+ * Full dataroom: "Dataroom Name-20260202T131428Z[-001]"+ * Folder download: "Dataroom Name-FolderName-20260202T131428Z[-001]"*/function generateZipFileName(dataroomName: string,timestamp: string,partNumber?: number,+ folderName?: string,): string {- // Zero-pad part number to 3 digitsconst paddedPart = partNumber?.toString().padStart(3, "0") ?? "";+ const base = folderName+ ? `${dataroomName}-${folderName}-${timestamp}`+ : `${dataroomName}-${timestamp}`;- return `${dataroomName}-${timestamp}${paddedPart ? `-${paddedPart}` : ""}`;+ return `${base}${paddedPart ? `-${paddedPart}` : ""}`;}export type BulkDownloadPayload = {@@ -78,6 +81,7 @@ export type BulkDownloadPayload = {userId?: string;emailNotification?: boolean;emailAddress?: string;+ folderName?: string;};export const bulkDownloadTask = task({@@ -98,6 +102,7 @@ export const bulkDownloadTask = task({viewerEmail,emailNotification,emailAddress,+ folderName,} = payload;logger.info("Starting bulk download task", {@@ -134,7 +139,7 @@ export const bulkDownloadTask = task({dataroomName,zipPartNumber: 1,totalParts: 1,- zipFileName: generateZipFileName(dataroomName, downloadTimestamp),+ zipFileName: generateZipFileName(dataroomName, downloadTimestamp, undefined, folderName),});// Update job with completed status@@ -149,7 +154,6 @@ export const bulkDownloadTask = task({).toISOString(), // 3 days});- // Send email notification if requestedif (emailNotification && emailAddress && completedJob) {await sendEmailNotification({emailAddress,@@ -158,6 +162,7 @@ export const bulkDownloadTask = task({teamId,dataroomId,expiresAt: completedJob.expiresAt,+ linkId: payload.linkId,});}@@ -222,6 +227,7 @@ export const bulkDownloadTask = task({dataroomName,downloadTimestamp,batchNumber,+ folderName,),});@@ -268,7 +274,6 @@ export const bulkDownloadTask = task({expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(), // 3 days});- // Send email notification if requestedif (emailNotification && emailAddress && completedJob) {await sendEmailNotification({emailAddress,@@ -277,6 +282,7 @@ export const bulkDownloadTask = task({teamId,dataroomId,expiresAt: completedJob.expiresAt,+ linkId: payload.linkId,});}@@ -501,6 +507,7 @@ async function sendEmailNotification({teamId,dataroomId,expiresAt,+ linkId,}: {emailAddress: string;dataroomName: string;@@ -508,17 +515,32 @@ async function sendEmailNotification({teamId: string;dataroomId: string;expiresAt?: string;+ linkId?: 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`;+ let downloadUrl: string;+ let isViewer = false;++ if (linkId) {+ const link = await prisma.link.findUnique({+ where: { id: linkId },+ select: { id: true, domainId: true, domainSlug: true, slug: true },+ });+ downloadUrl = link+ ? `${constructLinkUrl(link)}/downloads`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.com"}/view/${linkId}/downloads`;+ isViewer = true;+ } else {+ const baseUrl = process.env.NEXTAUTH_URL || "https://app.papermark.com";+ downloadUrl = `${baseUrl}/datarooms/${dataroomId}/documents`;+ }await sendDownloadReadyEmail({to: emailAddress,dataroomName,downloadUrl,expiresAt,+ isViewer,});logger.info("Download ready email sent", {jobId,diff --git a/pages/api/links/download/[jobId].ts b/pages/api/links/download/[jobId].tsnew file mode 100644index 00000000..e3b9ad53--- /dev/null+++ b/pages/api/links/download/[jobId].ts@@ -0,0 +1,72 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getDataroomSessionByLinkIdInPagesRouter } from "@/lib/auth/dataroom-auth";+import prisma from "@/lib/prisma";+import { downloadJobStore } from "@/lib/redis-download-job-store";++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 { linkId, jobId } = req.query as { linkId: string; jobId: string };+ if (!linkId || !jobId) {+ return res.status(400).json({ error: "linkId and jobId are required" });+ }++ const session = await getDataroomSessionByLinkIdInPagesRouter(req, linkId);+ if (!session) {+ return res.status(401).json({ error: "Session required" });+ }++ const view = await prisma.view.findUnique({+ where: { id: session.viewId },+ select: { viewerEmail: true },+ });+ if (!view?.viewerEmail) {+ return res.status(403).json({ error: "Viewer email not found" });+ }++ const job = await downloadJobStore.getJob(jobId);+ if (!job) {+ return res+ .status(404)+ .json({ error: "Download job not found or expired" });+ }++ if (job.linkId !== linkId || job.viewerEmail !== view.viewerEmail) {+ return res.status(403).json({ error: "Job does not belong to this viewer" });+ }++ // Use the request's origin so download links work on custom domains+ const proto = req.headers["x-forwarded-proto"] || "https";+ const host = req.headers["host"] || "app.papermark.com";+ const baseUrl = `${proto}://${host}`;++ const partCount = job.downloadUrls?.length ?? 0;+ const proxyDownloadUrls =+ job.status === "COMPLETED" && partCount > 0+ ? Array.from({ length: partCount }, (_, i) =>+ `${baseUrl}/api/links/download/file/${jobId}/${i}?linkId=${encodeURIComponent(linkId)}`,+ )+ : undefined;++ return res.status(200).json({+ id: job.id,+ status: job.status,+ progress: job.progress,+ totalFiles: job.totalFiles,+ processedFiles: job.processedFiles,+ downloadUrls: proxyDownloadUrls,+ 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,+ });+}diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.tsindex 9db18e42..1cab95a2 100644--- a/pages/api/links/download/bulk.ts+++ b/pages/api/links/download/bulk.ts@@ -1,86 +1,92 @@import { NextApiRequest, NextApiResponse } from "next";import { getTeamStorageConfigById } from "@/ee/features/storage/config";-import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";import { ItemType, ViewType } from "@prisma/client";-import { getLambdaClientForTeam } from "@/lib/files/aws-client";+import { verifyDataroomSessionInPagesRouter } from "@/lib/auth/dataroom-auth";import { notifyDocumentDownload } from "@/lib/integrations/slack/events";import prisma from "@/lib/prisma";+import { downloadJobStore } from "@/lib/redis-download-job-store";+import { bulkDownloadTask } from "@/lib/trigger/bulk-download";import { getIpAddress } from "@/lib/utils/ip";export const config = {- maxDuration: 300,- memory: 2048,+ maxDuration: 60,};export default async function handle(req: NextApiRequest,res: NextApiResponse,) {- if (req.method === "POST") {- // POST /api/links/download/bulk- const { linkId, viewId } = req.body as { linkId: string; viewId: string };-- try {- const view = await prisma.view.findUnique({- where: {- id: viewId,- linkId: linkId,- viewType: { equals: ViewType.DATAROOM_VIEW },- },- select: {- id: true,- viewedAt: true,- viewerEmail: true,- viewerId: true,- verified: true,- link: {- select: {- allowDownload: true,- expiresAt: true,- isArchived: true,- deletedAt: true,- enableWatermark: true,- watermarkConfig: true,- name: true,- permissionGroupId: true,- },+ if (req.method !== "POST") {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const { linkId, viewId, emailNotification } = req.body as {+ linkId: string;+ viewId: string;+ emailNotification?: boolean;+ };++ try {+ const view = await prisma.view.findUnique({+ where: {+ id: viewId,+ linkId: linkId,+ viewType: { equals: ViewType.DATAROOM_VIEW },+ },+ select: {+ id: true,+ viewedAt: true,+ viewerEmail: true,+ viewerId: true,+ verified: true,+ link: {+ select: {+ allowDownload: true,+ expiresAt: true,+ isArchived: true,+ deletedAt: true,+ enableWatermark: true,+ watermarkConfig: true,+ name: true,+ permissionGroupId: true,},- groupId: true,- dataroom: {- select: {- id: true,- name: true,- teamId: true,- allowBulkDownload: true,- folders: {- select: {- id: true,- name: true,- path: true,- },+ },+ groupId: true,+ dataroom: {+ select: {+ id: true,+ name: true,+ teamId: true,+ allowBulkDownload: true,+ folders: {+ select: {+ id: true,+ name: true,+ path: true,},- documents: {- select: {- id: true,- folderId: true,- document: {- select: {- id: true,- name: true,- versions: {- where: { isPrimary: true },- select: {- type: true,- file: true,- storageType: true,- originalFile: true,- contentType: true,- numPages: true,- },- take: 1,+ },+ documents: {+ select: {+ id: true,+ folderId: true,+ document: {+ select: {+ id: true,+ name: true,+ versions: {+ where: { isPrimary: true },+ select: {+ type: true,+ file: true,+ storageType: true,+ originalFile: true,+ contentType: true,+ numPages: true,},+ take: 1,},},},@@ -88,215 +94,266 @@ export default async function handle(},},},- });+ },+ });- // if view does not exist, we should not allow the download- if (!view) {- return res.status(404).json({ error: "Error downloading" });- }+ 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" });- }+ const dataroomId = view.dataroom?.id;+ const session = await verifyDataroomSessionInPagesRouter(+ req,+ linkId,+ dataroomId ?? "",+ );+ if (!session) {+ return res.status(401).json({ error: "Session required to download" });+ }- // if link is archived, we should not allow the download- if (view.link.isArchived) {- return res.status(403).json({ error: "Error downloading" });+ // Verified session and email are only required when the viewer requested email notification+ if (emailNotification) {+ if (!view.viewerEmail) {+ return res.status(400).json({+ error:+ "Email is required to receive download notifications. Enter your email in the dataroom.",+ });}-- if (view.link.deletedAt) {- return res.status(403).json({ error: "Error downloading" });+ if (!session.verified) {+ return res.status(403).json({+ error:+ "Verify your email with the one-time code to receive a notification when the download is ready.",+ });}+ }- // 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 (!view.link.allowDownload) {+ return res.status(403).json({ error: "Error downloading" });+ }- // if dataroom does not exist, we should not allow the download- if (!view.dataroom) {- 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 dataroom does not allow bulk download, we should not allow the download- if (!view.dataroom.allowBulkDownload) {- return res- .status(403)- .json({ error: "Bulk download is disabled for this dataroom" });- }+ if (view.link.deletedAt) {+ 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" });+ }- let downloadFolders = view.dataroom.folders;- let downloadDocuments = view.dataroom.documents;-- // Check permissions based on groupId (ViewerGroup) or permissionGroupId (PermissionGroup)- const effectiveGroupId = view.groupId || view.link.permissionGroupId;-- if (effectiveGroupId) {- let groupPermissions: any[] = [];-- if (view.groupId) {- // This is a ViewerGroup (legacy behavior)- groupPermissions = await prisma.viewerGroupAccessControls.findMany({- where: { groupId: view.groupId, canDownload: true },- });- } else if (view.link.permissionGroupId) {- // This is a PermissionGroup (new behavior)- groupPermissions =- await prisma.permissionGroupAccessControls.findMany({- where: {- groupId: view.link.permissionGroupId,- canDownload: true,- },- });- }+ // if dataroom does not exist, we should not allow the download+ if (!view.dataroom) {+ return res.status(404).json({ error: "Error downloading" });+ }- 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);-- downloadFolders = downloadFolders.filter((folder) =>- permittedFolderIds.includes(folder.id),- );- downloadDocuments = downloadDocuments.filter((doc) =>- permittedDocumentIds.includes(doc.id),- );- }+ // if dataroom does not allow bulk download, we should not allow the download+ if (!view.dataroom.allowBulkDownload) {+ return res+ .status(403)+ .json({ error: "Bulk download is disabled for this dataroom" });+ }- // Create individual document views for each document being downloaded- const downloadableDocuments = downloadDocuments.filter(- (doc) =>- doc.document.versions[0] &&- doc.document.versions[0].type !== "notion" &&- doc.document.versions[0].storageType !== "VERCEL_BLOB",- );+ // 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" });+ }- // For bulk downloads, only store metadata if there are less than 100 documents- const downloadMetadata =- downloadableDocuments.length < 100- ? {- dataroomName: view.dataroom!.name,- documentCount: downloadableDocuments.length,- documents: downloadableDocuments.map((doc) => ({- id: doc.document.id,- name: doc.document.name,- })),- }- : {- dataroomName: view.dataroom!.name,- documentCount: downloadableDocuments.length,- };-- await prisma.view.createMany({- data: downloadableDocuments.map((doc) => ({- viewType: "DOCUMENT_VIEW",- documentId: doc.document.id,- linkId: linkId,- dataroomId: view.dataroom!.id,- groupId: view.groupId,- dataroomViewId: view.id,- viewerEmail: view.viewerEmail,- downloadedAt: new Date(),- downloadType: "BULK",- downloadMetadata: downloadMetadata,- viewerId: view.viewerId,- verified: view.verified,- })),- skipDuplicates: true,- });+ let downloadFolders = view.dataroom.folders;+ let downloadDocuments = view.dataroom.documents;- // Construct folderStructure and fileKeys- const folderStructure: {- [key: string]: {- name: string;- path: string;- files: {- name: string;- key: string;- type?: string;- numPages?: number;- needsWatermark?: boolean;- }[];- };- } = {};- const fileKeys: string[] = [];-- // Create a map of folder IDs to folder names- const folderMap = new Map(- downloadFolders.map((folder) => [- folder.path,- { name: folder.name, id: folder.id },- ]),+ // Check permissions based on groupId (ViewerGroup) or permissionGroupId (PermissionGroup)+ const effectiveGroupId = view.groupId || view.link.permissionGroupId;++ if (effectiveGroupId) {+ let groupPermissions: any[] = [];++ if (view.groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: { groupId: view.groupId, canDownload: true },+ });+ } else if (view.link.permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions = await prisma.permissionGroupAccessControls.findMany({+ where: {+ groupId: view.link.permissionGroupId,+ 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);++ downloadFolders = downloadFolders.filter((folder) =>+ permittedFolderIds.includes(folder.id),+ );+ downloadDocuments = downloadDocuments.filter((doc) =>+ permittedDocumentIds.includes(doc.id),);+ }- const addFileToStructure = (- path: string,- fileName: string,- fileKey: string,- fileType?: string,- numPages?: number,- ) => {- 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: [],- };+ // Create individual document views for each document being downloaded+ const downloadableDocuments = downloadDocuments.filter(+ (doc) =>+ doc.document.versions[0] &&+ doc.document.versions[0].type !== "notion" &&+ doc.document.versions[0].storageType !== "VERCEL_BLOB",+ );++ // For bulk downloads, only store metadata if there are less than 100 documents+ const downloadMetadata =+ downloadableDocuments.length < 100+ ? {+ dataroomName: view.dataroom!.name,+ documentCount: downloadableDocuments.length,+ documents: downloadableDocuments.map((doc) => ({+ id: doc.document.id,+ name: doc.document.name,+ })),}- });+ : {+ dataroomName: view.dataroom!.name,+ documentCount: downloadableDocuments.length,+ };- // 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,+ await prisma.view.createMany({+ data: downloadableDocuments.map((doc) => ({+ viewType: "DOCUMENT_VIEW",+ documentId: doc.document.id,+ linkId: linkId,+ dataroomId: view.dataroom!.id,+ groupId: view.groupId,+ dataroomViewId: view.id,+ viewerEmail: view.viewerEmail,+ downloadedAt: new Date(),+ downloadType: "BULK",+ downloadMetadata: downloadMetadata,+ viewerId: view.viewerId,+ verified: view.verified,+ })),+ skipDuplicates: true,+ });++ // Construct folderStructure and fileKeys+ const folderStructure: {+ [key: string]: {+ name: string;+ path: string;+ files: {+ name: string;+ key: string;+ type?: string;+ numPages?: number;+ needsWatermark?: boolean;+ }[];+ };+ } = {};+ const fileKeys: string[] = [];++ // Create a map of folder IDs to folder names+ const folderMap = new Map(+ downloadFolders.map((folder) => [+ folder.path,+ { name: folder.name, id: folder.id },+ ]),+ );++ const addFileToStructure = (+ path: string,+ fileName: string,+ fileKey: string,+ fileType?: string,+ numPages?: number,+ ) => {+ 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: [],};}+ });- const needsWatermark =- view.link.enableWatermark &&- (fileType === "pdf" || fileType === "image");+ // 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,- type: fileType,- numPages: numPages,- needsWatermark: needsWatermark ?? undefined,- });- fileKeys.push(fileKey);- };+ const needsWatermark =+ view.link.enableWatermark &&+ (fileType === "pdf" || fileType === "image");++ folderStructure[path].files.push({+ name: fileName,+ key: fileKey,+ type: fileType,+ numPages: numPages,+ needsWatermark: needsWatermark ?? undefined,+ });+ fileKeys.push(fileKey);+ };++ // Add root level documents+ downloadDocuments+ .filter((doc) => !doc.folderId)+ .filter((doc) => doc.document.versions[0].type !== "notion")+ .filter((doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB")+ .forEach((doc) => {+ const fileKey =+ view.link.enableWatermark && doc.document.versions[0].type === "pdf"+ ? doc.document.versions[0].file+ : (doc.document.versions[0].originalFile ??+ doc.document.versions[0].file);++ addFileToStructure(+ "/",+ doc.document.name,+ fileKey,+ doc.document.versions[0].type ?? undefined,+ doc.document.versions[0].numPages ?? undefined,+ );+ });- // Add root level documents- downloadDocuments- .filter((doc) => !doc.folderId)+ // Add documents in folders+ 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")- .forEach((doc) => {+ .filter(+ (doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB",+ );++ folderDocs &&+ folderDocs.forEach((doc) => {+ // Use .file if watermark is enabled and document is PDF, otherwise use .originalFileconst fileKey =view.link.enableWatermark && doc.document.versions[0].type === "pdf"? doc.document.versions[0].file@@ -304,7 +361,7 @@ export default async function handle(doc.document.versions[0].file);addFileToStructure(- "/",+ folder.path,doc.document.name,fileKey,doc.document.versions[0].type ?? undefined,@@ -312,140 +369,115 @@ export default async function handle();});- // Add documents in folders- 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) => {- // Use .file if watermark is enabled and document is PDF, otherwise use .originalFile- const fileKey =- view.link.enableWatermark &&- doc.document.versions[0].type === "pdf"- ? doc.document.versions[0].file- : (doc.document.versions[0].originalFile ??- doc.document.versions[0].file);-- addFileToStructure(- folder.path,- doc.document.name,- fileKey,- doc.document.versions[0].type ?? undefined,- doc.document.versions[0].numPages ?? undefined,- );- });-- // If the folder is empty, ensure it's still added to the structure- if (folderDocs && folderDocs.length === 0) {- addFileToStructure(folder.path, "", "");- }- });-- if (fileKeys.length === 0) {- 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,- dataroomId: view.dataroom.id,- linkId,- viewerEmail: view.viewerEmail ?? undefined,- viewerId: view.viewerId ?? undefined,- metadata: {- documentCount: downloadDocuments.length,- isBulkDownload: true,- },- });- } catch (error) {- console.error("Error sending Slack notification:", error);- }+ // If the folder is empty, ensure it's still added to the structure+ if (folderDocs && folderDocs.length === 0) {+ addFileToStructure(folder.path, "", "");}+ });- // Get team-specific storage configuration- const teamId = view.dataroom!.teamId;- const [client, storageConfig] = await Promise.all([- getLambdaClientForTeam(teamId),- 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,- Payload: JSON.stringify({- sourceBucket: storageConfig.bucket,- fileKeys: fileKeys,- folderStructure: folderStructure,- dataroomName: view.dataroom!.name,- zipFileName,- watermarkConfig: view.link.enableWatermark- ? {- enabled: true,- config: view.link.watermarkConfig,- viewerData: {- email: view.viewerEmail,- date: (view.viewedAt- ? new Date(view.viewedAt)- : new Date()- ).toLocaleDateString(),- time: (view.viewedAt- ? new Date(view.viewedAt)- : new Date()- ).toLocaleTimeString(),- link: view.link.name,- ipAddress: getIpAddress(req.headers),- },- }- : { enabled: false },- }),- };-- 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);+ if (fileKeys.length === 0) {+ return res.status(404).json({ error: "No files to download" });+ }- 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) {- console.error("Error starting bulk download:", error);- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ if (view.dataroom?.teamId) {+ void notifyDocumentDownload({+ teamId: view.dataroom.teamId,+ documentId: undefined,+ dataroomId: view.dataroom.id,+ linkId,+ viewerEmail: view.viewerEmail ?? undefined,+ viewerId: view.viewerId ?? undefined,+ metadata: {+ documentCount: downloadDocuments.length,+ isBulkDownload: true,+ },+ }).catch((err) =>+ console.error("Error sending Slack notification:", err),+ );}- } else {- // We only allow POST requests- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);++ const teamId = view.dataroom!.teamId;+ const storageConfig = await getTeamStorageConfigById(teamId);+ const sendEmail =+ !!emailNotification && !!view.viewerEmail && !!session.verified;++ const job = await downloadJobStore.createJob({+ type: "bulk",+ status: "PENDING",+ dataroomId: view.dataroom!.id,+ dataroomName: view.dataroom!.name,+ totalFiles: fileKeys.length,+ processedFiles: 0,+ progress: 0,+ teamId,+ userId: view.viewerId ?? view.viewerEmail ?? "viewer",+ linkId,+ viewerId: view.viewerId ?? undefined,+ viewerEmail: view.viewerEmail ?? undefined,+ emailNotification: sendEmail,+ emailAddress: sendEmail ? (view.viewerEmail ?? undefined) : undefined,+ });++ const handle = await bulkDownloadTask.trigger(+ {+ jobId: job.id,+ dataroomId: view.dataroom!.id,+ dataroomName: view.dataroom!.name,+ teamId,+ folderStructure,+ fileKeys,+ sourceBucket: storageConfig.bucket,+ watermarkConfig: view.link.enableWatermark+ ? {+ enabled: true,+ config: view.link.watermarkConfig,+ viewerData: {+ email: view.viewerEmail,+ date: (view.viewedAt+ ? new Date(view.viewedAt)+ : new Date()+ ).toLocaleDateString(),+ time: (view.viewedAt+ ? new Date(view.viewedAt)+ : new Date()+ ).toLocaleTimeString(),+ link: view.link.name,+ ipAddress: getIpAddress(req.headers),+ },+ }+ : { enabled: false },+ viewId: view.id,+ viewerId: view.viewerId ?? undefined,+ viewerEmail: view.viewerEmail ?? undefined,+ linkId,+ emailNotification: sendEmail,+ emailAddress: sendEmail ? (view.viewerEmail ?? undefined) : undefined,+ },+ {+ idempotencyKey: job.id,+ tags: [+ `team_${teamId}`,+ `dataroom_${view.dataroom!.id}`,+ `job_${job.id}`,+ `link_${linkId}`,+ ],+ },+ );++ await downloadJobStore.updateJob(job.id, { triggerRunId: handle.id });++ return res.status(202).json({+ jobId: job.id,+ status: "PENDING",+ message: sendEmail+ ? "Download started. We'll email you when it's ready."+ : "Download started. You can check status on the downloads page.",+ });+ } 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/links/download/by-email.ts b/pages/api/links/download/by-email.tsnew file mode 100644index 00000000..e4541c5e--- /dev/null+++ b/pages/api/links/download/by-email.ts@@ -0,0 +1,35 @@+import { NextApiRequest, NextApiResponse } from "next";++import prisma from "@/lib/prisma";++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 linkId = req.query.linkId as string;+ const email = req.query.email as string;+ if (!linkId || !email) {+ return res.status(400).json({ error: "linkId and email are required" });+ }++ const view = await prisma.view.findFirst({+ where: {+ linkId,+ viewType: "DATAROOM_VIEW",+ viewerEmail: { equals: email, mode: "insensitive" },+ },+ select: { id: true },+ orderBy: { viewedAt: "desc" },+ });++ if (!view) {+ return res.status(404).json({ error: "No view found for this link and email" });+ }++ return res.status(200).json({ viewId: view.id });+}diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.tsindex a0a7f04a..c4782e45 100644--- a/pages/api/links/download/dataroom-folder.ts+++ b/pages/api/links/download/dataroom-folder.ts@@ -1,17 +1,18 @@import { NextApiRequest, NextApiResponse } from "next";import { getTeamStorageConfigById } from "@/ee/features/storage/config";-import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";import { ItemType, ViewType } from "@prisma/client";import slugify from "@sindresorhus/slugify";-import { getLambdaClientForTeam } from "@/lib/files/aws-client";+import { verifyDataroomSessionInPagesRouter } from "@/lib/auth/dataroom-auth";import { notifyDocumentDownload } from "@/lib/integrations/slack/events";import prisma from "@/lib/prisma";+import { downloadJobStore } from "@/lib/redis-download-job-store";+import { bulkDownloadTask } from "@/lib/trigger/bulk-download";import { getIpAddress } from "@/lib/utils/ip";export const config = {- maxDuration: 300,+ maxDuration: 60,};export default async function handler(@@ -24,11 +25,12 @@ export default async function handler(}try {- const { folderId, dataroomId, viewId, linkId } = req.body as {+ const { folderId, dataroomId, viewId, linkId, emailNotification } = req.body as {folderId: string;dataroomId: string;viewId: string;linkId: string;+ emailNotification?: boolean;};if (!folderId) {return res@@ -65,12 +67,35 @@ export default async function handler(},});- // if view does not exist, we should not allow the downloadif (!view) {return res.status(404).json({ error: "Error downloading" });}- // if link does not allow download, we should not allow the download+ const session = await verifyDataroomSessionInPagesRouter(+ req,+ linkId,+ dataroomId,+ );+ if (!session) {+ return res.status(401).json({ error: "Session required to download" });+ }++ // Verified session and email are only required when the viewer requested email notification+ if (emailNotification) {+ if (!view.viewerEmail) {+ return res.status(400).json({+ error:+ "Email is required to receive download notifications. Enter your email in the dataroom.",+ });+ }+ if (!session.verified) {+ return res.status(403).json({+ error:+ "Verify your email with the one-time code to receive a notification when the download is ready.",+ });+ }+ }+if (!view.link.allowDownload) {return res.status(403).json({ error: "Error downloading" });}@@ -357,24 +382,46 @@ export default async function handler(documentCount: allDocuments.length,isFolderDownload: true,},- }).catch((error) => {- console.error("Error sending Slack notification:", error);- });+ }).catch((err) => console.error("Error sending Slack notification:", err));}- // Get team-specific storage configuration- const [client, storageConfig] = await Promise.all([- getLambdaClientForTeam(view.link.teamId!),- getTeamStorageConfigById(view.link.teamId!),- ]);+ const teamId = view.link.teamId!;+ const storageConfig = await getTeamStorageConfigById(teamId);+ const dataroom = await prisma.dataroom.findUnique({+ where: { id: dataroomId },+ select: { name: true },+ });+ const dataroomName = dataroom?.name ?? "Dataroom";+ const sendEmail =+ !!emailNotification && !!view.viewerEmail && !!session.verified;++ const job = await downloadJobStore.createJob({+ type: "folder",+ status: "PENDING",+ dataroomId,+ dataroomName,+ folderName: rootFolder.name,+ totalFiles: fileKeys.length,+ processedFiles: 0,+ progress: 0,+ teamId,+ userId: view.viewerId ?? view.viewerEmail ?? "viewer",+ linkId,+ viewerId: view.viewerId ?? undefined,+ viewerEmail: view.viewerEmail ?? undefined,+ emailNotification: sendEmail,+ emailAddress: sendEmail ? view.viewerEmail ?? undefined : undefined,+ });- const params = {- FunctionName: `bulk-download-zip-creator-${process.env.NODE_ENV === "development" ? "dev" : "prod"}`,- InvocationType: InvocationType.RequestResponse,- Payload: JSON.stringify({- sourceBucket: storageConfig.bucket,- fileKeys,+ const handle = await bulkDownloadTask.trigger(+ {+ jobId: job.id,+ dataroomId,+ dataroomName,+ teamId,folderStructure,+ fileKeys,+ sourceBucket: storageConfig.bucket,watermarkConfig: view.link.enableWatermark? {enabled: true,@@ -392,18 +439,29 @@ export default async function handler(},}: { enabled: false },- }),- };-- const command = new InvokeCommand(params);- const response = await client.send(command);-- if (!response.Payload) throw new Error("Lambda returned empty payload");+ viewId: view.id,+ viewerId: view.viewerId ?? undefined,+ viewerEmail: view.viewerEmail ?? undefined,+ linkId,+ emailNotification: sendEmail,+ emailAddress: sendEmail ? view.viewerEmail ?? undefined : undefined,+ folderName: rootFolder.name,+ },+ {+ idempotencyKey: job.id,+ tags: [`team_${teamId}`, `dataroom_${dataroomId}`, `job_${job.id}`, `link_${linkId}`],+ },+ );- const parsed = JSON.parse(new TextDecoder().decode(response.Payload));- const { downloadUrl } = JSON.parse(parsed.body);+ await downloadJobStore.updateJob(job.id, { triggerRunId: handle.id });- res.status(200).json({ downloadUrl });+ return res.status(202).json({+ jobId: job.id,+ status: "PENDING",+ message: sendEmail+ ? "Download started. We'll email you when it's ready."+ : "Download started. Check the downloads page for status.",+ });} catch (error) {console.error("Download error:", error);return res.status(500).json({diff --git a/pages/api/links/download/file/[jobId]/[partIndex].ts b/pages/api/links/download/file/[jobId]/[partIndex].tsnew file mode 100644index 00000000..fc923fcd--- /dev/null+++ b/pages/api/links/download/file/[jobId]/[partIndex].ts@@ -0,0 +1,57 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getDataroomSessionByLinkIdInPagesRouter } from "@/lib/auth/dataroom-auth";+import prisma from "@/lib/prisma";+import { downloadJobStore } from "@/lib/redis-download-job-store";++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 linkId = req.query.linkId as string;+ const { jobId, partIndex } = req.query as { jobId: string; partIndex: string };+ if (!linkId || !jobId || partIndex == null) {+ return res.status(400).json({ error: "linkId, jobId and partIndex required" });+ }++ const session = await getDataroomSessionByLinkIdInPagesRouter(req, linkId);+ if (!session) {+ return res.status(401).json({ error: "Session required" });+ }++ const view = await prisma.view.findUnique({+ where: { id: session.viewId },+ select: { viewerEmail: true },+ });+ if (!view?.viewerEmail) {+ return res.status(403).json({ error: "Viewer email not found" });+ }++ const job = await downloadJobStore.getJob(jobId);+ if (!job) {+ return res+ .status(404)+ .json({ error: "Download job not found or expired" });+ }++ if (job.linkId !== linkId || job.viewerEmail !== view.viewerEmail) {+ return res.status(403).json({ error: "Job does not belong to this viewer" });+ }++ if (job.status !== "COMPLETED" || !job.downloadUrls?.length) {+ return res.status(400).json({ error: "Download not ready" });+ }++ const index = parseInt(partIndex, 10);+ if (Number.isNaN(index) || index < 0 || index >= job.downloadUrls.length) {+ return res.status(400).json({ error: "Invalid part index" });+ }++ const presignedUrl = job.downloadUrls[index];+ res.redirect(302, presignedUrl);+}diff --git a/pages/api/links/download/jobs.ts b/pages/api/links/download/jobs.tsnew file mode 100644index 00000000..cff3bc54--- /dev/null+++ b/pages/api/links/download/jobs.ts@@ -0,0 +1,41 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getDataroomSessionByLinkIdInPagesRouter } from "@/lib/auth/dataroom-auth";+import prisma from "@/lib/prisma";+import { downloadJobStore } from "@/lib/redis-download-job-store";++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 linkId = req.query.linkId as string;+ if (!linkId) {+ return res.status(400).json({ error: "linkId is required" });+ }++ const session = await getDataroomSessionByLinkIdInPagesRouter(req, linkId);+ if (!session) {+ return res.status(401).json({ error: "Session required" });+ }++ const view = await prisma.view.findUnique({+ where: { id: session.viewId },+ select: { viewerEmail: true },+ });+ if (!view?.viewerEmail) {+ return res.status(200).json([]);+ }++ const jobs = await downloadJobStore.getViewerJobs(+ linkId,+ view.viewerEmail,+ 20,+ );++ return res.status(200).json(jobs);+}diff --git a/pages/api/links/download/verify.ts b/pages/api/links/download/verify.tsnew file mode 100644index 00000000..bad5b6b7--- /dev/null+++ b/pages/api/links/download/verify.ts@@ -0,0 +1,198 @@+import { NextApiRequest, NextApiResponse } from "next";++import { parse } from "cookie";++import {+ createDataroomSession,+ getDataroomSessionByLinkIdInPagesRouter,+ updateDataroomSessionVerified,+} from "@/lib/auth/dataroom-auth";+import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";+import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";+import { generateOTP } from "@/lib/utils/generate-otp";+import { getIpAddress } from "@/lib/utils/ip";++const OTP_IDENTIFIER_PREFIX = "download-otp:";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ const linkId = req.query.linkId as string;+ if (!linkId) {+ return res.status(400).json({ error: "linkId is required" });+ }++ const session = await getDataroomSessionByLinkIdInPagesRouter(req, linkId);+ if (!session) {+ return res+ .status(401)+ .json({ error: "Session required", verified: false });+ }+ return res.status(200).json({ verified: session.verified });+ }++ if (req.method !== "POST") {+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const { linkId, viewId, email, code } = req.body as {+ linkId?: string;+ viewId?: string;+ email?: string;+ code?: string;+ };++ if (!linkId || !viewId || !email) {+ return res+ .status(400)+ .json({ error: "linkId, viewId and email are required" });+ }++ const view = await prisma.view.findUnique({+ where: { id: viewId, linkId, viewType: "DATAROOM_VIEW" },+ select: {+ id: true,+ dataroomId: true,+ viewerId: true,+ viewerEmail: true,+ link: { select: { teamId: true } },+ },+ });++ if (!view || view.viewerEmail?.toLowerCase() !== email.toLowerCase()) {+ return res+ .status(404)+ .json({ error: "View not found or email does not match" });+ }++ if (!view.link?.teamId) {+ return res.status(400).json({ error: "Link has no team" });+ }++ if (!code) {+ const { success: emailLimitSuccess } = await ratelimit(1, "30 s").limit(+ `${OTP_IDENTIFIER_PREFIX}${linkId}:${email.toLowerCase()}`,+ );+ if (!emailLimitSuccess) {+ return res.status(429).json({+ error: "Please wait 30 seconds before requesting another code.",+ });+ }++ const ipAddressValue = getIpAddress(req.headers) ?? "unknown";+ const { success: ipSuccess } = await ratelimit(10, "1 m").limit(+ `download-otp-ip:${ipAddressValue}`,+ );+ if (!ipSuccess) {+ return res.status(429).json({+ error: "Too many requests. Try again later.",+ });+ }++ await prisma.verificationToken.deleteMany({+ where: {+ identifier: `${OTP_IDENTIFIER_PREFIX}${linkId}:${email.toLowerCase()}`,+ },+ });++ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10);++ await prisma.verificationToken.create({+ data: {+ token: otpCode,+ identifier: `${OTP_IDENTIFIER_PREFIX}${linkId}:${email.toLowerCase()}`,+ expires: expiresAt,+ },+ });++ await sendOtpVerificationEmail(email, otpCode, true, view.link.teamId);++ return res.status(200).json({+ type: "email-verification",+ message: "Verification code sent to your email.",+ });+ }++ const { success: ipSuccess } = await ratelimit(10, "1 m").limit(+ `download-verify-ip:${getIpAddress(req.headers) ?? "unknown"}`,+ );+ if (!ipSuccess) {+ return res.status(429).json({ error: "Too many requests." });+ }++ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: code,+ identifier: `${OTP_IDENTIFIER_PREFIX}${linkId}:${email.toLowerCase()}`,+ },+ });++ if (!verification) {+ return res.status(401).json({+ error: "Invalid or expired code. Request a new code.",+ resetVerification: true,+ });+ }++ if (Date.now() > verification.expires.getTime()) {+ await prisma.verificationToken.delete({+ where: { token: code },+ });+ return res.status(401).json({+ error: "Code expired. Request a new code.",+ resetVerification: true,+ });+ }++ await prisma.verificationToken.delete({+ where: { token: code },+ });++ await prisma.view.update({+ where: { id: viewId },+ data: { verified: true },+ });++ const cookies = parse(req.headers.cookie || "");+ let sessionToken = cookies[`pm_drs_${linkId}`];++ const needNewSession = async () => {+ if (!view.dataroomId) return;+ const ipAddressValue = getIpAddress(req.headers) ?? "unknown";+ const { token, expiresAt } = await createDataroomSession(+ view.dataroomId,+ linkId,+ viewId,+ ipAddressValue,+ true,+ view.viewerId ?? undefined,+ );+ sessionToken = token;+ const maxAge = Math.floor((expiresAt - Date.now()) / 1000);+ res.setHeader("Set-Cookie", [+ `pm_drs_${linkId}=${token}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax`,+ ]);+ };++ if (sessionToken) {+ const updated = await updateDataroomSessionVerified(sessionToken, true);+ // If update failed (e.g. session expired and was deleted), create a new+ // session so the next request (e.g. bulk) has a valid session.+ if (!updated) {+ await needNewSession();+ }+ } else {+ await needNewSession();+ }++ return res.status(200).json({+ type: "verified",+ message: "Email verified. You can receive download notifications.",+ });+}diff --git a/pages/view/[linkId]/downloads.tsx b/pages/view/[linkId]/downloads.tsxnew file mode 100644index 00000000..3975e381--- /dev/null+++ b/pages/view/[linkId]/downloads.tsx@@ -0,0 +1,368 @@+import { GetServerSideProps } from "next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";++import {+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ Download,+ FileArchive,+ FolderOpen,+ Loader2,+} from "lucide-react";++import { DownloadOtpVerification } from "@/components/view/dataroom/download-otp-verification";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";++type Job = {+ id: string;+ status: string;+ progress: number;+ totalFiles: number;+ processedFiles: number;+ downloadUrls?: string[];+ error?: string;+ dataroomName: string;+ type?: "bulk" | "folder";+ folderName?: string;+ createdAt: string;+ expiresAt?: string;+};++export const getServerSideProps: GetServerSideProps = async (context) => {+ const linkId = context.params?.linkId as string;+ return { props: { linkId: linkId ?? null } };+};++export default function ViewDownloadsPage({+ linkId: linkIdProp,+}: {+ linkId: string | null;+}) {+ const router = useRouter();+ const linkId = (router.query.linkId as string) ?? linkIdProp ?? undefined;++ const [loading, setLoading] = useState(true);+ const [hasSession, setHasSession] = useState<boolean | null>(null);+ const [email, setEmail] = useState("");+ const [viewId, setViewId] = useState<string | null>(null);+ const [step, setStep] = useState<"session" | "email" | "otp" | "list">("session");+ const [jobs, setJobs] = useState<Job[]>([]);+ const [jobsLoading, setJobsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [expandedJobId, setExpandedJobId] = useState<string | null>(null);++ const checkSession = useCallback(async () => {+ if (!linkId) return;+ setLoading(true);+ setError(null);+ try {+ const res = await fetch(+ `/api/links/download/verify?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (res.ok) {+ setHasSession(true);+ setStep("list");+ return;+ }+ setHasSession(false);+ setStep("email");+ } catch {+ setHasSession(false);+ setStep("email");+ } finally {+ setLoading(false);+ }+ }, [linkId]);++ useEffect(() => {+ if (!linkId) return;+ checkSession();+ }, [linkId, checkSession]);++ const fetchJobs = useCallback(async () => {+ if (!linkId) return;+ setJobsLoading(true);+ try {+ const res = await fetch(+ `/api/links/download/jobs?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (res.ok) {+ const data = await res.json();+ setJobs(Array.isArray(data) ? data : []);+ } else {+ setJobs([]);+ }+ } catch {+ setJobs([]);+ } finally {+ setJobsLoading(false);+ }+ }, [linkId]);++ useEffect(() => {+ if (step === "list" && linkId) {+ fetchJobs();+ }+ }, [step, linkId, fetchJobs]);++ const handleEmailSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!linkId || !email.trim()) return;+ setError(null);+ try {+ const res = await fetch(+ `/api/links/download/by-email?linkId=${encodeURIComponent(linkId)}&email=${encodeURIComponent(email.trim())}`,+ );+ if (!res.ok) {+ setError("No access found for this email. Use the email you used to open the dataroom.");+ return;+ }+ const data = await res.json();+ setViewId(data.viewId);+ setStep("otp");+ } catch {+ setError("Something went wrong.");+ }+ };++ const handleOtpVerified = () => {+ setHasSession(true);+ setStep("list");+ };++ const handleDownload = (url: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.rel = "noopener noreferrer";+ document.body.appendChild(a);+ a.click();+ setTimeout(() => document.body.removeChild(a), 100);+ };++ const formatExpiration = (expiresAt?: string) => {+ if (!expiresAt) return "";+ const exp = new Date(expiresAt);+ const now = new Date();+ const d = Math.floor((exp.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));+ if (d > 0) return `${d} day${d > 1 ? "s" : ""}`;+ const h = Math.floor((exp.getTime() - now.getTime()) / (1000 * 60 * 60));+ return h > 0 ? `${h} hour${h > 1 ? "s" : ""}` : "soon";+ };++ const getJobTitle = (job: Job) => {+ if (job.type === "folder" && job.folderName) {+ return (+ <>+ <span className="font-medium">{job.dataroomName}</span>+ <span className="text-muted-foreground">+ {" "}+ — <FolderOpen className="mr-0.5 inline h-3.5 w-3" />+ Folder: {job.folderName}+ </span>+ </>+ );+ }+ return (+ <>+ <span className="font-medium">{job.dataroomName}</span>+ {job.type === "bulk" && (+ <span className="text-muted-foreground"> — Full dataroom</span>+ )}+ </>+ );+ };++ const handleDownloadAll = (urls: string[]) => {+ urls.forEach((url, i) => {+ setTimeout(() => handleDownload(url), i * 300);+ });+ };++ if (!linkId) {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ );+ }++ if (loading) {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ );+ }++ if (step === "email") {+ return (+ <div className="mx-auto flex min-h-screen max-w-sm flex-col justify-center px-4">+ <h1 className="text-xl font-semibold">View your downloads</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Enter the email you used to access this dataroom.+ </p>+ <form onSubmit={handleEmailSubmit} className="mt-6 space-y-4">+ <Input+ type="email"+ placeholder="[email protected]"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ required+ />+ {error && <p className="text-sm text-destructive">{error}</p>}+ <Button type="submit" className="w-full">+ Continue+ </Button>+ </form>+ </div>+ );+ }++ if (step === "otp" && viewId) {+ return (+ <div className="mx-auto flex min-h-screen max-w-sm flex-col justify-center px-4">+ <h1 className="text-xl font-semibold">Verify your email</h1>+ <DownloadOtpVerification+ linkId={linkId}+ viewId={viewId}+ email={email.trim()}+ onVerified={handleOtpVerified}+ />+ </div>+ );+ }++ return (+ <div className="mx-auto min-h-screen max-w-2xl px-4 py-10">+ <h1 className="text-xl font-semibold">Your downloads</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Download your prepared files below. Links expire after 3 days.+ </p>++ {jobsLoading ? (+ <div className="mt-8 flex justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ ) : jobs.length === 0 ? (+ <p className="mt-8 text-sm text-muted-foreground">+ You have no downloads yet. Start a download from the dataroom to see it here.+ </p>+ ) : (+ <ul className="mt-6 space-y-4">+ {jobs.map((job) => (+ <li+ key={job.id}+ className="flex flex-col gap-2 rounded-lg border p-4"+ >+ <div className="flex items-center justify-between">+ <div className="min-w-0 flex-1 text-sm">+ {getJobTitle(job)}+ </div>+ <span className="ml-2 shrink-0 text-xs text-muted-foreground">+ {new Date(job.createdAt).toLocaleString()}+ </span>+ </div>+ <div className="flex items-center gap-2 text-sm">+ {job.status === "COMPLETED" ? (+ <CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />+ ) : job.status === "PROCESSING" || job.status === "PENDING" ? (+ <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />+ ) : (+ <FileArchive className="h-4 w-4 shrink-0 text-muted-foreground" />+ )}+ <span className="text-muted-foreground">+ {job.status === "COMPLETED"+ ? "Ready"+ : job.status === "PROCESSING"+ ? `${job.processedFiles} / ${job.totalFiles} files`+ : job.status}+ </span>+ </div>+ {job.status === "COMPLETED" &&+ job.downloadUrls &&+ job.downloadUrls.length > 0 && (+ <div className="mt-2 flex flex-wrap items-center gap-2">+ {job.downloadUrls.length === 1 ? (+ <Button+ size="sm"+ onClick={() => handleDownload(job.downloadUrls![0])}+ >+ <Download className="mr-1 h-3 w-3" />+ Download+ </Button>+ ) : (+ <>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ setExpandedJobId(+ expandedJobId === job.id ? null : job.id,+ )+ }+ >+ {expandedJobId === job.id ? (+ <>+ <ChevronUp className="mr-1 h-3 w-3" />+ Hide parts+ </>+ ) : (+ <>+ <ChevronDown className="mr-1 h-3 w-3" />+ Show parts ({job.downloadUrls!.length})+ </>+ )}+ </Button>+ {expandedJobId === job.id && (+ <div className="w-full space-y-2 rounded-md border bg-muted/30 p-3">+ <Button+ size="sm"+ className="w-full"+ onClick={() =>+ handleDownloadAll(job.downloadUrls!)+ }+ >+ <Download className="mr-2 h-3 w-3" />+ Download all ({job.downloadUrls!.length} parts)+ </Button>+ <p className="text-xs text-muted-foreground">+ Or download individually:+ </p>+ <div className="max-h-32 space-y-1 overflow-y-auto">+ {job.downloadUrls!.map((url, i) => (+ <Button+ key={i}+ variant="outline"+ size="sm"+ className="w-full justify-start"+ onClick={() => handleDownload(url)}+ >+ <FileArchive className="mr-2 h-3 w-3" />+ Part {i + 1} of{" "}+ {job.downloadUrls!.length}+ </Button>+ ))}+ </div>+ </div>+ )}+ </>+ )}+ {job.expiresAt && (+ <span className="text-xs text-muted-foreground">+ Expires {formatExpiration(job.expiresAt)}+ </span>+ )}+ </div>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}diff --git a/pages/view/domains/[domain]/[slug]/downloads.tsx b/pages/view/domains/[domain]/[slug]/downloads.tsxnew file mode 100644index 00000000..c18e044b--- /dev/null+++ b/pages/view/domains/[domain]/[slug]/downloads.tsx@@ -0,0 +1,390 @@+import { GetServerSideProps } from "next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";++import {+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ Download,+ FileArchive,+ FolderOpen,+ Loader2,+} from "lucide-react";++import prisma from "@/lib/prisma";++import { DownloadOtpVerification } from "@/components/view/dataroom/download-otp-verification";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";++type Job = {+ id: string;+ status: string;+ progress: number;+ totalFiles: number;+ processedFiles: number;+ downloadUrls?: string[];+ error?: string;+ dataroomName: string;+ type?: "bulk" | "folder";+ folderName?: string;+ createdAt: string;+ expiresAt?: string;+};++export const getServerSideProps: GetServerSideProps = async (context) => {+ const domain = context.params?.domain as string;+ const slug = context.params?.slug as string;+ if (!domain || !slug) {+ return { notFound: true };+ }+ const link = await prisma.link.findUnique({+ where: {+ domainSlug_slug: { slug, domainSlug: domain },+ },+ select: { id: true },+ });+ if (!link) {+ return { notFound: true };+ }+ return { props: { linkId: link.id, domain, slug } };+};++export default function DomainDownloadsPage({+ linkId: linkIdProp,+ domain,+ slug,+}: {+ linkId: string;+ domain: string;+ slug: string;+}) {+ const router = useRouter();+ const linkId =+ (router.query.linkId as string) ??+ (router.query.slug ? linkIdProp : undefined) ??+ linkIdProp;++ const [loading, setLoading] = useState(true);+ const [hasSession, setHasSession] = useState<boolean | null>(null);+ const [email, setEmail] = useState("");+ const [viewId, setViewId] = useState<string | null>(null);+ const [step, setStep] = useState<"session" | "email" | "otp" | "list">("session");+ const [jobs, setJobs] = useState<Job[]>([]);+ const [jobsLoading, setJobsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [expandedJobId, setExpandedJobId] = useState<string | null>(null);++ const checkSession = useCallback(async () => {+ if (!linkId) return;+ setLoading(true);+ setError(null);+ try {+ const res = await fetch(+ `/api/links/download/verify?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (res.ok) {+ setHasSession(true);+ setStep("list");+ return;+ }+ setHasSession(false);+ setStep("email");+ } catch {+ setHasSession(false);+ setStep("email");+ } finally {+ setLoading(false);+ }+ }, [linkId]);++ useEffect(() => {+ if (!linkId) return;+ checkSession();+ }, [linkId, checkSession]);++ const fetchJobs = useCallback(async () => {+ if (!linkId) return;+ setJobsLoading(true);+ try {+ const res = await fetch(+ `/api/links/download/jobs?linkId=${encodeURIComponent(linkId)}`,+ { credentials: "include" },+ );+ if (res.ok) {+ const data = await res.json();+ setJobs(Array.isArray(data) ? data : []);+ } else {+ setJobs([]);+ }+ } catch {+ setJobs([]);+ } finally {+ setJobsLoading(false);+ }+ }, [linkId]);++ useEffect(() => {+ if (step === "list" && linkId) {+ fetchJobs();+ }+ }, [step, linkId, fetchJobs]);++ const handleEmailSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!linkId || !email.trim()) return;+ setError(null);+ try {+ const res = await fetch(+ `/api/links/download/by-email?linkId=${encodeURIComponent(linkId)}&email=${encodeURIComponent(email.trim())}`,+ );+ if (!res.ok) {+ setError("No access found for this email. Use the email you used to open the dataroom.");+ return;+ }+ const data = await res.json();+ setViewId(data.viewId);+ setStep("otp");+ } catch {+ setError("Something went wrong.");+ }+ };++ const handleOtpVerified = () => {+ setHasSession(true);+ setStep("list");+ };++ const handleDownload = (url: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.rel = "noopener noreferrer";+ document.body.appendChild(a);+ a.click();+ setTimeout(() => document.body.removeChild(a), 100);+ };++ const formatExpiration = (expiresAt?: string) => {+ if (!expiresAt) return "";+ const exp = new Date(expiresAt);+ const now = new Date();+ const d = Math.floor((exp.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));+ if (d > 0) return `${d} day${d > 1 ? "s" : ""}`;+ const h = Math.floor((exp.getTime() - now.getTime()) / (1000 * 60 * 60));+ return h > 0 ? `${h} hour${h > 1 ? "s" : ""}` : "soon";+ };++ const getJobTitle = (job: Job) => {+ if (job.type === "folder" && job.folderName) {+ return (+ <>+ <span className="font-medium">{job.dataroomName}</span>+ <span className="text-muted-foreground">+ {" "}+ — <FolderOpen className="mr-0.5 inline h-3.5 w-3" />+ Folder: {job.folderName}+ </span>+ </>+ );+ }+ return (+ <>+ <span className="font-medium">{job.dataroomName}</span>+ {job.type === "bulk" && (+ <span className="text-muted-foreground"> — Full dataroom</span>+ )}+ </>+ );+ };++ const handleDownloadAll = (urls: string[]) => {+ urls.forEach((url, i) => {+ setTimeout(() => handleDownload(url), i * 300);+ });+ };++ if (!linkId) {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ );+ }++ if (loading) {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ );+ }++ if (step === "email") {+ return (+ <div className="mx-auto flex min-h-screen max-w-sm flex-col justify-center px-4">+ <h1 className="text-xl font-semibold">View your downloads</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Enter the email you used to access this dataroom.+ </p>+ <form onSubmit={handleEmailSubmit} className="mt-6 space-y-4">+ <Input+ type="email"+ placeholder="[email protected]"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ required+ />+ {error && <p className="text-sm text-destructive">{error}</p>}+ <Button type="submit" className="w-full">+ Continue+ </Button>+ </form>+ </div>+ );+ }++ if (step === "otp" && viewId) {+ return (+ <div className="mx-auto flex min-h-screen max-w-sm flex-col justify-center px-4">+ <h1 className="text-xl font-semibold">Verify your email</h1>+ <DownloadOtpVerification+ linkId={linkId}+ viewId={viewId}+ email={email.trim()}+ onVerified={handleOtpVerified}+ />+ </div>+ );+ }++ return (+ <div className="mx-auto min-h-screen max-w-2xl px-4 py-10">+ <h1 className="text-xl font-semibold">Your downloads</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Download your prepared files below. Links expire after 3 days.+ </p>++ {jobsLoading ? (+ <div className="mt-8 flex justify-center">+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />+ </div>+ ) : jobs.length === 0 ? (+ <p className="mt-8 text-sm text-muted-foreground">+ You have no downloads yet. Start a download from the dataroom to see it here.+ </p>+ ) : (+ <ul className="mt-6 space-y-4">+ {jobs.map((job) => (+ <li+ key={job.id}+ className="flex flex-col gap-2 rounded-lg border p-4"+ >+ <div className="flex items-center justify-between">+ <div className="min-w-0 flex-1 text-sm">+ {getJobTitle(job)}+ </div>+ <span className="ml-2 shrink-0 text-xs text-muted-foreground">+ {new Date(job.createdAt).toLocaleString()}+ </span>+ </div>+ <div className="flex items-center gap-2 text-sm">+ {job.status === "COMPLETED" ? (+ <CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />+ ) : job.status === "PROCESSING" || job.status === "PENDING" ? (+ <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />+ ) : (+ <FileArchive className="h-4 w-4 shrink-0 text-muted-foreground" />+ )}+ <span className="text-muted-foreground">+ {job.status === "COMPLETED"+ ? "Ready"+ : job.status === "PROCESSING"+ ? `${job.processedFiles} / ${job.totalFiles} files`+ : job.status}+ </span>+ </div>+ {job.status === "COMPLETED" &&+ job.downloadUrls &&+ job.downloadUrls.length > 0 && (+ <div className="mt-2 flex flex-wrap items-center gap-2">+ {job.downloadUrls.length === 1 ? (+ <Button+ size="sm"+ onClick={() => handleDownload(job.downloadUrls![0])}+ >+ <Download className="mr-1 h-3 w-3" />+ Download+ </Button>+ ) : (+ <>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ setExpandedJobId(+ expandedJobId === job.id ? null : job.id,+ )+ }+ >+ {expandedJobId === job.id ? (+ <>+ <ChevronUp className="mr-1 h-3 w-3" />+ Hide parts+ </>+ ) : (+ <>+ <ChevronDown className="mr-1 h-3 w-3" />+ Show parts ({job.downloadUrls!.length})+ </>+ )}+ </Button>+ {expandedJobId === job.id && (+ <div className="w-full space-y-2 rounded-md border bg-muted/30 p-3">+ <Button+ size="sm"+ className="w-full"+ onClick={() =>+ handleDownloadAll(job.downloadUrls!)+ }+ >+ <Download className="mr-2 h-3 w-3" />+ Download all ({job.downloadUrls!.length} parts)+ </Button>+ <p className="text-xs text-muted-foreground">+ Or download individually:+ </p>+ <div className="max-h-32 space-y-1 overflow-y-auto">+ {job.downloadUrls!.map((url, i) => (+ <Button+ key={i}+ variant="outline"+ size="sm"+ className="w-full justify-start"+ onClick={() => handleDownload(url)}+ >+ <FileArchive className="mr-2 h-3 w-3" />+ Part {i + 1} of{" "}+ {job.downloadUrls!.length}+ </Button>+ ))}+ </div>+ </div>+ )}+ </>+ )}+ {job.expiresAt && (+ <span className="text-xs text-muted-foreground">+ Expires {formatExpiration(job.expiresAt)}+ </span>+ )}+ </div>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}