Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add separate function to fix internal notion api change
Marc Seitz1be839f484d9
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex 87313881..088fc67c 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -9,6 +9,7 @@ import { DefaultPermissionStrategy } from "@prisma/client";import { parsePageId } from "notion-utils";import { toast } from "sonner";import { mutate } from "swr";+import { z } from "zod";import { useAnalytics } from "@/lib/analytics";import {@@ -18,6 +19,7 @@ import {} from "@/lib/documents/create-document";import { putFile } from "@/lib/files/put-file";import { useDataroomPermissions } from "@/lib/hooks/use-dataroom-permissions";+import { getNotionPageIdFromSlug } from "@/lib/notion/utils";import { usePlan } from "@/lib/swr/use-billing";import { useDataroom } from "@/lib/swr/use-dataroom";import useLimits from "@/lib/swr/use-limits";@@ -387,17 +389,35 @@ export function AddDocumentModal({return;}- const validateNotionPageURL = parsePageId(notionLink);- // Check if it's a valid URL or not by Regx- const isValidURL =- /^(https?:\/\/)?([a-zA-Z0-9-]+\.){1,}[a-zA-Z]{2,}([a-zA-Z0-9-._~:/?#[\]@!$&'()*+,;=]+)?$/;-// Check if the field is empty or notif (!notionLink) {toast.error("Please enter a Notion link to proceed.");return; // prevent form from submitting}- if (validateNotionPageURL === null || !isValidURL.test(notionLink)) {++ // Validate URL format with Zod+ const urlSchema = z.string().url();+ const urlValidation = urlSchema.safeParse(notionLink);++ if (!urlValidation.success) {+ toast.error("Please enter a valid URL format.");+ return;+ }++ // Try to validate the Notion page URL+ let validateNotionPageURL = parsePageId(notionLink);++ // If parsePageId fails, try to get page ID from slug+ if (validateNotionPageURL === null) {+ try {+ validateNotionPageURL = await getNotionPageIdFromSlug(notionLink);+ } catch (slugError) {+ toast.error("Please enter a valid Notion link to proceed.");+ return;+ }+ }++ if (!validateNotionPageURL) {toast.error("Please enter a valid Notion link to proceed.");return;}diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex 372b2020..12ad63c6 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -3,6 +3,7 @@ import { parsePageId } from "notion-utils";import { DocumentData } from "@/lib/documents/create-document";import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import notion from "@/lib/notion";+import { getNotionPageIdFromSlug } from "@/lib/notion/utils";import prisma from "@/lib/prisma";import { convertCadToPdfTask } from "@/lib/trigger/convert-files";import { convertFilesToPdfTask } from "@/lib/trigger/convert-files";@@ -49,7 +50,17 @@ export const processDocument = async ({// Check whether the Notion page is publically accessible or notif (type === "notion") {try {- const pageId = parsePageId(key, { uuid: false });+ let pageId = parsePageId(key, { uuid: false });++ // If parsePageId fails, try to get page ID from slug+ if (!pageId) {+ try {+ pageId = await getNotionPageIdFromSlug(key);+ } catch (slugError) {+ throw new Error("Unable to extract page ID from Notion URL");+ }+ }+// if the page isn't accessible then end the process here.if (!pageId) {throw new Error("Notion page not found");diff --git a/lib/notion/index.ts b/lib/notion/index.tsindex 077bcdfe..45d07a3f 100644--- a/lib/notion/index.ts+++ b/lib/notion/index.ts@@ -1,4 +1,26 @@import { NotionAPI } from "notion-client";-const notion = new NotionAPI();+const notion = new NotionAPI({+ kyOptions: {+ hooks: {+ beforeRequest: [+ (request, options) => {+ const url = request.url.toString();++ if (url.includes("/api/v3/syncRecordValues")) {+ return new Request(+ url.replace(+ "/api/v3/syncRecordValues",+ "/api/v3/syncRecordValuesMain",+ ),+ options,+ );+ }++ return request;+ },+ ],+ },+ },+});export default notion;diff --git a/lib/notion/utils.ts b/lib/notion/utils.tsindex caf4d2b0..e59d4e36 100644--- a/lib/notion/utils.ts+++ b/lib/notion/utils.ts@@ -74,3 +74,55 @@ export const addSignedUrls: NotionAPI["addSignedUrls"] = async ({}}};++export async function getNotionPageIdFromSlug(url: string) {+ // Parse the URL to extract domain and slug+ const urlObj = new URL(url);+ const hostname = urlObj.hostname;++ // Extract domain from hostname (e.g., "domain" from "domain.notion.site")+ const domainMatch = hostname.match(/^([^.]+)\.notion\.site$/);+ if (!domainMatch) {+ throw new Error("Invalid Notion site URL format: ${url}");+ }++ const spaceDomain = domainMatch[1];++ // Extract slug from pathname (remove leading slash)+ // If slug is missing, we will try to get page just by using spaceDomain+ let slug = urlObj.pathname.substring(1) || "";++ // Make request to Notion's internal API+ const apiUrl =+ "https://${spaceDomain}.notion.site/api/v3/getPublicPageDataForDomain";+ const payload = {+ type: "block-space",+ name: "page",+ slug: slug,+ spaceDomain: spaceDomain,+ requestedOnPublicDomain: true,+ };++ const response = await fetch(apiUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "User-Agent": "Mozilla/5.0 (compatible; MyApp/1.0)",+ },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ throw new Error(+ "Notion API request failed: ${response.status} ${response.statusText}",+ );+ }++ const data = await response.json();++ if (data.pageId) {+ return data.pageId;+ } else {+ throw new Error("No pageId found in Notion API response");+ }+}