Skip to content

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

feat: add video viewer and tracking

Marc Seitzebd944033a92
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsx
index c67461d7..cbaaebeb 100644
--- a/components/view/dataroom/dataroom-view.tsx
+++ b/components/view/dataroom/dataroom-view.tsx
@@ -26,6 +26,7 @@ import EmailVerificationMessage from "../email-verification-form";
import AdvancedExcelViewer from "../viewer/advanced-excel-viewer";
import DownloadOnlyViewer from "../viewer/download-only-viewer";
import ImageViewer from "../viewer/image-viewer";
+import VideoViewer from "../viewer/video-viewer";
const ExcelViewer = dynamic(
() => import("@/components/view/viewer/excel-viewer"),
@@ -427,6 +428,23 @@ export default function DataroomView({
linkName={link.name ?? `Link #${link.id.slice(-5)}`}
/>
</div>
+ ) : viewData.fileType === "video" ? (
+ <div className="bg-gray-950">
+ <VideoViewer
+ file={viewData.file!}
+ linkId={link.id}
+ documentId={documentData.id}
+ viewId={viewData.viewId}
+ documentName={documentData.name}
+ allowDownload={viewData.canDownload ?? link.allowDownload!}
+ screenshotProtectionEnabled={link.enableScreenshotProtection!}
+ versionNumber={documentData.documentVersionNumber}
+ brand={brand}
+ dataroomId={dataroom.id}
+ setDocumentData={setDocumentData}
+ isPreview={viewData.isPreview}
+ />
+ </div>
) : viewData.pages ? (
<div className="bg-gray-950">
<PagesViewerNew
diff --git a/components/view/view-data.tsx b/components/view/view-data.tsx
index 9dce5d1a..1f1fad54 100644
--- a/components/view/view-data.tsx
+++ b/components/view/view-data.tsx
@@ -13,6 +13,7 @@ import { LinkWithDocument, NotionTheme, WatermarkConfig } from "@/lib/types";
import AdvancedExcelViewer from "./viewer/advanced-excel-viewer";
import DownloadOnlyViewer from "./viewer/download-only-viewer";
import ImageViewer from "./viewer/image-viewer";
+import VideoViewer from "./viewer/video-viewer";
const ExcelViewer = dynamic(
() => import("@/components/view/viewer/excel-viewer"),
@@ -146,6 +147,19 @@ export default function ViewData({
ipAddress={viewData.ipAddress}
linkName={link.name ?? `Link #${link.id.slice(-5)}`}
/>
+ ) : viewData.fileType === "video" ? (
+ <VideoViewer
+ file={viewData.file!}
+ linkId={link.id}
+ viewId={viewData.viewId}
+ documentId={document.id}
+ documentName={link.document?.name}
+ allowDownload={link.allowDownload!}
+ screenshotProtectionEnabled={link.enableScreenshotProtection!}
+ versionNumber={document.versions[0].versionNumber}
+ brand={brand}
+ isPreview={viewData.isPreview}
+ />
) : (
<PDFViewer
file={viewData.file}
diff --git a/components/view/viewer/video-player.tsx b/components/view/viewer/video-player.tsx
new file mode 100644
index 00000000..0b718edc
--- /dev/null
+++ b/components/view/viewer/video-player.tsx
@@ -0,0 +1,74 @@
+import {
+ forwardRef,
+ memo,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+} from "react";
+
+import { cn } from "@/lib/utils";
+
+interface VideoPlayerProps {
+ videoSrc: string;
+ onError?: (error: Error) => void;
+ controls?: boolean;
+ className?: string;
+ preventDownload?: boolean;
+}
+
+export const VideoPlayer = memo(
+ forwardRef<HTMLVideoElement, VideoPlayerProps>(
+ (
+ {
+ videoSrc,
+ onError,
+ controls = true,
+ className = "",
+ preventDownload = true,
+ },
+ ref,
+ ) => {
+ const videoRef = useRef<HTMLVideoElement>(null);
+
+ useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+
+ const handleError = (e: ErrorEvent) => {
+ console.error("Video playback error:", e);
+ onError?.(new Error("Failed to play video"));
+ };
+
+ video.addEventListener("error", handleError);
+
+ return () => {
+ video.removeEventListener("error", handleError);
+ };
+ }, [onError]);
+
+ return (
+ <video
+ ref={videoRef}
+ className={cn("max-h-full max-w-full object-contain", className)}
+ preload="metadata"
+ playsInline
+ controls={controls}
+ controlsList={
+ preventDownload ? "nodownload noremoteplayback" : undefined
+ }
+ onContextMenu={
+ preventDownload ? (e) => e.preventDefault() : undefined
+ }
+ src={videoSrc}
+ >
+ <source src={videoSrc} type="video/mp4" />
+ Your browser does not support the video tag.
+ </video>
+ );
+ },
+ ),
+);
+
+VideoPlayer.displayName = "VideoPlayer";
diff --git a/components/view/viewer/video-viewer.tsx b/components/view/viewer/video-viewer.tsx
new file mode 100644
index 00000000..2fa6c09f
--- /dev/null
+++ b/components/view/viewer/video-viewer.tsx
@@ -0,0 +1,148 @@
+import { useEffect, useRef, useState } from "react";
+
+import { Brand, DataroomBrand } from "@prisma/client";
+import { toast } from "sonner";
+
+import { createVideoTracker } from "@/lib/tracking/video-tracking";
+import { cn } from "@/lib/utils";
+
+import { ScreenProtector } from "../ScreenProtection";
+import { TDocumentData } from "../dataroom/dataroom-view";
+import Nav from "../nav";
+import { VideoPlayer } from "./video-player";
+
+export default function VideoViewer({
+ file,
+ linkId,
+ documentId,
+ viewId,
+ documentName,
+ allowDownload,
+ screenshotProtectionEnabled,
+ versionNumber,
+ brand,
+ dataroomId,
+ setDocumentData,
+ isPreview,
+}: {
+ file: string;
+ linkId: string;
+ documentId: string;
+ viewId?: string;
+ documentName: string;
+ allowDownload: boolean;
+ screenshotProtectionEnabled: boolean;
+ versionNumber: number;
+ brand?: Partial<Brand> | Partial<DataroomBrand> | null;
+ dataroomId?: string;
+ setDocumentData?: React.Dispatch<React.SetStateAction<TDocumentData | null>>;
+ isPreview?: boolean;
+}) {
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const [isWindowFocused, setIsWindowFocused] = useState(true);
+ const videoTrackerRef = useRef<ReturnType<typeof createVideoTracker> | null>(
+ null,
+ );
+
+ // Initialize video tracker
+ useEffect(() => {
+ if (!videoRef.current) return;
+
+ videoTrackerRef.current = createVideoTracker(videoRef.current, {
+ linkId,
+ documentId,
+ viewId,
+ dataroomId,
+ versionNumber,
+ isMuted: false,
+ isFocused: isWindowFocused,
+ isFullscreen: false,
+ isPreview,
+ playbackRate: 1,
+ volume: 1,
+ });
+
+ return () => {
+ videoTrackerRef.current?.cleanup();
+ };
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ dataroomId,
+ versionNumber,
+ isPreview,
+ isWindowFocused,
+ ]);
+
+ // Handle visibility change for analytics
+ useEffect(() => {
+ const handleVisibilityChange = () => {
+ if (!videoTrackerRef.current) return;
+ videoTrackerRef.current.trackVisibilityChange(
+ document.visibilityState === "visible",
+ );
+ };
+
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ };
+ }, []);
+
+ // Handle screenshot protection
+ useEffect(() => {
+ if (!screenshotProtectionEnabled) return;
+
+ const handleFocus = () => setIsWindowFocused(true);
+ const handleBlur = () => setIsWindowFocused(false);
+
+ window.addEventListener("focus", handleFocus);
+ window.addEventListener("blur", handleBlur);
+
+ return () => {
+ window.removeEventListener("focus", handleFocus);
+ window.removeEventListener("blur", handleBlur);
+ };
+ }, [screenshotProtectionEnabled]);
+
+ const handleVideoError = (error: Error) => {
+ console.error("Video playback error:", error);
+ toast.error("Error playing video. Please try again.");
+ };
+
+ return (
+ <>
+ <Nav
+ brand={brand}
+ documentName={documentName}
+ isDataroom={dataroomId ? true : false}
+ setDocumentData={setDocumentData}
+ isPreview={isPreview}
+ allowDownload={allowDownload}
+ linkId={linkId}
+ documentId={documentId}
+ viewId={viewId}
+ />
+ <div
+ style={{ height: "calc(100dvh - 64px)" }}
+ className={cn(
+ "relative flex items-center justify-center bg-black p-4",
+ !isWindowFocused &&
+ screenshotProtectionEnabled &&
+ "blur-xl transition-all duration-300",
+ )}
+ >
+ <div className="relative flex h-full w-full items-center justify-center">
+ <VideoPlayer
+ ref={videoRef}
+ videoSrc={file}
+ onError={handleVideoError}
+ preventDownload={!allowDownload}
+ />
+ {screenshotProtectionEnabled && <ScreenProtector />}
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/lib/constants.ts b/lib/constants.ts
index e82b672b..788c6c3d 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -99,6 +99,28 @@ export const SUPPORTED_DOCUMENT_SIMPLE_TYPES = [
"video",
] as const;
+export const VIDEO_EVENT_TYPES = [
+ // Playback events
+ "loaded", // Initial load
+ "played", // Play pressed
+ "seeked", // User seeked to position
+
+ // Speed events
+ "rate_changed", // Playback speed changed
+
+ // Volume events
+ "volume_up", // Volume increased
+ "volume_down", // Volume decreased
+ "muted", // Muted
+ "unmuted", // Unmuted
+
+ // View state events
+ "focus", // Window/tab gained focus
+ "blur", // Window/tab lost focus
+ "enterfullscreen", // Entered fullscreen
+ "exitfullscreen", // Exited fullscreen
+] as const;
+
export const COUNTRIES: { [key: string]: string } = {
AF: "Afghanistan",
AL: "Albania",
@@ -353,3 +375,37 @@ export const COUNTRIES: { [key: string]: string } = {
};
export const COUNTRY_CODES = Object.keys(COUNTRIES) as [string, ...string[]];
+
+export const EU_COUNTRY_CODES = [
+ "AT",
+ "BE",
+ "BG",
+ "CY",
+ "CZ",
+ "DE",
+ "DK",
+ "EE",
+ "ES",
+ "FI",
+ "FR",
+ "GB",
+ "GR",
+ "HR",
+ "HU",
+ "IE",
+ "IS",
+ "IT",
+ "LI",
+ "LT",
+ "LU",
+ "LV",
+ "MT",
+ "NL",
+ "NO",
+ "PL",
+ "PT",
+ "RO",
+ "SE",
+ "SI",
+ "SK",
+];
diff --git a/lib/tracking/video-tracking.ts b/lib/tracking/video-tracking.ts
new file mode 100644
index 00000000..96991276
--- /dev/null
+++ b/lib/tracking/video-tracking.ts
@@ -0,0 +1,321 @@
+import { VIDEO_EVENT_TYPES } from "@/lib/constants";
+
+type VideoTrackingEvent = {
+ linkId: string;
+ documentId: string;
+ viewId?: string;
+ dataroomId?: string;
+ versionNumber: number;
+ startTime: number;
+ endTime?: number;
+ playbackRate: number;
+ volume: number;
+ isMuted: boolean;
+ isFocused: boolean;
+ isFullscreen: boolean;
+ eventType: (typeof VIDEO_EVENT_TYPES)[number];
+ isPreview?: boolean;
+};
+
+type EventType = (typeof VIDEO_EVENT_TYPES)[number];
+
+// Simple debounce implementation with immediate option
+function debounce<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number,
+ immediate = false,
+): (...args: Parameters<T>) => void {
+ let timeout: NodeJS.Timeout | null = null;
+ let lastArgs: Parameters<T> | null = null;
+
+ return (...args: Parameters<T>) => {
+ lastArgs = args;
+
+ if (timeout) {
+ clearTimeout(timeout);
+ }
+
+ if (immediate && !timeout) {
+ func(...args);
+ }
+
+ timeout = setTimeout(() => {
+ if (!immediate && lastArgs) {
+ func(...lastArgs);
+ }
+ timeout = null;
+ lastArgs = null;
+ }, wait);
+ };
+}
+
+class VideoTracker {
+ private videoElement: HTMLVideoElement;
+ private lastTrackingTime: number = 0;
+ private isPlaying: boolean = false;
+ private lastTimeUpdate: number = Date.now();
+ private trackingConfig: Omit<
+ VideoTrackingEvent,
+ "startTime" | "endTime" | "eventType"
+ >;
+ private lastVolume: number = 1;
+ private hasLoaded: boolean = false;
+ private debouncedTrackEvent: Record<
+ EventType,
+ (eventType: EventType, endTime?: number) => void
+ >;
+ private boundEventListeners: { [key: string]: EventListener } = {};
+
+ constructor(
+ videoElement: HTMLVideoElement,
+ config: Omit<VideoTrackingEvent, "startTime" | "endTime" | "eventType">,
+ ) {
+ this.videoElement = videoElement;
+ this.trackingConfig = config;
+ this.lastVolume = videoElement.volume;
+
+ // Create a base debounced function
+ const createDebouncedHandler = (wait: number, immediate = false) =>
+ debounce(
+ (eventType: EventType, endTime?: number) => {
+ console.log(
+ `[VideoTracker] Tracking event: ${eventType} - ${endTime}`,
+ );
+ return this.trackEvent(eventType, endTime);
+ },
+ wait,
+ immediate,
+ );
+
+ // Initialize debounced handlers with different wait times
+ this.debouncedTrackEvent = {
+ loaded: createDebouncedHandler(1000, true), // Immediate for load events
+ played: createDebouncedHandler(1000),
+ seeked: createDebouncedHandler(500),
+ rate_changed: createDebouncedHandler(500),
+ volume_up: createDebouncedHandler(500),
+ volume_down: createDebouncedHandler(500),
+ muted: createDebouncedHandler(500, true),
+ unmuted: createDebouncedHandler(500, true),
+ focus: createDebouncedHandler(500, true),
+ blur: createDebouncedHandler(500, true),
+ enterfullscreen: createDebouncedHandler(500, true),
+ exitfullscreen: createDebouncedHandler(500, true),
+ };
+
+ this.setupEventListeners();
+ }
+
+ private addEventListenerWithCleanup(
+ target: EventTarget,
+ type: string,
+ listener: EventListener,
+ ) {
+ // Store the bound listener for cleanup
+ this.boundEventListeners[type] = listener;
+ target.addEventListener(type, listener);
+ }
+
+ private async trackEvent(eventType: EventType, endTime?: number) {
+ if (this.trackingConfig.isPreview) return;
+
+ const currentTime = this.videoElement.currentTime;
+
+ await fetch("/api/record_video_view", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ timestamp: new Date().toISOString(),
+ linkId: this.trackingConfig.linkId,
+ documentId: this.trackingConfig.documentId,
+ viewId: this.trackingConfig.viewId,
+ dataroomId: this.trackingConfig.dataroomId,
+ versionNumber: this.trackingConfig.versionNumber,
+ startTime: Math.round(this.lastTrackingTime),
+ endTime: endTime ? Math.round(endTime) : Math.round(currentTime),
+ playbackRate: this.videoElement.playbackRate,
+ volume: this.videoElement.volume,
+ isMuted: this.trackingConfig.isMuted,
+ isFocused: this.trackingConfig.isFocused,
+ isFullscreen: this.trackingConfig.isFullscreen,
+ eventType,
+ }),
+ });
+
+ this.lastTrackingTime = currentTime;
+ }
+
+ private setupEventListeners() {
+ // Loading events - only track the first load event
+ const handleLoad = () => {
+ if (!this.hasLoaded) {
+ this.hasLoaded = true;
+ this.debouncedTrackEvent.loaded("loaded");
+ }
+ };
+
+ this.addEventListenerWithCleanup(
+ this.videoElement,
+ "loadedmetadata",
+ handleLoad,
+ );
+ this.addEventListenerWithCleanup(this.videoElement, "canplay", handleLoad);
+
+ let lastPlayTime = 0;
+
+ // Playback events
+ this.addEventListenerWithCleanup(this.videoElement, "play", () => {
+ const now = Date.now();
+ if (this.isPlaying || now - lastPlayTime < 1000) return;
+
+ this.isPlaying = true;
+ this.lastTrackingTime = this.videoElement.currentTime;
+ lastPlayTime = now;
+ // Track play event with a slight delay to ensure we have the correct state
+ setTimeout(() => {
+ this.debouncedTrackEvent.played("played");
+ }, 100);
+ this.startPeriodicTracking();
+ });
+
+ let lastPauseTime = 0;
+
+ this.addEventListenerWithCleanup(this.videoElement, "pause", () => {
+ const now = Date.now();
+ if (!this.isPlaying || now - lastPauseTime < 1000) return;
+
+ this.isPlaying = false;
+ lastPauseTime = now;
+ this.stopPeriodicTracking();
+ // Track pause event with a slight delay to ensure we have the correct state
+ setTimeout(() => {
+ this.debouncedTrackEvent.played("played");
+ }, 100);
+ });
+
+ let seekStartTime: number | null = null;
+ let isSeeking = false;
+
+ this.addEventListenerWithCleanup(this.videoElement, "seeking", () => {
+ if (isSeeking) return;
+ isSeeking = true;
+ seekStartTime = this.videoElement.currentTime;
+ });
+
+ this.addEventListenerWithCleanup(this.videoElement, "seeked", () => {
+ if (!isSeeking) return;
+ if (
+ seekStartTime !== null &&
+ Math.abs(seekStartTime - this.videoElement.currentTime) > 1
+ ) {
+ this.debouncedTrackEvent.seeked("seeked");
+ }
+ seekStartTime = null;
+ isSeeking = false;
+ });
+
+ // Continuous playback tracking using timeupdate
+ let lastTimeupdateTime = 0;
+ this.addEventListenerWithCleanup(this.videoElement, "timeupdate", () => {
+ const now = Date.now();
+ if (this.isPlaying && now - lastTimeupdateTime >= 10000) {
+ // For periodic updates, use a non-debounced direct call to ensure timing
+ this.trackEvent("played");
+ lastTimeupdateTime = now;
+ }
+ });
+
+ // Speed events
+ let lastPlaybackRate = this.videoElement.playbackRate;
+ this.addEventListenerWithCleanup(this.videoElement, "ratechange", () => {
+ const newRate = this.videoElement.playbackRate;
+ if (Math.abs(newRate - lastPlaybackRate) < 0.01) return; // Only ignore if truly unchanged (floating point comparison)
+
+ this.debouncedTrackEvent.rate_changed("rate_changed");
+ lastPlaybackRate = newRate;
+ });
+
+ // Volume events
+ this.addEventListenerWithCleanup(this.videoElement, "volumechange", () => {
+ const prevMuted = this.trackingConfig.isMuted;
+ const prevVolume = this.lastVolume;
+
+ this.trackingConfig.isMuted = this.videoElement.muted;
+ this.lastVolume = this.videoElement.volume;
+
+ if (prevMuted !== this.videoElement.muted) {
+ const eventType = this.videoElement.muted ? "muted" : "unmuted";
+ this.debouncedTrackEvent[eventType](eventType);
+ } else if (
+ !this.videoElement.muted &&
+ Math.abs(prevVolume - this.videoElement.volume) > 0.05
+ ) {
+ const eventType =
+ this.videoElement.volume > prevVolume ? "volume_up" : "volume_down";
+ this.debouncedTrackEvent[eventType](eventType);
+ }
+ });
+
+ // Fullscreen events
+ let isInFullscreen = false;
+ this.addEventListenerWithCleanup(document, "fullscreenchange", () => {
+ const newIsFullscreen = !!document.fullscreenElement;
+ if (isInFullscreen === newIsFullscreen) return;
+
+ isInFullscreen = newIsFullscreen;
+ this.trackingConfig.isFullscreen = isInFullscreen;
+ const eventType = isInFullscreen ? "enterfullscreen" : "exitfullscreen";
+ this.debouncedTrackEvent[eventType](eventType);
+ });
+
+ // Handle video end
+ this.addEventListenerWithCleanup(this.videoElement, "ended", () => {
+ if (!this.isPlaying) return;
+ this.isPlaying = false;
+ this.debouncedTrackEvent.played("played");
+ });
+ }
+
+ private startPeriodicTracking() {
+ // Reset the timeupdate counter when starting tracking
+ this.lastTimeUpdate = Date.now();
+ }
+
+ private stopPeriodicTracking() {
+ // No need for cleanup as we're using the timeupdate event
+ }
+
+ public updateConfig(
+ config: Partial<
+ Omit<VideoTrackingEvent, "startTime" | "endTime" | "eventType">
+ >,
+ ) {
+ this.trackingConfig = { ...this.trackingConfig, ...config };
+ }
+
+ public trackVisibilityChange(isVisible: boolean) {
+ const eventType = isVisible ? "focus" : "blur";
+ this.debouncedTrackEvent[eventType](eventType);
+ }
+
+ public cleanup() {
+ // Remove all event listeners
+ Object.entries(this.boundEventListeners).forEach(([type, listener]) => {
+ const target = type === "fullscreenchange" ? document : this.videoElement;
+ target.removeEventListener(type, listener);
+ });
+
+ if (this.isPlaying) {
+ this.debouncedTrackEvent.blur("blur");
+ }
+ }
+}
+
+export const createVideoTracker = (
+ videoElement: HTMLVideoElement,
+ config: Omit<VideoTrackingEvent, "startTime" | "endTime" | "eventType">,
+) => {
+ return new VideoTracker(videoElement, config);
+};
diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.ts
index 20e2e09e..46ec7588 100644
--- a/pages/api/views-dataroom.ts
+++ b/pages/api/views-dataroom.ts
@@ -628,7 +628,11 @@ export default async function handle(
return;
}
- if (documentVersion.type === "pdf" || documentVersion.type === "image") {
+ if (
+ documentVersion.type === "pdf" ||
+ documentVersion.type === "image" ||
+ documentVersion.type === "video"
+ ) {
documentVersion.file = await getFile({
data: documentVersion.file,
type: documentVersion.storageType,
@@ -717,7 +721,8 @@ export default async function handle(
(documentVersion &&
(documentVersion.type === "pdf" ||
documentVersion.type === "image" ||
- documentVersion.type === "zip")) ||
+ documentVersion.type === "zip" ||
+ documentVersion.type === "video")) ||
(documentVersion && useAdvancedExcelViewer)
? documentVersion.file
: undefined,
diff --git a/pages/api/views.ts b/pages/api/views.ts
index f310c3b2..42aebc2d 100644
--- a/pages/api/views.ts
+++ b/pages/api/views.ts
@@ -496,7 +496,11 @@ export default async function handle(
return;
}
- if (documentVersion.type === "pdf" || documentVersion.type === "image") {
+ if (
+ documentVersion.type === "pdf" ||
+ documentVersion.type === "image" ||
+ documentVersion.type === "video"
+ ) {
documentVersion.file = await getFile({
data: documentVersion.file,
type: documentVersion.storageType,
@@ -548,7 +552,8 @@ export default async function handle(
(documentVersion &&
(documentVersion.type === "pdf" ||
documentVersion.type === "image" ||
- documentVersion.type === "zip")) ||
+ documentVersion.type === "zip" ||
+ documentVersion.type === "video")) ||
(documentVersion && useAdvancedExcelViewer)
? documentVersion.file
: undefined,