Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: link as a file
Iuliia Shnaidc820f1e5a8d
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 1e9b2003..8e2e8cee 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -880,6 +880,7 @@ export async function POST(request: NextRequest) {type: documentVersion.storageType,});}+ // For link documents, the file is already a URL, no processing neededif (documentVersion.type === "sheet") {const document = await prisma.document.findUnique({where: { id: documentId },@@ -976,7 +977,8 @@ export async function POST(request: NextRequest) {(documentVersion.type === "pdf" ||documentVersion.type === "image" ||documentVersion.type === "zip" ||- documentVersion.type === "video")) ||+ documentVersion.type === "video" ||+ documentVersion.type === "link")) ||(documentVersion && useAdvancedExcelViewer)? documentVersion.file: undefined,diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex 9ae89ef4..9c096fe5 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -669,7 +669,8 @@ export async function POST(request: NextRequest) {(documentVersion.type === "pdf" ||documentVersion.type === "image" ||documentVersion.type === "zip" ||- documentVersion.type === "video")) ||+ documentVersion.type === "video" ||+ documentVersion.type === "link")) ||(documentVersion && useAdvancedExcelViewer)? documentVersion.file: undefined,diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex b1215d64..3be31166 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -74,6 +74,8 @@ export function AddDocumentModal({const [isOpen, setIsOpen] = useState<boolean | undefined>(undefined);const [currentFile, setCurrentFile] = useState<File | null>(null);const [notionLink, setNotionLink] = useState<string | null>(null);+ const [webLink, setWebLink] = useState<string | null>(null);+ const [uploadMode, setUploadMode] = useState<"file" | "link">("file");const [showGroupPermissions, setShowGroupPermissions] = useState(false);const [uploadedFiles, setUploadedFiles] = useState<{@@ -524,9 +526,144 @@ export function AddDocumentModal({}};+ const handleWebLinkUpload = async (+ event: FormEvent<HTMLFormElement>,+ ): Promise<void> => {+ event.preventDefault();++ if (!canAddDocuments) {+ toast.error("You have reached the maximum number of documents.");+ return;+ }++ // Check if the field is empty or not+ if (!webLink) {+ toast.error("Please enter a website URL to proceed.");+ return;+ }++ // Validate URL format with Zod+ const urlSchema = z.string().url();+ const urlValidation = urlSchema.safeParse(webLink);++ if (!urlValidation.success) {+ toast.error("Please enter a valid URL format.");+ return;+ }++ try {+ setUploading(true);++ // Extract domain name from URL for the document name+ let linkName = "Web Link";+ try {+ const url = new URL(webLink);+ linkName = url.hostname.replace("www.", "");+ } catch (e) {+ // Use default name if URL parsing fails+ }++ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/documents`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: linkName,+ url: webLink,+ numPages: 1,+ type: "link",+ createLink: false,+ folderPathName: currentFolderPath?.join("/"),+ }),+ },+ );++ if (!response.ok) {+ const { error } = await response.json();+ toast.error(error);+ return;+ }++ const document = await response.json();++ if (isDataroom && dataroomId) {+ const dataroomResponse = await addDocumentToDataroom({+ documentId: document.id,+ folderPathName: currentFolderPath?.join("/"),+ });++ if (dataroomResponse?.ok) {+ const dataroomDocument =+ (await dataroomResponse.json()) as DataroomDocument & {+ dataroom: {+ _count: { viewerGroups: number; permissionGroups: number };+ };+ };++ await applyUnifiedPermissionsToDocument(+ document,+ dataroomDocument,+ currentFolderPath,+ );+ }++ analytics.capture("Document Added", {+ documentId: document.id,+ name: document.name,+ numPages: document.numPages,+ path: router.asPath,+ type: "link",+ teamId: teamId,+ dataroomId: dataroomId,+ $set: {+ teamId: teamId,+ teamPlan: plan,+ },+ });++ return;+ }++ if (!newVersion) {+ toast.success("Web link added. Redirecting to document page...");++ analytics.capture("Document Added", {+ documentId: document.id,+ name: document.name,+ fileSize: null,+ path: router.asPath,+ type: "link",+ teamId: teamId,+ $set: {+ teamId: teamId,+ teamPlan: plan,+ },+ });++ // redirect to the document page+ router.push("/documents/" + document.id);+ }+ } catch (error) {+ setUploading(false);+ toast.error("An error occurred while processing the web link.");+ console.error(+ "An error occurred while processing the web link: ",+ error,+ );+ } finally {+ setUploading(false);+ setIsOpen(false);+ }+ };+const clearModelStates = () => {currentFile !== null && setCurrentFile(null);notionLink !== null && setNotionLink(null);+ webLink !== null && setWebLink(null);+ setUploadMode("file");setIsOpen(!isOpen);setAddDocumentModalOpen && setAddDocumentModalOpen(!isOpen);};@@ -605,49 +742,128 @@ export function AddDocumentModal({</CardDescription></CardHeader><CardContent className="space-y-2">- <form- encType="multipart/form-data"- onSubmit={handleFileUpload}- className="flex flex-col space-y-4"- >- <div className="space-y-1">- <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">- <DocumentUpload- currentFile={currentFile}- setCurrentFile={setCurrentFile}- />+ {uploadMode === "file" ? (+ <form+ encType="multipart/form-data"+ onSubmit={handleFileUpload}+ className="flex flex-col space-y-4"+ >+ <div className="space-y-1">+ <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">+ <DocumentUpload+ currentFile={currentFile}+ setCurrentFile={setCurrentFile}+ />+ </div>+ </div>++ <div className="flex justify-center">+ <Button+ type="submit"+ className="w-full lg:w-1/2"+ disabled={uploading || !currentFile}+ loading={uploading}+ >+ {uploading ? "Uploading..." : "Upload Document"}+ </Button>+ </div>++ {!newVersion && (+ <div className="flex justify-center">+ <p className="text-sm text-muted-foreground">+ Want to{" "}+ <button+ type="button"+ className="underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"+ onClick={(e) => {+ e.stopPropagation();+ document+ .getElementById("upload-multi-files-zone")+ ?.click();+ clearModelStates();+ }}+ >+ upload multiple files+ </button>{" "}+ or{" "}+ <button+ type="button"+ className="inline-flex items-center gap-1 underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"+ onClick={(e) => {+ e.preventDefault();+ setUploadMode("link");+ }}+ >+ share link as a document++ </button>+ ?+ </p>+ </div>+ )}+ </form>+ ) : (+ <form+ encType="multipart/form-data"+ onSubmit={handleWebLinkUpload}+ className="flex flex-col space-y-4"+ >+ <div className="space-y-1">+ <Label htmlFor="web-link">Website URL</Label>+ <div className="mt-2">+ <input+ type="text"+ name="web-link"+ id="web-link"+ placeholder="https://example.com"+ className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"+ value={webLink || ""}+ onChange={(e) => setWebLink(e.target.value)}+ />+ </div>+ {/* <small className="text-xs text-muted-foreground">+ The page will be captured and converted to a document format.+ </small> */}+ </div>++ <div className="flex justify-center">+ <Button+ type="submit"+ className="w-full lg:w-1/2"+ disabled={uploading || !webLink}+ loading={uploading}+ >+ {uploading ? "Saving..." : "Save Web Link"}+ </Button></div>- </div>- {!newVersion ? (<div className="flex justify-center"><buttontype="button"- className="text-sm text-muted-foreground underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"+ className="flex items-center gap-2 text-sm text-muted-foreground underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"onClick={(e) => {- e.stopPropagation();- document- .getElementById("upload-multi-files-zone")- ?.click();- clearModelStates();+ e.preventDefault();+ setUploadMode("file");}}>- Want to upload multiple files?+ <svg+ className="h-4 w-4"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"+ />+ </svg>+ Back to file upload</button></div>- ) : null}-- <div className="flex justify-center">- <Button- type="submit"- className="w-full lg:w-1/2"- disabled={uploading || !currentFile}- loading={uploading}- >- {uploading ? "Uploading..." : "Upload Document"}- </Button>- </div>- </form>+ </form>+ )}</CardContent></Card></TabsContent>diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 8d82a6d1..ee698c24 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -19,6 +19,8 @@ import AccessForm, {} from "@/components/view/access-form";import EmailVerificationMessage from "./access-form/email-verification-form";+import LinkPreview from "./link-preview";+import { TNavData } from "./nav";import ViewData, { TViewDocumentData } from "./view-data";type RowData = { [key: string]: any };@@ -117,6 +119,14 @@ export default function DocumentView({);const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);+ const [linkOpened, setLinkOpened] = useState<boolean>(false);++ // Check if this is a link document+ const isLinkDocument = document.type === "link";+ // For link documents, get URL from viewData.file (from API) or fallback to document.file+ const linkUrl = isLinkDocument+ ? (viewData.file || document.file)+ : null;const handleSubmission = async (): Promise<void> => {setIsLoading(true);@@ -161,20 +171,24 @@ export default function DocumentView({verificationToken,isTeamMember,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;- plausible("documentViewed"); // track the event- analytics.identify(- userEmail ?? verifiedEmail ?? data.email ?? undefined,- );- analytics.capture("Link Viewed", {- linkId: link.id,- documentId: document.id,- linkType: "DOCUMENT_LINK",- viewerId: viewId,- viewerEmail: data.email ?? verifiedEmail ?? userEmail,- isEmbedded,- isTeamMember,- teamId: link.teamId,- });++ // For link documents, we don't track views here - only when the link is opened+ if (!isLinkDocument) {+ plausible("documentViewed"); // track the event+ analytics.identify(+ userEmail ?? verifiedEmail ?? data.email ?? undefined,+ );+ analytics.capture("Link Viewed", {+ linkId: link.id,+ documentId: document.id,+ linkType: "DOCUMENT_LINK",+ viewerId: viewId,+ viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ isEmbedded,+ isTeamMember,+ teamId: link.teamId,+ });+ }// set the verification token to the cookieif (verificationToken) {@@ -277,6 +291,73 @@ export default function DocumentView({);}+ const handleLinkContinue = async () => {+ // Use viewData.file or fallback to document.file+ const finalLinkUrl = linkUrl || document.file;+ if (!finalLinkUrl) {+ console.error("Link URL not available", { linkUrl, documentFile: document.file, viewDataFile: viewData.file });+ return;+ }++ // Track link open in analytics and record 100% completion (non-blocking)+ if (viewData.viewId) {+ // Record page view for page 1 to mark 100% completion+ fetch("/api/record_view", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ linkId: link.id,+ documentId: document.id,+ viewId: viewData.viewId,+ pageNumber: 1,+ versionNumber: document.versions[0].versionNumber,+ duration: 1000, // 1 second minimum duration+ time: Date.now(),+ }),+ keepalive: true,+ }).catch((error) => {+ console.error("Failed to record page view:", error);+ });++ // Track link open+ fetch("/api/record_link_open", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ linkId: link.id,+ documentId: document.id,+ viewId: viewData.viewId,+ linkUrl: finalLinkUrl,+ viewerEmail: data.email ?? verifiedEmail ?? userEmail ?? undefined,+ }),+ }).catch((error) => {+ console.error("Failed to track link open:", error);+ });++ plausible("linkOpened");+ analytics.capture("Link Opened", {+ linkId: link.id,+ documentId: document.id,+ linkType: "DOCUMENT_LINK",+ viewerId: viewData.viewId,+ viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ teamId: link.teamId,+ });+ }++ // Open link in new window/tab immediately+ setLinkOpened(true);+ const newWindow = window.open(finalLinkUrl, "_blank", "noopener,noreferrer");+ if (!newWindow) {+ // If popup blocked, fallback to current window+ window.location.href = finalLinkUrl;+ }+ };+if (isLoading) {return (<div className="flex h-screen items-center justify-center">@@ -284,6 +365,41 @@ export default function DocumentView({</div>);}++ // For link documents, show the preview page+ if (submitted && isLinkDocument) {+ const navData: TNavData = {+ linkId: link.id,+ documentId: document.id,+ viewId: viewData.viewId,+ isPreview: viewData.isPreview || false,+ allowDownload: link.allowDownload || false,+ brand: brand,+ annotationsFeatureEnabled: annotationsEnabled || false,+ };++ // Use viewData.file or fallback to document.file+ const finalLinkUrl = linkUrl || document.file || "";++ return (+ <div+ className="bg-gray-950"+ style={{+ backgroundColor:+ brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",+ }}+ >+ <LinkPreview+ linkUrl={finalLinkUrl}+ linkName={document.name}+ brand={brand}+ onContinue={handleLinkContinue}+ navData={navData}+ />+ </div>+ );+ }+return (<divclassName="bg-gray-950"diff --git a/components/view/link-preview.tsx b/components/view/link-preview.tsxnew file mode 100644index 00000000..a2f473dd--- /dev/null+++ b/components/view/link-preview.tsx@@ -0,0 +1,98 @@+import { useEffect, useState } from "react";++import { ExternalLink } from "lucide-react";++import { Brand } from "@prisma/client";++import { Button } from "@/components/ui/button";++import Nav, { TNavData } from "./nav";++interface LinkPreviewProps {+ linkUrl: string;+ linkName: string;+ brand?: Partial<Brand> | null;+ onContinue: () => void;+ navData: TNavData;+}++export default function LinkPreview({+ linkUrl,+ linkName,+ brand,+ onContinue,+ navData,+}: LinkPreviewProps) {+ const [domain, setDomain] = useState<string>("");++ useEffect(() => {+ if (!linkUrl) {+ console.warn("LinkPreview: linkUrl is missing", { linkUrl, linkName });+ return;+ }++ try {+ const url = new URL(linkUrl);+ setDomain(url.hostname.replace("www.", ""));+ } catch (e) {+ // If URL parsing fails, try to extract domain from string+ const match = linkUrl.match(/https?:\/\/([^\/]+)/);+ if (match) {+ setDomain(match[1].replace("www.", ""));+ } else {+ setDomain(linkUrl.length > 50 ? linkUrl.substring(0, 50) + "..." : linkUrl);+ }+ }+ }, [linkUrl, linkName]);++ return (+ <>+ <Nav pageNumber={1} numPages={1} navData={navData} />+ <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">+ <ExternalLink className="h-12 w-12 text-gray-600 dark:text-gray-300" />+ </div>+ <h2 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">+ {domain || linkName || "External Link"}+ </h2>+ <p className="max-w-md text-sm text-gray-500 dark:text-gray-400">+ You're leaving Papermark. If you trust this link, click to continue.+ </p>+ {linkUrl ? (+ <a+ href={linkUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="block cursor-pointer break-all text-sm font-medium text-blue-600 hover:text-blue-700 underline transition-colors dark:text-blue-400 dark:hover:text-blue-300"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onContinue();+ }}+ >+ {linkUrl}+ </a>+ ) : (+ <p className="text-sm text-gray-500 dark:text-gray-400">+ Link URL not available+ </p>+ )}+ <Button+ onClick={onContinue}+ className="w-full max-w-md space-x-2"+ size="lg"+ disabled={!linkUrl}+ >+ <ExternalLink className="h-4 w-4" />+ <span>Continue to {domain || "link"}</span>+ </Button>+ </div>+ </div>+ </>+ );+}+diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex a972629b..f195e69f 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -21,6 +21,7 @@ import { NotionPage } from "@/components/view/viewer/notion-page";import PDFViewer from "@/components/view/viewer/pdf-default-viewer";import { DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE } from "./dataroom/dataroom-document-view";+import LinkPreview from "./link-preview";import { TNavData } from "./nav";import AdvancedExcelViewer from "./viewer/advanced-excel-viewer";import DownloadOnlyViewer from "./viewer/download-only-viewer";@@ -112,6 +113,64 @@ export default function ViewData({screenshotProtectionEnabled={link.enableScreenshotProtection!}navData={navData}/>+ ) : viewData.fileType === "link" ? (+ <LinkPreview+ linkUrl={viewData.file || document.versions[0]?.file || ""}+ linkName={document.name}+ brand={brand}+ onContinue={async () => {+ const url = viewData.file || document.versions[0]?.file;+ if (!url) return;++ // Track link open in analytics and record 100% completion (non-blocking)+ if (navData.viewId) {+ // Record page view for page 1 to mark 100% completion+ fetch("/api/record_view", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ linkId: navData.linkId,+ documentId: navData.documentId,+ viewId: navData.viewId,+ pageNumber: 1,+ versionNumber: document.versions[0]?.versionNumber || 1,+ duration: 1000, // 1 second minimum duration+ time: Date.now(),+ }),+ keepalive: true,+ }).catch((error) => {+ console.error("Failed to record page view:", error);+ });++ // Track link open+ fetch("/api/record_link_open", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ linkId: navData.linkId,+ documentId: navData.documentId,+ viewId: navData.viewId,+ linkUrl: url,+ viewerEmail: viewerEmail,+ }),+ }).catch((error) => {+ console.error("Failed to track link open:", error);+ });+ }++ // Open link in new window immediately+ const newWindow = window.open(url, "_blank", "noopener,noreferrer");+ if (!newWindow) {+ // If popup blocked, fallback to current window+ window.location.href = url;+ }+ }}+ navData={navData}+ />) : document.downloadOnly ? (<DownloadOnlyViewerversionNumber={document.versions[0].versionNumber}diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex 44672b8b..89c025d9 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -75,6 +75,15 @@ export const processDocument = async ({}}+ // For link type, validate URL format+ if (type === "link") {+ try {+ new URL(key);+ } catch (error) {+ throw new Error("Invalid URL format for link document.");+ }+ }+const folder = await prisma.folder.findUnique({where: {teamId_path: {diff --git a/lib/constants.ts b/lib/constants.tsindex 3e61fc22..fba2109b 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -171,6 +171,7 @@ export const VIEWER_ACCEPTED_FILE_TYPES = {export const SUPPORTED_DOCUMENT_SIMPLE_TYPES = ["pdf","notion",+ "link","sheet","slides","docs",diff --git a/lib/utils/get-file-icon.tsx b/lib/utils/get-file-icon.tsxindex 1f5d9506..38b44765 100644--- a/lib/utils/get-file-icon.tsx+++ b/lib/utils/get-file-icon.tsx@@ -1,4 +1,4 @@-import { FileIcon, MailIcon } from "lucide-react";+import { FileIcon, Link as LinkIcon, MailIcon } from "lucide-react";import CadIcon from "@/components/shared/icons/files/cad";import DocsIcon from "@/components/shared/icons/files/docs";@@ -49,6 +49,8 @@ export function fileIcon({return <SheetIcon className={className} isLight={isLight} />;case "notion":return <NotionIcon className={className} />;+ case "link":+ return <LinkIcon className={className} />;case "image/vnd.dwg":case "image/vnd.dxf":case "cad":diff --git a/lib/zod/url-validation.ts b/lib/zod/url-validation.tsindex 2aff35df..fd41303b 100644--- a/lib/zod/url-validation.ts+++ b/lib/zod/url-validation.ts@@ -82,6 +82,7 @@ export const validateUrlSecurity = (url: string): boolean => {};// Custom validator for file paths - either Notion URLs or S3 storage paths+// Note: General URLs for link type are validated at the documentUploadSchema levelconst createFilePathValidator = () => {return z.string()@@ -222,12 +223,13 @@ export const documentUploadSchema = z.string().min(1, "Document name is required").max(255, "Document name too long"),- url: filePathSchema,+ url: z.string().min(1, "URL is required"), // Use string for now, will validate based on typestorageType: z.enum(["S3_PATH", "VERCEL_BLOB"], {errorMap: () => ({ message: "Invalid storage type" }),})- .default("VERCEL_BLOB"),+ .default("VERCEL_BLOB")+ .optional(),numPages: z.number().int().positive().optional(),type: z.enum(SUPPORTED_DOCUMENT_SIMPLE_TYPES as unknown as readonly [@@ -252,15 +254,42 @@ export const documentUploadSchema = z},).or(z.literal("text/html")) // Allow text/html for Notion documents- .nullish(), // Make contentType optional for Notion files+ .nullish(), // Make contentType optional for Notion files and linkscreateLink: z.boolean().optional(),fileSize: z.number().int().positive().optional(),})+ .refine(+ async (data) => {+ // For link type, validate URL format and security+ if (data.type === "link") {+ if (!data.url.startsWith("https://")) {+ return false;+ }+ try {+ new URL(data.url); // Validate URL format+ return validateUrlSecurity(data.url);+ } catch {+ return false;+ }+ }+ // For other types, use the file path validator+ return await filePathSchema.safeParseAsync(data.url).then((r) => r.success);+ },+ {+ message: "URL must be a valid HTTPS URL for link type, or a valid file path for other types",+ path: ["url"],+ },+ ).refine((data) => {- // Skip content type validation if it's not provided (e.g., for Notion files)+ // Skip content type validation if it's not provided (e.g., for Notion files or links)if (!data.contentType) {- return data.type === "notion";+ return data.type === "notion" || data.type === "link";+ }++ // For link type, content type is optional+ if (data.type === "link") {+ return true;}// Validate that content type matches the declared file type@@ -280,6 +309,11 @@ export const documentUploadSchema = z).refine(async (data) => {+ // For link type, storage type is not required and URL validation is handled elsewhere+ if (data.type === "link") {+ return true;+ }+// Skip storage type validation if not provided (e.g., for Notion files)if (!data.storageType) {// For Notion URLs, storage type is not requireddiff --git a/pages/api/record_link_open.ts b/pages/api/record_link_open.tsnew file mode 100644index 00000000..bc878822--- /dev/null+++ b/pages/api/record_link_open.ts@@ -0,0 +1,127 @@+import type { NextApiRequest, NextApiResponse } from "next";++import { getGeoData, LOCALHOST_GEO_DATA, LOCALHOST_IP } from "@/lib/utils/geo";+import { recordLinkViewTB } from "@/lib/tinybird";+import { isBot, userAgentFromString } from "@/lib/utils/user-agent";+import { EU_COUNTRY_CODES } from "@/lib/constants";+import { capitalize, getDomainWithoutWWW, log } from "@/lib/utils";++type Geo = {+ country?: string;+ city?: string;+ region?: string;+ latitude?: string;+ longitude?: string;+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ const {+ linkId,+ documentId,+ viewId,+ linkUrl,+ viewerEmail,+ } = req.body as {+ linkId: string;+ documentId: string;+ viewId: string;+ linkUrl: string;+ viewerEmail?: string;+ };++ if (!linkId || !documentId || !viewId || !linkUrl) {+ res.status(400).json({ message: "Missing required fields" });+ return;+ }++ const geo: Geo =+ process.env.VERCEL === "1" ? getGeoData(req.headers) : LOCALHOST_GEO_DATA;++ const referer = req.headers.referer;+ const ua = userAgentFromString(req.headers["user-agent"] || "");++ const bot = isBot(ua.ua);++ // don't track clicks from bots+ if (bot) {+ return res.status(200).json({ success: true, skipped: true });+ }++ const ip = process.env.VERCEL === "1"+ ? (Array.isArray(req.headers["x-forwarded-for"])+ ? req.headers["x-forwarded-for"][0]+ : req.headers["x-forwarded-for"]) || req.headers["x-real-ip"]+ : LOCALHOST_IP;++ // get continent, region & geolocation data+ const { continent, region } =+ process.env.VERCEL === "1"+ ? {+ continent: req.headers["x-vercel-ip-continent"] as string | undefined,+ region: req.headers["x-vercel-ip-country-region"] as string | undefined,+ }+ : LOCALHOST_GEO_DATA;++ const isEuCountry = geo.country && EU_COUNTRY_CODES.includes(geo.country);++ const refererDomain = referer ? getDomainWithoutWWW(referer) : "(direct)";++ const clickId = `click_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;++ const clickData = {+ timestamp: new Date(Date.now()).toISOString(),+ click_id: clickId,+ view_id: viewId,+ link_id: linkId,+ document_id: documentId,+ dataroom_id: null,+ continent: continent || "",+ country: geo.country || "Unknown",+ region: region || "Unknown",+ city: geo.city || "Unknown",+ latitude: geo.latitude || "Unknown",+ longitude: geo.longitude || "Unknown",+ device: ua.device.type ? capitalize(ua.device.type) : "Desktop",+ device_vendor: ua.device.vendor || "Unknown",+ device_model: ua.device.model || "Unknown",+ browser: ua.browser.name || "Unknown",+ browser_version: ua.browser.version || "Unknown",+ engine: ua.engine.name || "Unknown",+ engine_version: ua.engine.version || "Unknown",+ os: ua.os.name || "Unknown",+ os_version: ua.os.version || "Unknown",+ cpu_architecture: ua.cpu?.architecture || "Unknown",+ ua: ua.ua || "Unknown",+ bot: ua.isBot,+ referer: refererDomain,+ referer_url: referer || "(direct)",+ ip_address:+ // only record IP if it's a valid IP and not from a EU country+ typeof ip === "string" && ip.trim().length > 0 && !isEuCountry+ ? ip+ : null,+ };++ // Record link open in Tinybird (notifications/webhooks are handled when view is created)+ try {+ await recordLinkViewTB(clickData);+ } catch (error) {+ log({+ message: `Failed to record link open (tinybird) for ${linkId}. \n\n ${error}`,+ type: "error",+ mention: true,+ });+ // Still return success to not block the redirect+ }++ return res.status(200).json({ success: true });+}+diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 5f300d3a..f71b888a 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -337,11 +337,15 @@ export default async function handle(return res.status(404).end("Team not found");}+ // For link documents, storageType is optional but processDocument requires it+ // Use VERCEL_BLOB as a placeholder (not actually used for links)+ const finalStorageType = storageType || (fileType === "link" ? "VERCEL_BLOB" : "VERCEL_BLOB");+const document = await processDocument({documentData: {name,key: fileUrl,- storageType,+ storageType: finalStorageType,numPages,supportedFileType: fileType,contentType: contentType || null,