Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add download-only file support
Marc Seitz2080f9d3430a
diff --git a/components/document-upload.tsx b/components/document-upload.tsxindex d5a63079..6b05514a 100644--- a/components/document-upload.tsx+++ b/components/document-upload.tsx@@ -70,6 +70,8 @@ export default function DocumentUpload({"image/png": [], // ".png""image/jpeg": [], // ".jpeg""image/jpg": [], // ".jpg"+ "application/zip": [], // ".zip"+ "application/x-zip-compressed": [], // ".zip"},multiple: false,maxSize: maxSize * 1024 * 1024, // 30 MBdiff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex c3ed499e..f7d3bb9c 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -51,6 +51,8 @@ const allAcceptableDropZoneMimeTypes = {"image/png": [], // ".png""image/jpeg": [], // ".jpeg""image/jpg": [], // ".jpg"+ "application/zip": [], // ".zip"+ "application/x-zip-compressed": [], // ".zip"};interface FileWithPaths extends File {@@ -251,6 +253,7 @@ export default function UploadZone({name: file.name,storageType: DocumentStorageType.S3_PATH,contentType: contentType,+ fileSize: file.size,};const fileUploadPathName = file?.whereToUploadPath;diff --git a/components/view/DataroomViewer.tsx b/components/view/DataroomViewer.tsxindex 1186c8f0..2d2f48ae 100644--- a/components/view/DataroomViewer.tsx+++ b/components/view/DataroomViewer.tsx@@ -37,6 +37,7 @@ type DataroomDocument = {id: string;name: string;orderIndex: number | null;+ downloadOnly: boolean;versions: {id: string;type: string;@@ -75,7 +76,7 @@ export default function DataroomViewer({setDataroomVerified,isPreview,folderId,- setFolderId+ setFolderId,}: {brand: Partial<DataroomBrand>;viewId?: string;diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex 53c151c5..3f14b5d9 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -24,6 +24,7 @@ import DataroomViewer from "../DataroomViewer";import PagesViewerNew from "../PagesViewerNew";import EmailVerificationMessage from "../email-verification-form";import AdvancedExcelViewer from "../viewer/advanced-excel-viewer";+import DownloadOnlyViewer from "../viewer/download-only-viewer";import ImageViewer from "../viewer/image-viewer";const ExcelViewer = dynamic(@@ -48,6 +49,7 @@ export type TDocumentData = {documentType: TSupportedDocumentSimpleType;documentVersionId: string;documentVersionNumber: number;+ downloadOnly: boolean;isVertical?: boolean;};@@ -434,6 +436,20 @@ export default function DataroomView({linkName={link.name ?? `Link #${link.id.slice(-5)}`}/></div>+ ) : documentData?.downloadOnly ? (+ <DownloadOnlyViewer+ file={viewData.file!}+ linkId={link.id}+ documentId={documentData.id}+ viewId={viewData.viewId}+ allowDownload={true}+ versionNumber={documentData.documentVersionNumber}+ brand={brand}+ documentName={documentData.name}+ isPreview={viewData.isPreview}+ dataroomId={dataroom.id}+ setDocumentData={setDocumentData}+ />) : null;}diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsxindex b2a2ff67..5fb27669 100644--- a/components/view/dataroom/document-card.tsx+++ b/components/view/dataroom/document-card.tsx@@ -10,6 +10,7 @@ type DRDocument = {dataroomDocumentId: string;id: string;name: string;+ downloadOnly: boolean;versions: {id: string;type: string;@@ -59,6 +60,7 @@ export default function DocumentCard({.type as TSupportedDocumentSimpleType,documentVersionId: document.versions[0].id,documentVersionNumber: document.versions[0].versionNumber,+ downloadOnly: document.downloadOnly,isVertical: document.versions[0].isVertical,});}}diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex 637dfed5..b6d8b2be 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -11,6 +11,7 @@ import { DEFAULT_DOCUMENT_VIEW_TYPE } from "@/components/view/document-view";import { LinkWithDocument, NotionTheme, WatermarkConfig } from "@/lib/types";import AdvancedExcelViewer from "./viewer/advanced-excel-viewer";+import DownloadOnlyViewer from "./viewer/download-only-viewer";import ImageViewer from "./viewer/image-viewer";const ExcelViewer = dynamic(@@ -131,6 +132,18 @@ export default function ViewData({ipAddress={viewData.ipAddress}linkName={link.name ?? `Link #${link.id.slice(-5)}`}/>+ ) : document.downloadOnly ? (+ <DownloadOnlyViewer+ file={viewData.file!}+ linkId={link.id}+ viewId={viewData.viewId}+ documentId={document.id}+ allowDownload={true}+ versionNumber={document.versions[0].versionNumber}+ brand={brand}+ documentName={document.name}+ isPreview={viewData.isPreview}+ />) : (<PDFViewerfile={viewData.file}diff --git a/components/view/viewer/download-only-viewer.tsx b/components/view/viewer/download-only-viewer.tsxnew file mode 100644index 00000000..76fa7d60--- /dev/null+++ b/components/view/viewer/download-only-viewer.tsx@@ -0,0 +1,203 @@+import { useRouter } from "next/router";++import { useEffect, useRef } from "react";++import { Brand, DataroomBrand } from "@prisma/client";+import { Download } from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";++import { TDocumentData } from "../dataroom/dataroom-view";+import Nav from "../nav";++const trackPageView = async (data: {+ linkId: string;+ documentId: string;+ viewId?: string;+ duration: number;+ pageNumber: number;+ versionNumber: number;+ dataroomId?: string;+ isPreview?: boolean;+}) => {+ // If the view is a preview, do not track the view+ if (data.isPreview) return;++ await fetch("/api/record_view", {+ method: "POST",+ body: JSON.stringify(data),+ headers: {+ "Content-Type": "application/json",+ },+ });+};++export default function DownloadOnlyViewer({+ file,+ linkId,+ documentId,+ viewId,+ allowDownload,+ versionNumber,+ brand,+ documentName,+ isPreview,+ dataroomId,+ setDocumentData,+}: {+ file: string;+ linkId: string;+ documentId: string;+ viewId?: string;+ allowDownload: boolean;+ versionNumber: number;+ brand?: Partial<Brand> | Partial<DataroomBrand> | null;+ documentName?: string;+ isPreview?: boolean;+ dataroomId?: string;+ setDocumentData?: React.Dispatch<React.SetStateAction<TDocumentData | null>>;+}) {+ const router = useRouter();+ const startTimeRef = useRef(Date.now());+ const visibilityRef = useRef<boolean>(true);++ useEffect(() => {+ // Remove token and email query parameters on component mount+ const removeQueryParams = (queries: string[]) => {+ const currentQuery = { ...router.query };+ const currentPath = router.asPath.split("?")[0];+ queries.map((query) => delete currentQuery[query]);++ router.replace(+ {+ pathname: currentPath,+ query: currentQuery,+ },+ undefined,+ { shallow: true },+ );+ };++ if (router.query.token) {+ removeQueryParams(["token", "email", "domain", "slug", "linkId"]);+ }+ }, []);++ useEffect(() => {+ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible") {+ visibilityRef.current = true;+ startTimeRef.current = Date.now();+ } else {+ visibilityRef.current = false;+ const duration = Date.now() - startTimeRef.current;+ trackPageView({+ linkId,+ documentId,+ viewId,+ duration,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ });+ }+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);++ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+ }, [documentId, linkId, viewId, versionNumber, dataroomId, isPreview]);++ useEffect(() => {+ const handleBeforeUnload = () => {+ const duration = Date.now() - startTimeRef.current;+ trackPageView({+ linkId,+ documentId,+ viewId,+ duration,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ });+ };++ window.addEventListener("beforeunload", handleBeforeUnload);++ return () => {+ window.removeEventListener("beforeunload", handleBeforeUnload);+ };+ }, [documentId, linkId, viewId, versionNumber, dataroomId, isPreview]);++ const downloadFile = async () => {+ if (isPreview) {+ toast.error("You cannot download documents in preview mode.");+ return;+ }+ if (!allowDownload) return;+ try {+ const response = await fetch(`/api/links/download`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ linkId, viewId }),+ });++ if (!response.ok) {+ toast.error("Error downloading file");+ return;+ }+ const { downloadUrl } = await response.json();++ window.open(downloadUrl, "_blank");+ } catch (error) {+ console.error("Error downloading file:", error);+ }+ };++ return (+ <>+ <Nav+ pageNumber={1}+ numPages={1}+ allowDownload={allowDownload}+ brand={brand}+ viewId={viewId}+ linkId={linkId}+ documentId={documentId}+ documentName={documentName}+ isPreview={isPreview}+ isDataroom={dataroomId ? true : false}+ setDocumentData={setDocumentData}+ />+ <div+ style={{ height: "calc(100dvh - 64px)" }}+ className="relative flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-900"+ >+ <div className="flex flex-col items-center space-y-6 p-8 text-center">+ <div className="rounded-full bg-gray-100 p-6 dark:bg-gray-800">+ <Download className="h-12 w-12 text-gray-600 dark:text-gray-300" />+ </div>+ <h2 className="text-xl font-medium text-gray-900 dark:text-gray-100">+ {documentName || "Download Document"}+ </h2>+ <p className="text-sm text-gray-500 dark:text-gray-400">+ This document is available for download only+ </p>+ {allowDownload && (+ <Button onClick={downloadFile} className="w-full space-x-2">+ <Download className="h-4 w-4" />+ <span>Download Now</span>+ </Button>+ )}+ </div>+ </div>+ </>+ );+}diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 2f60b184..c5e2dc8d 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -57,6 +57,7 @@ export async function fetchDataroomLinkData({id: true,name: true,advancedExcelEnabled: true,+ downloadOnly: true,versions: {where: { isPrimary: true },select: {@@ -130,6 +131,7 @@ export async function fetchDocumentLinkData({name: true,assistantEnabled: true,advancedExcelEnabled: true,+ downloadOnly: true,teamId: true,ownerId: true,team: {diff --git a/lib/constants.ts b/lib/constants.tsindex 6ad9d887..8297c03f 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -93,6 +93,8 @@ export const SUPPORTED_DOCUMENT_MIME_TYPES = ["image/png", // .png"image/jpeg", // .jpeg"image/jpg", // .jpg+ "application/zip", // .zip+ "application/x-zip-compressed", // .zip];export const SUPPORTED_DOCUMENT_SIMPLE_TYPES = [@@ -103,6 +105,7 @@ export const SUPPORTED_DOCUMENT_SIMPLE_TYPES = ["docs","cad","image",+ "zip",];export const COUNTRIES: { [key: string]: string } = {diff --git a/lib/utils/get-content-type.ts b/lib/utils/get-content-type.tsindex c3840ed2..c27357d7 100644--- a/lib/utils/get-content-type.ts+++ b/lib/utils/get-content-type.ts@@ -22,6 +22,9 @@ export function getSupportedContentType(contentType: string): string | null {case "image/jpeg":case "image/jpg":return "image";+ case "application/zip":+ case "application/x-zip-compressed":+ return "zip";default:return null;}@@ -67,29 +70,3 @@ export function getExtensionFromContentType(return null;}}--export function getExtensionFromSupportedType(- supportedType: string,-): string | null {- switch (supportedType) {- case "pdf":- return "pdf";- case "sheet":- return "xlsx";- default:- return null;- }-}--export function getMimeTypeFromSupportedType(- supportedType: string,-): string | null {- switch (supportedType) {- case "pdf":- return "application/pdf";- case "sheet":- return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";- default:- return null;- }-}diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.tsindex cb0ff083..afc9bc84 100644--- a/pages/api/links/download/index.ts+++ b/pages/api/links/download/index.ts@@ -35,6 +35,7 @@ export default async function handle(document: {select: {teamId: true,+ downloadOnly: true,versions: {where: { isPrimary: true },select: {@@ -58,7 +59,7 @@ export default async function handle(}// if link does not allow download, we should not allow the download- if (!view.link.allowDownload) {+ if (!view.link.allowDownload && !view.document?.downloadOnly) {return res.status(403).json({ error: "Error downloading" });}diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 6e1da491..19cd8bf2 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -217,6 +217,9 @@ export default async function handle(},});+ // determine if the document is download only+ const isDownloadOnly = type === "zip";+// Save data to the databaseconst document = await prisma.document.create({data: {@@ -229,6 +232,7 @@ export default async function handle(storageType,ownerId: userId,teamId: teamId,+ downloadOnly: isDownloadOnly,...(createLink && {links: {create: {diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 591f06d9..6a7f650a 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -702,7 +702,8 @@ export default async function handle(file:(documentVersion &&(documentVersion.type === "pdf" ||- documentVersion.type === "image")) ||+ documentVersion.type === "image" ||+ documentVersion.type === "zip")) ||(documentVersion && useAdvancedExcelViewer)? documentVersion.file: undefined,diff --git a/pages/api/views.ts b/pages/api/views.tsindex 554d78e0..f29196ab 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -533,7 +533,8 @@ export default async function handle(file:(documentVersion &&(documentVersion.type === "pdf" ||- documentVersion.type === "image")) ||+ documentVersion.type === "image" ||+ documentVersion.type === "zip")) ||(documentVersion && useAdvancedExcelViewer)? documentVersion.file: undefined,diff --git a/prisma/migrations/20241118000000_add_filesize_and_downloadonly/migration.sql b/prisma/migrations/20241118000000_add_filesize_and_downloadonly/migration.sqlnew file mode 100644index 00000000..13206f80--- /dev/null+++ b/prisma/migrations/20241118000000_add_filesize_and_downloadonly/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Document" ADD COLUMN "downloadOnly" BOOLEAN NOT NULL DEFAULT false;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 00b1e240..6e29eb51 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -148,6 +148,7 @@ model Document {ownerId String? // This field holds the foreign key.assistantEnabled Boolean @default(false) // This indicates if assistant is enabled for this documentadvancedExcelEnabled Boolean @default(false) // This indicates if advanced Excel is enabled for this document+ downloadOnly Boolean @default(false) // Indicates if the document is download onlycreatedAt DateTime @default(now())updatedAt DateTime @updatedAtlinks Link[]