Skip to content

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

feat: add duplicate document

Marc Seitz898c8f73f4c0
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsx
index b387e0a0..a401383a 100644
--- a/components/documents/document-card.tsx
+++ b/components/documents/document-card.tsx
@@ -1,10 +1,16 @@
import Image from "next/image";
import Link from "next/link";
+import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import { TeamContextType } from "@/context/team-context";
-import { FolderInputIcon, MoreVertical, TrashIcon } from "lucide-react";
+import {
+ FolderInputIcon,
+ Layers2Icon,
+ MoreVertical,
+ TrashIcon,
+} from "lucide-react";
import { useTheme } from "next-themes";
import { toast } from "sonner";
import { mutate } from "swr";
@@ -37,6 +43,7 @@ export default function DocumentsCard({
document: prismaDocument,
teamInfo,
}: DocumentsCardProps) {
+ const router = useRouter();
const { theme, systemTheme } = useTheme();
const isLight =
theme === "light" || (theme === "system" && systemTheme === "light");
@@ -47,6 +54,9 @@ export default function DocumentsCard({
const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
+ /** current folder name */
+ const currentFolderPath = router.query.name as string[] | undefined;
+
function handleCopyToClipboard(id: string) {
copyToClipboard(
`${process.env.NEXT_PUBLIC_BASE_URL}/view/${id}`,
@@ -125,6 +135,30 @@ export default function DocumentsCard({
}
};
+ const handleDuplicateDocument = async (event: any) => {
+ event.stopPropagation();
+ event.preventDefault();
+
+ toast.promise(
+ fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/documents/${prismaDocument.id}/duplicate`,
+ {
+ method: "POST",
+ },
+ ).then(() => {
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`);
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${currentFolderPath?.join("/")}`,
+ );
+ }),
+ {
+ loading: "Duplicating document...",
+ success: "Document duplicated successfully.",
+ error: "Failed to duplicate document. Try again.",
+ },
+ );
+ };
+
return (
<>
<li className="group/row relative flex items-center justify-between rounded-lg border-0 p-3 ring-1 ring-gray-200 transition-all hover:bg-secondary hover:ring-gray-300 dark:bg-secondary dark:ring-gray-700 hover:dark:ring-gray-500 sm:p-4">
@@ -218,6 +252,10 @@ export default function DocumentsCard({
<FolderInputIcon className="mr-2 h-4 w-4" />
Move to folder
</DropdownMenuItem>
+ <DropdownMenuItem onClick={(e) => handleDuplicateDocument(e)}>
+ <Layers2Icon className="mr-2 h-4 w-4" />
+ Duplicate document
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={(event) => handleButtonClick(event, prismaDocument.id)}
diff --git a/lib/files/copy-file-server.ts b/lib/files/copy-file-server.ts
new file mode 100644
index 00000000..a14f2558
--- /dev/null
+++ b/lib/files/copy-file-server.ts
@@ -0,0 +1,134 @@
+import { CopyObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";
+import { DocumentStorageType } from "@prisma/client";
+import { put } from "@vercel/blob";
+import { match } from "ts-pattern";
+
+import { newId } from "@/lib/id-helper";
+
+import { getS3Client } from "./aws-client";
+
+export const copyFileServer = async ({
+ teamId,
+ filePath,
+ fileName,
+ storageType,
+}: {
+ teamId: string;
+ filePath: string;
+ fileName: string;
+ storageType: DocumentStorageType;
+}) => {
+ const { type, data } = await match(storageType)
+ .with("S3_PATH", async () => copyFileInS3Server({ teamId, filePath }))
+ .with("VERCEL_BLOB", async () =>
+ copyFileInVercelServer({ fileName, fileUrl: filePath }),
+ )
+ .otherwise(() => {
+ return {
+ type: null,
+ data: null,
+ };
+ });
+
+ return { type, data };
+};
+
+const copyFileInVercelServer = async ({
+ fileName,
+ fileUrl,
+}: {
+ fileName: string;
+ fileUrl: string;
+}) => {
+ const file = await fetch(fileUrl);
+ const contents = await file.arrayBuffer();
+ const newFileName = fileName + "-copy";
+
+ const blob = await put(newFileName, contents, {
+ access: "public",
+ });
+
+ return {
+ type: DocumentStorageType.VERCEL_BLOB,
+ data: { fromLocation: fileUrl, toLocation: blob.url },
+ };
+};
+
+const copyFileInS3Server = async ({
+ teamId,
+ filePath,
+}: {
+ teamId: string;
+ filePath: string;
+}) => {
+ // Get the current document ID from the file path
+ const fromDocId = filePath.match(/doc_\w+/)?.[0];
+ // Generate a new document ID for copied document prefix
+ const toDocId = newId("doc");
+
+ if (!fromDocId) {
+ throw new Error("Invalid file ID");
+ }
+
+ const fromLocation = `${teamId}/${fromDocId}/`;
+ const toLocation = `${teamId}/${toDocId}/`;
+
+ const response = await copyFolder({
+ fromBucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET as string,
+ fromLocation: fromLocation,
+ toBucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET as string,
+ toLocation: toLocation,
+ });
+
+ console.log("response", response);
+
+ return {
+ type: DocumentStorageType.S3_PATH,
+ data: { fromLocation, toLocation },
+ };
+};
+
+// copies all items in a folder on s3
+async function copyFolder({
+ fromBucket,
+ fromLocation,
+ toBucket = fromBucket,
+ toLocation,
+}: {
+ fromBucket: string;
+ fromLocation: string;
+ toBucket: string;
+ toLocation: string;
+}) {
+ const client = getS3Client();
+ let count = 0;
+ const recursiveCopy = async function (token?: string) {
+ const listCommand = new ListObjectsV2Command({
+ Bucket: fromBucket,
+ Prefix: fromLocation,
+ ContinuationToken: token,
+ });
+ let list = await client.send(listCommand); // get the list
+ if (list.KeyCount && list.Contents) {
+ // if items to copy
+ const fromObjectKeys = list.Contents.map((content) => content.Key); // get the existing object keys
+ for (let fromObjectKey of fromObjectKeys) {
+ // loop through items and copy each one
+ const toObjectKey = fromObjectKey?.replace(fromLocation, toLocation); // replace with the destination in the key
+ // copy the file
+ const copyCommand = new CopyObjectCommand({
+ Bucket: toBucket,
+ CopySource: `${fromBucket}/${fromObjectKey}`,
+ Key: toObjectKey,
+ });
+ await client.send(copyCommand);
+ count += 1;
+ }
+ }
+ if (list.NextContinuationToken) {
+ recursiveCopy(list.NextContinuationToken);
+ }
+ return `${count} files copied.`;
+ };
+ return recursiveCopy();
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/duplicate.ts b/pages/api/teams/[teamId]/documents/[id]/duplicate.ts
new file mode 100644
index 00000000..02a65beb
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/duplicate.ts
@@ -0,0 +1,144 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { DocumentVersion } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { errorhandler } from "@/lib/errorHandler";
+import { copyFileServer } from "@/lib/files/copy-file-server";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // GET /api/teams/:teamId/documents/:id/duplicate
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id: docId } = req.query as { teamId: string; id: string };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId,
+ },
+ },
+ documents: {
+ some: {
+ id: {
+ equals: docId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const document = await prisma.document.findUnique({
+ where: {
+ id: docId,
+ },
+ include: {
+ versions: {
+ where: { isPrimary: true },
+ orderBy: { createdAt: "desc" },
+ take: 1,
+ include: {
+ pages: true,
+ },
+ },
+ },
+ });
+
+ if (!document) {
+ return res.status(404).end("Document not found");
+ }
+
+ const { documentId, ...documentVersion } = document.versions[0];
+
+ const { type, data } = await copyFileServer({
+ teamId: teamId,
+ filePath: documentVersion.file,
+ fileName: document.name,
+ storageType: documentVersion.storageType,
+ });
+
+ console.log("type", type);
+ console.log("data", data);
+
+ const duplicateDocument = await prisma.document.create({
+ data: {
+ ...document,
+ name: `${document.name} (Copy)`,
+ id: undefined,
+ teamId: teamId,
+ ownerId: userId,
+ assistantEnabled: false,
+ createdAt: undefined,
+ updatedAt: undefined,
+ file: document.file.replace(data?.fromLocation!, data?.toLocation!),
+ versions: {
+ create: {
+ ...documentVersion,
+ id: undefined,
+ versionNumber: 1,
+ createdAt: undefined,
+ updatedAt: undefined,
+ fileId: undefined,
+ file: documentVersion.file.replace(
+ data?.fromLocation!,
+ data?.toLocation!,
+ ),
+ pages: {
+ createMany: {
+ data: documentVersion.pages.map((page) => ({
+ ...page,
+ id: undefined,
+ file: page.file.replace(
+ data?.fromLocation!,
+ data?.toLocation!,
+ ),
+ versionId: undefined,
+ createdAt: undefined,
+ updatedAt: undefined,
+ })),
+ },
+ },
+ },
+ },
+ links: {
+ create: {},
+ },
+ },
+ });
+
+ console.log("duplicate document", duplicateDocument);
+
+ return res.status(200).json({
+ message: "Document duplicated successfully!",
+ });
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow POST requests
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}