Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
refactor: send webhook from link view
Marc Seitzf771b059833f
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 25b7d9bc..08670698 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -592,32 +592,17 @@ export async function POST(request: NextRequest) {// Send events in the background to avoid blocking the responseif (newDataroomView) {- const headerObj = headersToObject(request.headers);waitUntil(- Promise.all([- // Record link view in Tinybird- recordLinkView({- req: request,- clickId: newId("linkView"),- viewId: newDataroomView.id,- linkId,- dataroomId,- }),-- // Send notification to the document owner- link.enableNotification- ? sendNotification({ viewId: newDataroomView.id })- : null,-- // Send webhook event- recordVisit({- viewId: newDataroomView.id,- linkId,- teamId: link.teamId!,- dataroomId,- headers: headerObj,- }),- ]),+ // Record link view in Tinybird+ recordLinkView({+ req: request,+ clickId: newId("linkView"),+ viewId: newDataroomView.id,+ linkId,+ dataroomId,+ teamId: link.teamId!,+ enableNotification: link.enableNotification,+ }),);}@@ -699,33 +684,17 @@ export async function POST(request: NextRequest) {select: { id: true },});- // Send events in the background to avoid blocking the response- const headerObj = headersToObject(request.headers);waitUntil(- Promise.all([- // Record link view in Tinybird- recordLinkView({- req: request,- clickId: newId("linkView"),- viewId: dataroomView.id,- linkId,- dataroomId,- }),-- // Send notification to the document owner- link.enableNotification- ? sendNotification({ viewId: dataroomView.id })- : null,-- // Send webhook event- recordVisit({- viewId: dataroomView.id,- linkId,- teamId: link.teamId!,- dataroomId,- headers: headerObj,- }),- ]),+ // Record link view in Tinybird+ recordLinkView({+ req: request,+ clickId: newId("linkView"),+ viewId: dataroomView.id,+ linkId,+ dataroomId,+ teamId: link.teamId!,+ enableNotification: link.enableNotification,+ }),);}diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex 56ba8efd..aa86a07d 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -573,37 +573,19 @@ export async function POST(request: NextRequest) {}if (newView) {- console.time("waitUntil");- // INFO: create a header object because headers look different on nextapirequest vs nextrequest- const headerObj = headersToObject(request.headers);// Record view in the background to avoid blocking the responsewaitUntil(- Promise.all([- // Record link view in Tinybird- recordLinkView({- req: request,- clickId: newId("linkView"),- viewId: newView.id,- linkId,- documentId,- }),-- // Send notification to the document owner- link.enableNotification- ? sendNotification({ viewId: newView.id })- : null,-- // Send webhook event- recordVisit({- viewId: newView.id,- linkId,- teamId: link.teamId!,- documentId,- headers: headerObj,- }),- ]),+ // Record link view in Tinybird+ recordLinkView({+ req: request,+ clickId: newId("linkView"),+ viewId: newView.id,+ linkId,+ documentId,+ teamId: link.teamId!,+ enableNotification: link.enableNotification,+ }),);- console.timeEnd("waitUntil");}const returnObject = {diff --git a/lib/api/views/send-webhook-event.ts b/lib/api/views/send-webhook-event.tsnew file mode 100644index 00000000..b8d996e1--- /dev/null+++ b/lib/api/views/send-webhook-event.ts@@ -0,0 +1,181 @@+import { getFeatureFlags } from "@/lib/featureFlags";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";+import { sendWebhooks } from "@/lib/webhook/send-webhooks";++export async function sendLinkViewWebhook({+ teamId,+ clickData,+}: {+ teamId: string;+ clickData: any;+}) {+ try {+ const {+ view_id: viewId,+ link_id: linkId,+ document_id: documentId,+ dataroom_id: dataroomId,+ } = clickData;++ if (!viewId || !linkId || !teamId) {+ throw new Error("Missing required parameters");+ }++ const features = await getFeatureFlags({ teamId });+ if (!features.webhooks) {+ // webhooks are not enabled for this team+ return;+ }++ // Get webhooks for team+ const webhooks = await prisma.webhook.findMany({+ where: {+ teamId,+ triggers: {+ array_contains: ["link.viewed"],+ },+ },+ select: {+ pId: true,+ url: true,+ secret: true,+ },+ });++ if (!webhooks || (webhooks && webhooks.length === 0)) {+ // No webhooks for team, so we don't need to send webhooks+ return;+ }++ // Get link information+ const link = await prisma.link.findUnique({+ where: { id: linkId, teamId },+ });++ if (!link) {+ throw new Error("Link not found");+ }++ // Prepare link data for webhook+ const linkData = {+ id: link.id,+ url: link.domainId+ ? `https://${link.domainSlug}/${link.slug}`+ : `https://www.papermark.io/view/${link.id}`,+ domain:+ link.domainId && link.domainSlug ? link.domainSlug : "papermark.io",+ key: link.domainId && link.slug ? link.slug : `view/${link.id}`,+ name: link.name,+ expiresAt: link.expiresAt?.toISOString() || null,+ hasPassword: !!link.password,+ allowList: link.allowList,+ denyList: link.denyList,+ enabledEmailProtection: link.emailProtected,+ enabledEmailVerification: link.emailAuthenticated,+ allowDownload: link.allowDownload ?? false,+ isArchived: link.isArchived,+ enabledNotification: link.enableNotification ?? false,+ enabledFeedback: link.enableFeedback ?? false,+ enabledQuestion: link.enableQuestion ?? false,+ enabledScreenshotProtection: link.enableScreenshotProtection ?? false,+ enabledAgreement: link.enableAgreement ?? false,+ enabledWatermark: link.enableWatermark ?? false,+ metaTitle: link.metaTitle,+ metaDescription: link.metaDescription,+ metaImage: link.metaImage,+ metaFavicon: link.metaFavicon,+ documentId: link.documentId,+ dataroomId: link.dataroomId,+ groupId: link.groupId,+ linkType: link.linkType,+ teamId: teamId,+ createdAt: link.createdAt.toISOString(),+ updatedAt: link.updatedAt.toISOString(),+ };++ // Get view information+ const view = await prisma.view.findUnique({+ where: { id: viewId, linkId },+ select: {+ id: true,+ viewedAt: true,+ viewerEmail: true,+ verified: true,+ },+ });++ if (!view) {+ throw new Error("View not found");+ }++ // Prepare view data for webhook+ const viewData = {+ viewedAt: view.viewedAt.toISOString(),+ viewId: view.id,+ email: view.viewerEmail,+ emailVerified: view.verified,+ country: clickData.country,+ city: clickData.city,+ device: clickData.device,+ browser: clickData.browser,+ os: clickData.os,+ ua: clickData.ua,+ referer: clickData.referer,+ };++ // Get document and dataroom information for webhook in parallel+ const [document, dataroom] = await Promise.all([+ documentId+ ? prisma.document.findUnique({+ where: { id: documentId, teamId },+ select: { id: true, name: true, contentType: true },+ })+ : null,+ dataroomId+ ? prisma.dataroom.findUnique({+ where: { id: dataroomId, teamId },+ select: { id: true, name: true },+ })+ : null,+ ]);++ // Prepare webhook payload+ const webhookData = {+ view: viewData,+ link: linkData,+ ...(document && {+ document: {+ id: document.id,+ name: document.name,+ contentType: document.contentType,+ teamId: teamId,+ },+ }),+ ...(dataroom && {+ dataroom: {+ id: dataroom.id,+ name: dataroom.name,+ teamId: teamId,+ },+ }),+ };++ // Send webhooks+ if (webhooks.length > 0) {+ await sendWebhooks({+ webhooks,+ trigger: "link.viewed",+ data: webhookData,+ });+ }+ return;+ } catch (error) {+ log({+ message: `Error sending webhooks for link view: ${error}`,+ type: "error",+ mention: true,+ });+ return;+ }+}diff --git a/lib/tracking/record-link-view.ts b/lib/tracking/record-link-view.tsindex a2e2ea2b..dbda263f 100644--- a/lib/tracking/record-link-view.ts+++ b/lib/tracking/record-link-view.ts@@ -5,6 +5,8 @@ import { geolocation, ipAddress } from "@vercel/functions";import { recordLinkViewTB } from "@/lib/tinybird";import { isBot } from "@/lib/utils/user-agent";+import sendNotification from "../api/notification-helper";+import { sendLinkViewWebhook } from "../api/views/send-webhook-event";import { EU_COUNTRY_CODES } from "../constants";import { capitalize, getDomainWithoutWWW } from "../utils";import { LOCALHOST_GEO_DATA, LOCALHOST_IP } from "../utils/geo";@@ -14,15 +16,19 @@ export async function recordLinkView({clickId,viewId,linkId,+ teamId,documentId,dataroomId,+ enableNotification,}: {req: NextRequest;clickId: string;viewId: string;linkId: string;+ teamId: string;documentId?: string;dataroomId?: string;+ enableNotification: boolean | null;}) {const ua = userAgent(req);const bot = isBot(ua.ua);@@ -34,15 +40,6 @@ export async function recordLinkView({const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;- // const cacheKey = `recordClick:${linkId}:${ip}`;-- // // by default, we deduplicate clicks for a domain + key pair from the same IP address – only record 1 click per hour- // // here, we check if the clickId is cached in Redis within the last hour- // const cachedClickId = await redis.get<string>(cacheKey);- // if (cachedClickId) {- // return null;- // }-// get continent, region & geolocation data// interesting, geolocation().region is Vercel's edge region – NOT the actual region// so we use the x-vercel-ip-country-region or geolocation().countryRegion to get the actual region@@ -69,11 +66,6 @@ export async function recordLinkView({link_id: linkId,document_id: documentId || null,dataroom_id: dataroomId || null,- 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,continent: continent || "",country: geo.country || "Unknown",region: region || "Unknown",@@ -94,17 +86,31 @@ export async function recordLinkView({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 view in Tinybird- await recordLinkViewTB(clickData);+ const locationData = {+ continent,+ country: geo.country || "Unknown",+ region: region || "Unknown",+ city: geo.city || "Unknown",+ };++ const [, ,] = await Promise.all([+ // record link view in Tinybird+ recordLinkViewTB(clickData),+- // const [,] = await Promise.all([- // // cache the click ID in Redis for 1 hour- // // redis.set(cacheKey, clickId, {- // // ex: 60 * 60,- // // }),- // ]);+ // send webhook event+ sendLinkViewWebhook({+ teamId,+ clickData,+ }),+ ]);return clickData;}