Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Added new feature to provide user an option to allow the file be downloaded or not.
Vinod Pal05bdddb7518e
diff --git a/components/PDFViewer.tsx b/components/PDFViewer.tsxindex e6a8ee3f..71a650b2 100644--- a/components/PDFViewer.tsx+++ b/components/PDFViewer.tsx@@ -142,6 +142,7 @@ export default function PDFViewer(props: any) {pageNumber={pageNumber}numPages={numPages}downloadFile={downloadfile}+ allowDownload={props.allowDownload}/><divhidden={loading}@@ -197,10 +198,12 @@ export default function PDFViewer(props: any) {function Nav({pageNumber,numPages,+ allowDownload,downloadFile,}: {pageNumber: number;numPages: number;+ allowDownload: boolean;downloadFile: (e: React.MouseEvent<HTMLButtonElement>) => void;}) {return (@@ -219,11 +222,15 @@ function Nav({<span>{pageNumber}</span><span className="text-gray-400"> / {numPages}</span></div>- <div className="bg-gray-900 text-white rounded-md px-2 py-1 text-sm m-1">- <button onClick={downloadFile}>- <Download className="w-8 h-6" />- </button>- </div>+ {allowDownload ? (+ <div className="bg-gray-900 text-white rounded-md px-2 py-1 text-sm m-1">+ <button onClick={downloadFile}>+ <Download className="w-8 h-6" />+ </button>+ </div>+ ) : (+ ""+ )}</div></div></div>diff --git a/components/links/link-sheet/allow-download-section.tsx b/components/links/link-sheet/allow-download-section.tsxnew file mode 100644index 00000000..cb06a808--- /dev/null+++ b/components/links/link-sheet/allow-download-section.tsx@@ -0,0 +1,43 @@+import { Dispatch, SetStateAction, useState, useEffect } from "react";+import { Switch } from "@/components/ui/switch";+import { cn } from "@/lib/utils";+import { DEFAULT_LINK_TYPE } from ".";++export default function AllowDownloadSection({+ data,+ setData,+}: {+ data: DEFAULT_LINK_TYPE;+ setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;+}) {+ const { allowDownload } = data;+ const [enabled, setEnabled] = useState<boolean>(false);++ useEffect(() => {+ setEnabled(allowDownload);+ }, [allowDownload]);++ const handleAllowDownload = () => {+ const updatedAllowDownload = !enabled;+ setData({ ...data, allowDownload: updatedAllowDownload });+ setEnabled(updatedAllowDownload);+ };++ return (+ <div className="pb-5">+ <div className="flex items-center justify-between">+ <div className="flex items-center justify-between space-x-2">+ <h2+ className={cn(+ "text-sm font-medium leading-6",+ enabled ? "text-foreground" : "text-muted-foreground"+ )}+ >+ Download+ </h2>+ </div>+ <Switch checked={enabled} onCheckedChange={handleAllowDownload} />+ </div>+ </div>+ );+}diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 98673a03..335dd850 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -8,7 +8,7 @@ import {} from "@/components/ui/sheet";import { Separator } from "@/components/ui/separator";import { Dispatch, SetStateAction, useEffect, useState } from "react";-import PasswordSection from "./password-section"+import PasswordSection from "./password-section";import ExpirationSection from "./expiration-section";import EmailProtectionSection from "./email-protection-section";import { useRouter } from "next/router";@@ -22,6 +22,7 @@ import { cn } from "@/lib/utils";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import Link from "next/link";import DomainSection from "./domain-section";+import AllowDownloadSection from "./allow-download-section";export const DEFAULT_LINK_PROPS = {id: null,@@ -31,6 +32,7 @@ export const DEFAULT_LINK_PROPS = {expiresAt: null,password: null,emailProtected: true,+ allowDownload: false,};export type DEFAULT_LINK_TYPE = {@@ -41,10 +43,18 @@ export type DEFAULT_LINK_TYPE = {expiresAt: Date | null;password: string | null;emailProtected: boolean;+ allowDownload: boolean;};--export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen: boolean, setIsOpen: Dispatch<SetStateAction<boolean>>, currentLink?: DEFAULT_LINK_TYPE }) {+export default function LinkSheet({+ isOpen,+ setIsOpen,+ currentLink,+}: {+ isOpen: boolean;+ setIsOpen: Dispatch<SetStateAction<boolean>>;+ currentLink?: DEFAULT_LINK_TYPE;+}) {const { links } = useDocumentLinks();const { domains } = useDomains();const [data, setData] = useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS);@@ -85,7 +95,7 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:if (!response.ok) {// handle error with toast messageconst { error } = await response.json();- toast.error(error)+ toast.error(error);setIsLoading(false);return;}@@ -97,7 +107,9 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:// Update the link in the list of linksmutate(`/api/documents/${encodeURIComponent(documentId)}/links`,- (links || []).map(link => link.id === currentLink.id ? returnedLink : link),+ (links || []).map((link) =>+ link.id === currentLink.id ? returnedLink : link+ ),false);toast.success("Link updated successfully");@@ -112,15 +124,11 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:toast.success("Link created successfully");}--setData(DEFAULT_LINK_PROPS);setIsLoading(false);- }-+ };// console.log("current Data", data)-return (<Sheet open={isOpen} onOpenChange={(open: boolean) => setIsOpen(open)}>@@ -171,6 +179,7 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:<PasswordSection {...{ data, setData }} /><ExpirationSection {...{ data, setData }} /><EmailProtectionSection {...{ data, setData }} />+ <AllowDownloadSection {...{ data, setData }} /></div></div></div>diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex 1fa4e527..753657f7 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -28,20 +28,22 @@ import MoreHorizontal from "../shared/icons/more-horizontal";import { Skeleton } from "../ui/skeleton";import LinksVisitors from "./links-visitors";import ChevronDown from "../shared/icons/chevron-down";-import LinkSheet, { DEFAULT_LINK_PROPS, type DEFAULT_LINK_TYPE } from "./link-sheet";+import LinkSheet, {+ DEFAULT_LINK_PROPS,+ type DEFAULT_LINK_TYPE,+} from "./link-sheet";import { useState } from "react";import { LinkWithViews } from "@/lib/types";import { mutate } from "swr";import { toast } from "sonner";--export default function LinksTable() {const { links } = useDocumentLinks();const [isLoading, setIsLoading] = useState<boolean>(false);const [isLinkSheetVisible, setIsLinkSheetVisible] = useState<boolean>(false);- const [selectedLink, setSelectedLink] = useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS);+ const [selectedLink, setSelectedLink] =+ useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS);const handleCopyToClipboard = (linkString: string) => {copyToClipboard(`${linkString}`, "Link copied to clipboard.");@@ -56,11 +58,16 @@ export default function LinksTable() {expiresAt: link.expiresAt,password: link.password,emailProtected: link.emailProtected,+ allowDownload: link.allowDownload ? link.allowDownload : false,});setIsLinkSheetVisible(true);};- const handleArchiveLink = async (linkId: string, documentId: string, isArchived: boolean) => {+ const handleArchiveLink = async (+ linkId: string,+ documentId: string,+ isArchived: boolean+ ) => {setIsLoading(true);const response = await fetch(`/api/links/${linkId}/archive`, {@@ -82,18 +89,22 @@ export default function LinksTable() {// Update the archived link in the list of linksmutate(`/api/documents/${encodeURIComponent(documentId)}/links`,- (links || []).map(link => link.id === linkId ? archivedLink : link),+ (links || []).map((link) => (link.id === linkId ? archivedLink : link)),false);- toast.success(!isArchived ? "Link successfully archived" : "Link successfully reactivated");+ toast.success(+ !isArchived+ ? "Link successfully archived"+ : "Link successfully reactivated"+ );setIsLoading(false);- }+ };const archivedLinksCount = links? links.filter((link) => link.isArchived).length: 0;-+return (<><div className="w-full sm:p-4">@@ -372,4 +383,4 @@ export default function LinksTable() {</div></>);-}\ No newline at end of file+}diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex d03b07f8..11419424 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -168,6 +168,7 @@ export default function DocumentView({linkId={link.id}documentId={document.id}name={document.name}+ allowDownload={link.allowDownload}/></div>);diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 2659e70b..762d22d8 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -22,8 +22,9 @@ export default async function handle(id: true,expiresAt: true,emailProtected: true,+ allowDownload: true,password: true,- document: { select: { id: true, name:true } },+ document: { select: { id: true, name: true } },},});@@ -61,9 +62,9 @@ export default async function handle(if (domain && slug) {domainObj = await prisma.domain.findUnique({where: {- slug: domain- }- })+ slug: domain,+ },+ });if (!domainObj) {return res.status(400).json({ error: "Domain not found." });@@ -105,6 +106,7 @@ export default async function handle(password: hashedPassword,name: linkData.name || null,emailProtected: linkData.emailProtected,+ allowDownload: linkData.allowDownload,expiresAt: exat,domainId: domainObj?.id || null,domainSlug: domain || null,@@ -136,7 +138,7 @@ export default async function handle(const { id } = req.query as { id: string };- try{+ try {const linkToBeDeleted = await prisma.link.findUnique({where: {id: id,@@ -145,25 +147,27 @@ export default async function handle(document: {select: {ownerId: true,- }- }- }+ },+ },+ },});-+if (!linkToBeDeleted) {return res.status(404).json({ error: "Link not found" });}- if (linkToBeDeleted.document.ownerId !== (session.user as CustomUser).id){+ if (+ linkToBeDeleted.document.ownerId !== (session.user as CustomUser).id+ ) {return res.status(401).end("Unauthorized to access the link");}-+await prisma.link.delete({where: {id: id,- }+ },});-+res.status(204).end(); // 204 No Content response for successful deletes} catch (error) {return res.status(500).json({diff --git a/pages/api/links/domains/[domain]/[slug]/index.ts b/pages/api/links/domains/[domain]/[slug]/index.tsindex 8b1b8cc1..9fa4a9e9 100644--- a/pages/api/links/domains/[domain]/[slug]/index.ts+++ b/pages/api/links/domains/[domain]/[slug]/index.ts@@ -7,7 +7,7 @@ export default async function handle() {if (req.method === "GET") {// GET /api/links/domains/:domain/:slug- const { domain, slug } = req.query as { domain: string, slug: string };+ const { domain, slug } = req.query as { domain: string; slug: string };try {const link = await prisma.link.findUnique({@@ -21,6 +21,7 @@ export default async function handle(id: true,expiresAt: true,emailProtected: true,+ allowDownload: true,password: true,document: { select: { id: true } },},diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 2c8a902f..76b6a0bf 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -18,8 +18,9 @@ export default async function handler(const { documentId, password, expiresAt, ...linkDomainData } = req.body;- const hashedPassword = password && password.length > 0 ? await hashPassword(password) : null- const exat = expiresAt ? new Date(expiresAt) : null+ const hashedPassword =+ password && password.length > 0 ? await hashPassword(password) : null;+ const exat = expiresAt ? new Date(expiresAt) : null;let { domain, slug, ...linkData } = linkDomainData;@@ -34,9 +35,9 @@ export default async function handler(if (domain && slug) {domainObj = await prisma.domain.findUnique({where: {- slug: domain- }- })+ slug: domain,+ },+ });if (!domainObj) {return res.status(400).json({ error: "Domain not found." });@@ -49,16 +50,14 @@ export default async function handler(domainSlug_slug: {slug: slug,domainSlug: domain,- }+ },},});if (existingLink) {- return res- .status(400)- .json({- error: "The link already exists.",- });+ return res.status(400).json({+ error: "The link already exists.",+ });}}@@ -70,6 +69,7 @@ export default async function handler(name: linkData.name || null,emailProtected: linkData.emailProtected,expiresAt: exat,+ allowDownload: linkData.allowDownload,domainId: domainObj?.id || null,domainSlug: domain || null,slug: slug || null,diff --git a/prisma/migrations/202310122339_NewColumnInLinkTable/migration.sql b/prisma/migrations/202310122339_NewColumnInLinkTable/migration.sqlnew file mode 100644index 00000000..137dd328--- /dev/null+++ b/prisma/migrations/202310122339_NewColumnInLinkTable/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Link" ADD COLUMN "allowDownload" BOOLEAN DEFAULT false;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex c24d8f54..574d6e31 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -1,28 +1,28 @@datasource db {- provider = "postgresql"- url = env("POSTGRES_PRISMA_URL") // uses connection pooling+ provider = "postgresql"+ url = env("POSTGRES_PRISMA_URL") // uses connection pooling// url = env("POSTGRES_PRISMA_URL_NON_POOLING") // uses a direct connection- directUrl = env("POSTGRES_PRISMA_URL_NON_POOLING") // uses a direct connection+ directUrl = env("POSTGRES_PRISMA_URL_NON_POOLING") // uses a direct connectionshadowDatabaseUrl = env("POSTGRES_PRISMA_URL_NON_POOLING") // used for migrations- }+}generator client {- provider = "prisma-client-js"+ provider = "prisma-client-js"}model Account {- id String @id @default(cuid())- userId String- type String- provider String- providerAccountId String- refresh_token String? @db.Text- access_token String? @db.Text- expires_at Int?- token_type String?- scope String?- id_token String? @db.Text- session_state String?+ id String @id @default(cuid())+ userId String+ type String+ provider String+ providerAccountId String+ refresh_token String? @db.Text+ access_token String? @db.Text+ expires_at Int?+ token_type String?+ scope String?+ id_token String? @db.Text+ session_state String?user User @relation(fields: [userId], references: [id], onDelete: Cascade)@@ -38,21 +38,21 @@ model Session {}model User {- id String @id @default(cuid())- name String?- email String? @unique- emailVerified DateTime?- image String?- createdAt DateTime @default(now())- accounts Account[]- sessions Session[]- documents Document[]- domains Domain[]- plan String @default("free")- stripeId String? @unique // Stripe subscription / customer ID- subscriptionId String? @unique // Stripe subscription ID- startsAt DateTime? // Stripe subscription start date- endsAt DateTime? // Stripe subscription end date+ id String @id @default(cuid())+ name String?+ email String? @unique+ emailVerified DateTime?+ image String?+ createdAt DateTime @default(now())+ accounts Account[]+ sessions Session[]+ documents Document[]+ domains Domain[]+ plan String @default("free")+ stripeId String? @unique // Stripe subscription / customer ID+ subscriptionId String? @unique // Stripe subscription ID+ startsAt DateTime? // Stripe subscription start date+ endsAt DateTime? // Stripe subscription end date}model VerificationToken {@@ -64,38 +64,39 @@ model VerificationToken {}model Document {- id String @id @default(cuid())- name String+ id String @id @default(cuid())+ name Stringdescription String?- file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)- type String? // This should be a reference to the file type (pdf, docx, etc.)- numPages Int? // This should be a reference to the number of pages in the document- owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)- ownerId String // This field holds the foreign key.- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- links Link[]- views View[]+ file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)+ type String? // This should be a reference to the file type (pdf, docx, etc.)+ numPages Int? // This should be a reference to the number of pages in the document+ owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)+ ownerId String // This field holds the foreign key.+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ links Link[]+ views View[]}model Link {- id String @id @default(cuid())- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)- documentId String- url String? @unique- name String? // Link name- slug String? // Link slug for pretty URLs- expiresAt DateTime? // Optional expiration date- password String? // Optional password for link protection- allowedEmails String[] // Array of emails allowed to view the document- emailProtected Boolean @default(true) // Optional email protection- isArchived Boolean @default(false) // Indicates if the link is archived- views View[]- domain Domain? @relation(fields: [domainId], references: [id], onDelete: SetNull)- domainId String? // This can be nullable, representing links without custom domains- domainSlug String? // This will store the domain's slug even if the domain is deleted- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ id String @id @default(cuid())+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)+ documentId String+ url String? @unique+ name String? // Link name+ slug String? // Link slug for pretty URLs+ expiresAt DateTime? // Optional expiration date+ password String? // Optional password for link protection+ allowedEmails String[] // Array of emails allowed to view the document+ emailProtected Boolean @default(true) // Optional email protection+ allowDownload Boolean? @default(false) // Optional give user a option to allow to download the document+ isArchived Boolean @default(false) // Indicates if the link is archived+ views View[]+ domain Domain? @relation(fields: [domainId], references: [id], onDelete: SetNull)+ domainId String? // This can be nullable, representing links without custom domains+ domainSlug String? // This will store the domain's slug even if the domain is deleted+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt@@unique([domainSlug, slug])}@@ -109,16 +110,15 @@ model Domain {lastChecked DateTime @default(now())createdAt DateTime @default(now())updatedAt DateTime @updatedAt- links Link[] // links associated with this domain+ links Link[] // links associated with this domain}-model View {- id String @id @default(cuid())- link Link @relation(fields: [linkId], references: [id])+ id String @id @default(cuid())+ link Link @relation(fields: [linkId], references: [id])linkId String- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)documentId String- viewerEmail String? // Email of the viewer if known- viewedAt DateTime @default(now())+ viewerEmail String? // Email of the viewer if known+ viewedAt DateTime @default(now())}