Skip to content

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

feat: add numPages to Document

Marc Seitz5f8c87267786
diff --git a/components/PDFViewer.tsx b/components/PDFViewer.tsx
index ac6b671e..9e10f6dc 100644
--- a/components/PDFViewer.tsx
+++ b/components/PDFViewer.tsx
@@ -18,7 +18,7 @@ export default function PDFViewer(props: any) {
useEffect(() => {
pageNumberRef.current = pageNumber;
}, [pageNumber]);
-
+
useEffect(() => {
startTimeRef.current = Date.now(); // update the start time for the new page
@@ -30,6 +30,13 @@ export default function PDFViewer(props: any) {
};
}, [pageNumber]); // monitor pageNumber for changes
+ useEffect(() => {
+ if (numPages > 0) {
+ updateNumPages(numPages);
+ }
+ }, [numPages]); // monitor numPages for changes
+
+
function onDocumentLoadSuccess({
numPages: nextNumPages,
}: {
@@ -95,6 +102,19 @@ export default function PDFViewer(props: any) {
});
}
+ async function updateNumPages(numPages: number) {
+ await fetch(`/api/documents/update`, {
+ method: "POST",
+ body: JSON.stringify({
+ documentId: props.documentId,
+ numPages: numPages,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
return (
<>
<Nav pageNumber={pageNumber} numPages={numPages} />
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsx
index 1ca042c2..c196b3c6 100644
--- a/components/documents/add-document-modal.tsx
+++ b/components/documents/add-document-modal.tsx
@@ -13,7 +13,12 @@ import type { PutBlobResult } from "@vercel/blob";
import toast from "react-hot-toast";
import Notification from "@/components/Notification";
import DocumentUpload from "@/components/document-upload";
+import { pdfjs } from "react-pdf";
+import { getExtension } from "@/lib/utils";
+import { get } from "http";
+import { set } from "date-fns";
+pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
export function AddDocumentModal({children}: {children: React.ReactNode}) {
const router = useRouter();
@@ -48,41 +53,39 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
// get the blob url from the response
const blob = (await blobResponse.json()) as PutBlobResult;
- // create a document in the database with the blob url
- const response = await fetch("/api/documents", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- name: blob.pathname,
- url: blob.url,
- }),
- });
+ let response: Response | undefined;
+ let numPages: number | undefined;
+ // create a document in the database if the document is a pdf
+ if (getExtension(blob.pathname).includes("pdf")) {
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
+ numPages = await getTotalPages(blob.url);
+ response = await saveDocumentToDatabase(blob, numPages);
+ } else {
+ response = await saveDocumentToDatabase(blob);
}
- const document = await response.json();
-
- navigator.clipboard.writeText(
- `${process.env.NEXT_PUBLIC_BASE_URL}/view/${document.links[0].id}`
- );
-
- toast.custom((t) => (
- <Notification
- visible={t.visible}
- closeToast={() => toast.dismiss(t.id)}
- message={
- "Document uploaded and link copied to clipboard. Redirecting to document page..."
- }
- />
- ));
-
- setTimeout(() => {
- router.push("/documents/" + document.id);
- }, 4000);
+ if (response) {
+ const document = await response.json();
+
+ navigator.clipboard.writeText(
+ `${process.env.NEXT_PUBLIC_BASE_URL}/view/${document.links[0].id}`
+ );
+
+ toast.custom((t) => (
+ <Notification
+ visible={t.visible}
+ closeToast={() => toast.dismiss(t.id)}
+ message={
+ "Document uploaded and link copied to clipboard. Redirecting to document page..."
+ }
+ />
+ ));
+
+ setTimeout(() => {
+ router.push("/documents/" + document.id);
+ }, 4000);
+ }
+
} catch (error) {
console.error("An error occurred while uploading the file: ", error);
} finally {
@@ -90,6 +93,33 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
}
};
+ async function saveDocumentToDatabase(blob: PutBlobResult, numPages?: number) {
+ // create a document in the database with the blob url
+ const response = await fetch("/api/documents", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: blob.pathname,
+ url: blob.url,
+ numPages: numPages,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ return response;
+ }
+
+ // get the number of pages in the pdf
+ async function getTotalPages(url: string): Promise<number> {
+ const pdf = await pdfjs.getDocument(url).promise;
+ return pdf.numPages;
+ };
+
return (
<Dialog>
<DialogTrigger>{children}</DialogTrigger>
diff --git a/pages/api/documents/index.ts b/pages/api/documents/index.ts
index 73bfa3a5..7639a0df 100644
--- a/pages/api/documents/index.ts
+++ b/pages/api/documents/index.ts
@@ -51,7 +51,7 @@ export default async function handle(
}
// Assuming data is an object with `name` and `description` properties
- const { name, url, description } = req.body;
+ const { name, url, numPages } = req.body;
// Get the file extension and save it as the type
const type = getExtension(name);
@@ -63,7 +63,7 @@ export default async function handle(
const document = await prisma.document.create({
data: {
name: name,
- description: description,
+ numPages: numPages,
file: url,
type: type,
ownerId: (session.user as CustomUser).id,
diff --git a/pages/api/documents/update.ts b/pages/api/documents/update.ts
new file mode 100644
index 00000000..6cf4991d
--- /dev/null
+++ b/pages/api/documents/update.ts
@@ -0,0 +1,43 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { authOptions } from "../auth/[...nextauth]";
+import { CustomUser } from "@/lib/types";
+import { getExtension, log } from "@/lib/utils";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method === "POST") {
+ // POST /api/documents/update
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ // Assuming data is an object with `name` and `description` properties
+ const { documentId, numPages } = req.body;
+
+ try {
+ // Save data to the database
+ await prisma.document.update({
+ where: { id: documentId },
+ data: { numPages: numPages },
+ });
+
+ res.status(201).json({message: "Document updated successfully"});
+ } catch (error) {
+ log(`Failed to create document. Error: \n\n ${error}`);
+ res.status(500).json({
+ message: "Internal Server Error",
+ error: (error as Error).message,
+ });
+ }
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 23ebfb00..a2fa556b 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -62,6 +62,7 @@ model Document {
description 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])
ownerId String // This field holds the foreign key.
createdAt DateTime @default(now())