Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add video analytics on document detail page
Marc Seitzae003a076bac
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex d0828195..f4451cc8 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -537,6 +537,7 @@ export default function DocumentHeader({{primaryVersion.type !== "notion" &&primaryVersion.type !== "sheet" &&primaryVersion.type !== "zip" &&+ primaryVersion.type !== "video" &&(!orientationLoading ? (<ButtonTooltip content="Change orientation"><Button@@ -560,29 +561,31 @@ export default function DocumentHeader({</div>))}- {primaryVersion.type !== "notion" && (- <AddDocumentModal- newVersion- openModal={openAddDocModal}- setAddDocumentModalOpen={setOpenAddDocModal}- >- <Button- variant="ghost"- size="icon"- onClick={(e) => {- e.stopPropagation();- setOpenAddDocModal(true);- }}- className="hidden md:flex"+ {primaryVersion.type !== "notion" &&+ primaryVersion.type !== "video" && (+ <AddDocumentModal+ newVersion+ openModal={openAddDocModal}+ setAddDocumentModalOpen={setOpenAddDocModal}>- <FileUp className="h-6 w-6" />- </Button>- </AddDocumentModal>- )}+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ setOpenAddDocModal(true);+ }}+ className="hidden md:flex"+ >+ <FileUp className="h-6 w-6" />+ </Button>+ </AddDocumentModal>+ )}{prismaDocument.type !== "notion" &&prismaDocument.type !== "sheet" &&prismaDocument.type !== "zip" &&+ prismaDocument.type !== "video" &&prismaDocument.assistantEnabled && (<ButtonclassName="group hidden h-8 space-x-1 whitespace-nowrap bg-gradient-to-r from-[#16222A] via-emerald-500 to-[#16222A] text-xs duration-200 ease-linear hover:bg-right md:flex lg:h-9 lg:text-sm"@@ -626,29 +629,31 @@ export default function DocumentHeader({><DropdownMenuLabel>Actions</DropdownMenuLabel><DropdownMenuGroup className="block md:hidden">- {prismaDocument.type !== "notion" && (- <DropdownMenuItem>- <AddDocumentModal- newVersion- setAddDocumentModalOpen={setAddDocumentVersion}- >- <button- title="Add a new version"- className="flex items-center"- onClick={(e) => {- e.stopPropagation();- setAddDocumentVersion(true);- }}+ {prismaDocument.type !== "notion" &&+ primaryVersion.type !== "video" && (+ <DropdownMenuItem>+ <AddDocumentModal+ newVersion+ setAddDocumentModalOpen={setAddDocumentVersion}>- <FileUp className="mr-2 h-4 w-4" /> Add new version- </button>- </AddDocumentModal>- </DropdownMenuItem>- )}+ <button+ title="Add a new version"+ className="flex items-center"+ onClick={(e) => {+ e.stopPropagation();+ setAddDocumentVersion(true);+ }}+ >+ <FileUp className="mr-2 h-4 w-4" /> Add new version+ </button>+ </AddDocumentModal>+ </DropdownMenuItem>+ )}{prismaDocument.type !== "notion" &&prismaDocument.type !== "sheet" &&- prismaDocument.type !== "zip" && (+ prismaDocument.type !== "zip" &&+ primaryVersion.type !== "video" && (<><DropdownMenuItemonClick={() => changeDocumentOrientation()}@@ -679,6 +684,7 @@ export default function DocumentHeader({{primaryVersion.type !== "notion" &&primaryVersion.type !== "sheet" &&primaryVersion.type !== "zip" &&+ primaryVersion.type !== "video" &&(!prismaDocument.assistantEnabled ? (<DropdownMenuItemonClick={() =>@@ -775,14 +781,15 @@ export default function DocumentHeader({</DropdownMenuItem>{/* Download latest version */}- {primaryVersion.type !== "notion" ? (- <DropdownMenuItem- onClick={() => downloadDocument(primaryVersion)}- >- <DownloadIcon className="mr-2 h-4 w-4" />- Download latest version- </DropdownMenuItem>- ) : null}+ {primaryVersion.type !== "notion" &&+ primaryVersion.type !== "video" && (+ <DropdownMenuItem+ onClick={() => downloadDocument(primaryVersion)}+ >+ <DownloadIcon className="mr-2 h-4 w-4" />+ Download latest version+ </DropdownMenuItem>+ )}<DropdownMenuSeparator />diff --git a/components/documents/video-analytics.tsx b/components/documents/video-analytics.tsxnew file mode 100644index 00000000..0609c7d7--- /dev/null+++ b/components/documents/video-analytics.tsx@@ -0,0 +1,232 @@+import { DocumentVersion } from "@prisma/client";+import { formatDistanceToNow } from "date-fns";+import {+ Area,+ AreaChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import useSWR from "swr";++import StatsElement from "@/components/documents/stats-element";+import VideoChartPlaceholder from "@/components/documents/video-chart-placeholder";+import { Card, CardContent } from "@/components/ui/card";+import LoadingSpinner from "@/components/ui/loading-spinner";++import { fetcher } from "@/lib/utils";++interface VideoAnalyticsProps {+ teamId: string;+ documentId: string;+ primaryVersion: DocumentVersion;+}++export default function VideoAnalytics({+ teamId,+ documentId,+ primaryVersion,+}: VideoAnalyticsProps) {+ const { data, error, isLoading } = useSWR<{+ overall: {+ unique_views: number;+ total_views: number;+ total_watch_time: number;+ avg_view_duration: number;+ last_viewed_at: string;+ first_viewed_at: string;+ view_distribution: Array<{+ start_time: number;+ unique_views: number;+ total_views: number;+ }>;+ } | null;+ }>(`/api/teams/${teamId}/documents/${documentId}/video-analytics`, fetcher);++ if (error) {+ console.error("Error loading video analytics:", error);+ return null;+ }++ if (isLoading) {+ return (+ <Card>+ <CardContent className="flex h-[300px] items-center justify-center">+ <LoadingSpinner />+ </CardContent>+ </Card>+ );+ }++ console.log(data);+ if (!data?.overall) {+ const emptyStats = [+ {+ name: "Total visits",+ value: "0",+ active: false,+ },+ {+ name: "Watch time",+ value: "0:00",+ unit: "minutes",+ active: false,+ },+ {+ name: "Average view duration",+ value: "0:00",+ unit: "minutes",+ active: false,+ },+ ];++ return (+ <div className="space-y-4">+ <VideoChartPlaceholder length={primaryVersion.length} />+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {emptyStats.map((stat, index) => (+ <StatsElement key={stat.name} stat={stat} statIdx={index} />+ ))}+ </div>+ </div>+ );+ }++ const formatTime = (seconds: number) => {+ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = Math.floor(seconds % 60);+ return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;+ };++ const formatTooltipTime = (value: number) => {+ return formatTime(value);+ };++ const CustomTooltip = ({ active, payload, label }: any) => {+ if (active && payload && payload.length) {+ const uniqueViews = payload[0].value;+ const playbackCount = payload[1].value;+ const intensity = playbackCount / uniqueViews || 1;++ return (+ <div className="space-y-1 rounded-md border bg-background p-2 text-sm">+ <p className="font-medium">{formatTooltipTime(label)}</p>+ <div className="space-y-0.5 text-muted-foreground">+ <p className="flex items-center gap-2">+ <span className="h-2 w-2 rounded-full bg-emerald-500" />+ {uniqueViews} unique viewer{uniqueViews !== 1 ? "s" : ""}+ </p>+ <p className="flex items-center gap-2">+ <span className="h-2 w-2 rounded-full bg-[#3B82F6]" />+ {playbackCount} playback{playbackCount !== 1 ? "s" : ""}+ </p>+ <p className="pt-1 text-xs">+ Replayed {(intensity - 1).toFixed(1)}x on average+ </p>+ </div>+ </div>+ );+ }+ return null;+ };++ const stats = [+ {+ name: "Total visits",+ value: data.overall.unique_views.toString(),+ active: true,+ },+ {+ name: "Watch time",+ value: formatTime(data.overall.total_watch_time),+ unit: "minutes",+ active: true,+ },+ {+ name: "Average view duration",+ value: formatTime(data.overall.avg_view_duration),+ unit: "minutes",+ active: true,+ },+ ];++ return (+ <div className="space-y-4">+ <div className="mt-2 flex items-center justify-center gap-4 text-sm text-muted-foreground">+ <div className="flex items-center gap-2">+ <div className="h-3 w-3 rounded-full bg-emerald-500" />+ <span>Unique Viewers</span>+ </div>+ <div className="flex items-center gap-2">+ <div className="h-3 w-3 rounded-full bg-[#3B82F6]" />+ <span>Playback Count</span>+ </div>+ </div>+ <div className="-mx-9 h-[300px]">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart+ data={data.overall.view_distribution}+ margin={{ top: 10, right: 10, left: 0, bottom: 0 }}+ >+ <XAxis+ dataKey="start_time"+ tickFormatter={formatTooltipTime}+ stroke="#888888"+ fontSize={12}+ />+ <YAxis+ stroke="#888888"+ fontSize={12}+ tickFormatter={(value) => Math.floor(value).toString()}+ domain={[0, (dataMax: number) => dataMax + 1]}+ padding={{ top: 20 }}+ allowDecimals={false}+ />+ <Tooltip content={<CustomTooltip />} />+ <defs>+ <linearGradient+ id="uniqueViewsGradient"+ x1="0"+ y1="0"+ x2="0"+ y2="1"+ >+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />+ </linearGradient>+ <linearGradient id="playbackGradient" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#3B82F6" stopOpacity={0.3} />+ <stop offset="95%" stopColor="#3B82F6" stopOpacity={0} />+ </linearGradient>+ </defs>+ <Area+ type="monotone"+ dataKey="unique_views"+ stroke="#10b981"+ strokeWidth={2}+ fill="url(#uniqueViewsGradient)"+ dot={false}+ name="Unique Viewers"+ />+ <Area+ type="monotone"+ dataKey="total_views"+ stroke="#3B82F6"+ strokeWidth={2}+ fill="url(#playbackGradient)"+ dot={false}+ name="Playback Count"+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>++ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {stats.map((stat, index) => (+ <StatsElement key={stat.name} stat={stat} statIdx={index} />+ ))}+ </div>+ </div>+ );+}diff --git a/components/documents/video-chart-placeholder.tsx b/components/documents/video-chart-placeholder.tsxnew file mode 100644index 00000000..896626d2--- /dev/null+++ b/components/documents/video-chart-placeholder.tsx@@ -0,0 +1,100 @@+import {+ Area,+ AreaChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";++export default function VideoChartPlaceholder({+ length,+}: {+ length: number | null;+}) {+ const videoLength = length || 51;+ // Generate placeholder data with a nice curve+ const data = Array.from({ length: videoLength }, (_, i) => ({+ start_time: i,+ unique_views:+ i < videoLength / 3 ? 10 : i > videoLength - videoLength / 3 ? 3 : 6,+ }));++ const formatTime = (seconds: number) => {+ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = Math.floor(seconds % 60);+ return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;+ };++ const CustomTooltip = ({ active, payload, label }: any) => {+ if (active && payload && payload.length) {+ return (+ <div className="space-y-1 rounded-md border bg-background p-2 text-sm">+ <p className="text-xs text-muted-foreground">Example Data</p>+ <p className="font-medium">{formatTime(label)}</p>+ <div className="space-y-0.5 text-muted-foreground">+ <p className="flex items-center gap-2">+ <span className="h-2 w-2 rounded-full bg-gray-400" />+ {payload[0].value} unique viewers+ </p>+ <p className="flex items-center gap-2">+ <span className="h-2 w-2 rounded-full bg-gray-600" />+ {payload[0].value} playbacks+ </p>+ </div>+ </div>+ );+ }+ return null;+ };++ return (+ <div className="space-y-4">+ <div className="-ml-9 h-[300px]">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart+ data={data}+ margin={{ top: 10, right: 10, left: 0, bottom: 0 }}+ >+ <XAxis+ dataKey="start_time"+ tickFormatter={formatTime}+ stroke="#888888"+ fontSize={12}+ />+ <YAxis+ stroke="#888888"+ fontSize={12}+ tickFormatter={(value) => Math.floor(value).toString()}+ domain={[0, 1]}+ padding={{ top: 20 }}+ allowDecimals={false}+ />+ <Tooltip content={<CustomTooltip />} />+ <defs>+ <linearGradient+ id="uniqueViewsGradient"+ x1="0"+ y1="0"+ x2="0"+ y2="1"+ >+ <stop offset="5%" stopColor="#9CA3AF" stopOpacity={0.3} />+ <stop offset="95%" stopColor="#9CA3AF" stopOpacity={0} />+ </linearGradient>+ </defs>+ <Area+ type="monotone"+ dataKey="unique_views"+ stroke="#9CA3AF"+ strokeWidth={2}+ fill="url(#uniqueViewsGradient)"+ dot={false}+ name="Unique Viewers"+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ </div>+ );+}diff --git a/components/visitors/visitor-video-chart.tsx b/components/visitors/visitor-video-chart.tsxnew file mode 100644index 00000000..7758dcc3--- /dev/null+++ b/components/visitors/visitor-video-chart.tsx@@ -0,0 +1,113 @@+import {+ Area,+ AreaChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import useSWR from "swr";++import { Card } from "@/components/ui/card";+import LoadingSpinner from "@/components/ui/loading-spinner";++import { fetcher } from "@/lib/utils";++export default function VisitorVideoChart({+ documentId,+ viewId,+ teamId,+}: {+ documentId: string;+ viewId: string;+ teamId: string;+}) {+ // Fetch video events if this is a video document+ const { data: videoEvents, error: videoError } = useSWR<{+ data: Array<{+ start_time: number;+ views: number;+ }>;+ }>(+ teamId+ ? `/api/teams/${teamId}/documents/${documentId}/views/${viewId}/video-stats`+ : null,+ fetcher,+ );++ if (videoError) {+ console.error("Error loading video events:", videoError);+ return null;+ }++ if (!videoEvents) {+ return (+ <Card>+ <div className="flex h-[200px] items-center justify-center">+ <LoadingSpinner />+ </div>+ </Card>+ );+ }++ const formatTime = (seconds: number) => {+ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = Math.floor(seconds % 60);+ return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;+ };++ return (+ <div className="-ml-10 h-[200px]">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart+ data={videoEvents.data}+ margin={{ top: 10, right: 10, left: 0, bottom: 0 }}+ >+ <XAxis+ dataKey="start_time"+ tickFormatter={formatTime}+ stroke="#888888"+ fontSize={12}+ />+ <YAxis+ stroke="#888888"+ fontSize={12}+ tickFormatter={(value) => Math.floor(value).toString()}+ domain={[0, (dataMax: number) => dataMax + 1]}+ padding={{ top: 20 }}+ allowDecimals={false}+ />+ <Tooltip+ content={({ active, payload, label }) => {+ if (active && payload && payload.length) {+ return (+ <div className="space-y-1 rounded-md border bg-background p-2 text-sm">+ <p className="font-medium">{formatTime(label)}</p>+ <div className="space-y-0.5 text-muted-foreground">+ <p>Playback count: {payload[0].value}</p>+ </div>+ </div>+ );+ }+ return null;+ }}+ />+ <Area+ type="monotone"+ dataKey="views"+ stroke="#10b981"+ strokeWidth={2}+ fill="url(#playbackGradient)"+ dot={false}+ />+ <defs>+ <linearGradient id="playbackGradient" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />+ </linearGradient>+ </defs>+ </AreaChart>+ </ResponsiveContainer>+ </div>+ );+}diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex 1b0c4c4a..75e443cb 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -62,8 +62,13 @@ import { VisitorAvatar } from "./visitor-avatar";import VisitorChart from "./visitor-chart";import VisitorUserAgent from "./visitor-useragent";import VisitorUserAgentPlaceholder from "./visitor-useragent-placeholder";+import VisitorVideoChart from "./visitor-video-chart";-export default function VisitorsTable() {+export default function VisitorsTable({+ isVideo = false,+}: {+ isVideo?: boolean;+}) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;const [currentPage, setCurrentPage] = useState<number>(1);@@ -116,6 +121,8 @@ export default function VisitorsTable() {setIsLoading(false);};+ console.log(views);+return (<div className="w-full"><div className="mb-2 md:mb-4">@@ -403,12 +410,20 @@ export default function VisitorsTable() {Version {view.versionNumber}</div></div>- <VisitorChart- documentId={view.documentId!}- viewId={view.id}- totalPages={view.versionNumPages}- versionNumber={view.versionNumber}- />+ {isVideo ? (+ <VisitorVideoChart+ documentId={view.documentId!}+ viewId={view.id}+ teamId={view.teamId!}+ />+ ) : (+ <VisitorChart+ documentId={view.documentId!}+ viewId={view.id}+ totalPages={view.versionNumPages}+ versionNumber={view.versionNumber}+ />+ )}</TableCell></TableRow></>diff --git a/pages/api/teams/[teamId]/documents/[id]/video-analytics.ts b/pages/api/teams/[teamId]/documents/[id]/video-analytics.tsnew file mode 100644index 00000000..19be7f7a--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/video-analytics.ts@@ -0,0 +1,233 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { getVideoEventsByDocument } from "@/lib/tinybird/pipes";+import { CustomUser } from "@/lib/types";++interface AnalyticsResponse {+ overall: {+ unique_views: number;+ total_views: number;+ total_watch_time: number;+ avg_view_duration: number;+ last_viewed_at: string;+ first_viewed_at: string;+ view_distribution: Array<{+ start_time: number;+ unique_views: number;+ total_views: number;+ }>;+ } | null;+}++function calculateAnalytics(+ events: Array<{+ timestamp: string;+ view_id: string;+ event_type: string;+ start_time: number;+ end_time: number;+ playback_rate: number;+ volume: number;+ is_muted: number;+ is_focused: number;+ is_fullscreen: number;+ }>,+ videoLength: number,+): AnalyticsResponse {+ if (!events || events.length === 0) {+ return {+ overall: null,+ };+ }++ try {+ // Filter for valid events and ensure valid time ranges > 1 second+ const validEvents = events.filter(+ (event) =>+ (event.event_type === "played" ||+ event.event_type === "muted" ||+ event.event_type === "unmuted" ||+ event.event_type === "rate_changed") &&+ event.end_time > event.start_time &&+ event.end_time - event.start_time >= 1,+ );++ // Get all unique view_ids from any event type+ const uniqueViewIds = new Set(events.map((e) => e.view_id));++ // Calculate total watch time+ let totalWatchTime = 0;+ validEvents.forEach((event) => {+ const duration = event.end_time - event.start_time;+ totalWatchTime += duration;+ });++ // Create a baseline array with zeros for every second+ const viewDistributionMap = new Map<+ number,+ { uniqueViewers: Set<string>; viewDurations: Map<string, number> }+ >();+ for (let t = 0; t <= videoLength; t++) {+ viewDistributionMap.set(t, {+ uniqueViewers: new Set(),+ viewDurations: new Map(), // Map of view_id to number of times this second was viewed+ });+ }++ // Fill in the actual playback periods+ validEvents.forEach((event) => {+ // For each second in the duration, track the view+ for (let t = event.start_time; t < event.end_time; t++) {+ const stats = viewDistributionMap.get(t)!;+ stats.uniqueViewers.add(event.view_id);++ // Increment the count for this view_id at this second+ const currentCount = stats.viewDurations.get(event.view_id) || 0;+ stats.viewDurations.set(event.view_id, currentCount + 1);+ }+ });++ // Sort events by timestamp to find first and last view+ const sortedEvents = [...validEvents].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),+ );++ // Convert view distribution to sorted array with both metrics+ const distributionArray = Array.from(viewDistributionMap.entries())+ .map(([start_time, stats]) => {+ // Sum up all view durations for this second+ let totalViews = 0;+ stats.viewDurations.forEach((count) => {+ totalViews += count;+ });++ return {+ start_time,+ unique_views: stats.uniqueViewers.size,+ total_views: totalViews,+ };+ })+ .sort((a, b) => a.start_time - b.start_time);++ return {+ overall: {+ unique_views: uniqueViewIds.size,+ total_views: uniqueViewIds.size,+ total_watch_time: totalWatchTime,+ avg_view_duration: totalWatchTime / uniqueViewIds.size,+ first_viewed_at: sortedEvents[0].timestamp,+ last_viewed_at: sortedEvents[sortedEvents.length - 1].timestamp,+ view_distribution: distributionArray,+ },+ };+ } catch (error) {+ console.error("Error calculating analytics:", error);+ console.error("Events data:", JSON.stringify(events, null, 2));+ throw error;+ }+}++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ try {+ const session = await getServerSession(req, res, authOptions);+ const user = session?.user as CustomUser;++ if (!user?.id) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const { teamId, id: documentId } = req.query as {+ teamId: string;+ id: string;+ };++ // Check if user has access to this document and team+ const document = await prisma.document.findFirst({+ where: {+ id: documentId,+ teamId,+ team: {+ users: {+ some: {+ userId: user.id,+ },+ },+ },+ },+ include: {+ versions: {+ where: {+ isPrimary: true,+ },+ select: {+ length: true,+ },+ },+ },+ });++ if (!document) {+ return res.status(404).json({ message: "Document not found" });+ }++ const videoLength = document.versions[0]?.length || 51;+ if (!videoLength) {+ return res.status(400).json({ message: "Video length not found" });+ }++ try {+ // Fetch video events from Tinybird+ console.log("Fetching video events for document:", documentId);+ const response = await getVideoEventsByDocument({+ document_id: documentId,+ });++ console.log("Tinybird response:", JSON.stringify(response, null, 2));++ if (!response || !response.data) {+ console.error("Invalid response from Tinybird:", response);+ return res+ .status(500)+ .json({ message: "Invalid response from analytics service" });+ }++ const analytics = calculateAnalytics(response.data, videoLength);+ return res.status(200).json(analytics);+ } catch (error) {+ console.error("Tinybird error details:", {+ error,+ message: error instanceof Error ? error.message : "Unknown error",+ stack: error instanceof Error ? error.stack : undefined,+ });+ return res.status(500).json({+ message: "Error fetching video analytics",+ error: error instanceof Error ? error.message : "Unknown error",+ });+ }+ } catch (error) {+ console.error(+ "Error in /api/teams/[teamId]/documents/[id]/video-analytics:",+ {+ error,+ message: error instanceof Error ? error.message : "Unknown error",+ stack: error instanceof Error ? error.stack : undefined,+ },+ );+ return res.status(500).json({+ message: "Internal Server Error",+ error: error instanceof Error ? error.message : "Unknown error",+ });+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.tsnew file mode 100644index 00000000..efb19d65--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.ts@@ -0,0 +1,119 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { getVideoEventsByView } from "@/lib/tinybird/pipes";+import { CustomUser } from "@/lib/types";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ return res.status(405).json({ error: "Method not allowed" });+ }++ try {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ const {+ teamId,+ id: documentId,+ viewId,+ } = req.query as {+ teamId: string;+ id: string;+ viewId: string;+ };+ const userId = (session.user as CustomUser).id;++ // Check document access+ const doc = await prisma.document.findFirst({+ where: {+ id: documentId,+ teamId,+ team: {+ users: {+ some: {+ userId,+ },+ },+ },+ },+ include: {+ versions: {+ where: {+ isPrimary: true,+ },+ select: {+ length: true,+ },+ },+ },+ });++ if (!doc) {+ return res.status(404).json({ error: "Document not found" });+ }++ const videoLength = doc.versions[0]?.length;+ if (!videoLength) {+ return res.status(400).json({ error: "Video length not found" });+ }++ // Fetch video events from Tinybird+ const response = await getVideoEventsByView({+ view_id: viewId,+ document_id: documentId,+ });++ if (!response?.data) {+ return res.status(200).json({ data: [] });+ }++ // Filter for valid events and ensure valid time ranges > 1 second+ const validEvents = response.data.filter(+ (event) =>+ (event.event_type === "played" ||+ event.event_type === "muted" ||+ event.event_type === "unmuted" ||+ event.event_type === "rate_changed") &&+ event.end_time > event.start_time &&+ event.end_time - event.start_time >= 1,+ );++ // Create a baseline array with zeros for every second+ const viewDistributionMap = new Map<number, number>();+ for (let t = 0; t <= videoLength; t++) {+ viewDistributionMap.set(t, 0);+ }++ // Fill in the actual playback periods+ validEvents.forEach((event) => {+ // For each second in the duration, increment the view count+ for (let t = event.start_time; t < event.end_time; t++) {+ viewDistributionMap.set(t, (viewDistributionMap.get(t) || 0) + 1);+ }+ });++ // Convert to sorted array+ const distributionArray = Array.from(viewDistributionMap.entries())+ .map(([start_time, views]) => ({+ start_time,+ views,+ }))+ .sort((a, b) => a.start_time - b.start_time);++ return res.status(200).json({+ data: distributionArray,+ });+ } catch (error) {+ console.error("Error fetching video stats:", error);+ return res.status(500).json({ error: "Internal Server Error" });+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex 3a3c9b0c..51ec7c43 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -1,35 +1,187 @@import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { View } from "@prisma/client";+import { JsonValue } from "@prisma/client/runtime/library";import { getServerSession } from "next-auth/next";import { LIMITS } from "@/lib/constants";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { getViewPageDuration } from "@/lib/tinybird";+import { getVideoEventsByDocument } from "@/lib/tinybird/pipes";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";+type DocumentVersion = {+ versionNumber: number;+ createdAt: Date;+ numPages: number | null;+ type: string | null;+ length: number | null;+};++type Document = {+ id: string;+ versions: DocumentVersion[];+ numPages: number | null;+ type: string | null;+ ownerId: string | null;+ _count: {+ views: number;+ };+};++type VideoEvent = {+ view_id: string;+ start_time: number;+ end_time: number;+ event_type: string;+};++type ViewWithExtras = View & {+ link: { name: string | null };+ feedbackResponse: {+ id: string;+ data: JsonValue;+ } | null;+ agreementResponse: {+ id: string;+ agreementId: string;+ agreement: { name: string };+ } | null;+};++async function getVideoViews(+ views: ViewWithExtras[],+ document: Document,+ videoEvents: { data: VideoEvent[] },+) {+ const durationsPromises = views.map((view) => {+ const viewEvents =+ videoEvents?.data.filter(+ (event) =>+ event.view_id === view.id &&+ ["played", "muted", "unmuted", "rate_changed"].includes(+ event.event_type,+ ) &&+ event.end_time > event.start_time &&+ event.end_time - event.start_time >= 1,+ ) || [];++ // Track timestamps and their frequency for total watch time+ const timestampCounts = new Map<number, number>();+ // Track unique timestamps for completion calculation+ const uniqueTimestamps = new Set<number>();++ // Calculate total watch time+ // let totalWatchTime = 0;+ viewEvents.forEach((event) => {+ for (let t = event.start_time; t < event.end_time; t++) {+ const timestamp = Math.floor(t);+ // Count total occurrences including replays+ timestampCounts.set(+ timestamp,+ (timestampCounts.get(timestamp) || 0) + 1,+ );+ // Track unique timestamps+ uniqueTimestamps.add(timestamp);+ }+ });++ // Sum up all timestamps including duplicates for total watch time+ let totalWatchTime = 0;+ timestampCounts.forEach((count) => {+ totalWatchTime += count;+ });++ // Get the number of unique timestamps watched+ const uniqueWatchTime = uniqueTimestamps.size;++ return {+ data: [],+ totalWatchTime,+ uniqueWatchTime,+ videoLength: document.versions[0]?.length || 0,+ };+ });++ const durations = await Promise.all(durationsPromises);++ return views.map((view, index) => {+ const relevantDocumentVersion = document.versions.find(+ (version) => version.createdAt <= view.viewedAt,+ );++ const duration = durations[index];+ const completionRate =+ duration.videoLength > 0+ ? Math.min(100, (duration.uniqueWatchTime / duration.videoLength) * 100)+ : 0;++ return {+ ...view,+ duration: durations[index],+ totalDuration: duration.totalWatchTime * 1000, // convert to milliseconds+ completionRate: completionRate.toFixed(),+ versionNumber: relevantDocumentVersion?.versionNumber || 1,+ versionNumPages: 0,+ };+ });+}++async function getDocumentViews(views: ViewWithExtras[], document: Document) {+ const durationsPromises = views.map((view) => {+ return getViewPageDuration({+ documentId: document.id,+ viewId: view.id,+ since: 0,+ });+ });++ const durations = await Promise.all(durationsPromises);++ return views.map((view, index) => {+ const relevantDocumentVersion = document.versions.find(+ (version) => version.createdAt <= view.viewedAt,+ );++ const numPages =+ relevantDocumentVersion?.numPages || document.numPages || 0;+ const completionRate = numPages+ ? (durations[index].data.length / numPages) * 100+ : 0;++ return {+ ...view,+ duration: durations[index],+ totalDuration: durations[index].data.reduce(+ (total: number, data: { sum_duration: number }) =>+ total + data.sum_duration,+ 0,+ ),+ completionRate: completionRate.toFixed(),+ versionNumber: relevantDocumentVersion?.versionNumber || 1,+ versionNumPages: numPages,+ };+ });+}+export default async function handle(req: NextApiRequest,res: NextApiResponse,) {if (req.method === "GET") {- // GET /api/teams/:teamId/documents/:id/viewsconst session = await getServerSession(req, res, authOptions);if (!session) {return res.status(401).end("Unauthorized");}- // get document id and teamId from query params-const { teamId, id: docId } = req.query as { teamId: string; id: string };const page = parseInt((req.query.page as string) || "1", 10);const limit = parseInt((req.query.limit as string) || "10", 10);const offset = (page - 1) * limit;- console.log("offset", offset);-const userId = (session.user as CustomUser).id;try {@@ -55,12 +207,15 @@ export default async function handle(id: true,ownerId: true,numPages: true,+ type: true,versions: {orderBy: { createdAt: "desc" },select: {versionNumber: true,createdAt: true,numPages: true,+ type: true,+ length: true,},},_count: {@@ -76,8 +231,8 @@ export default async function handle(}const views = await prisma.view.findMany({- skip: offset, // Implementing pagination- take: limit, // Limit the number of views fetched+ skip: offset,+ take: limit,where: {documentId: docId,},@@ -131,53 +286,25 @@ export default async function handle(const limitedViews =team.plan === "free" && offset >= LIMITS.views ? [] : views;- const durationsPromises = limitedViews?.map((view: { id: string }) => {- return getViewPageDuration({- documentId: docId,- viewId: view.id,- since: 0,+ let viewsWithDuration;+ if (document.type === "video") {+ const videoEvents = await getVideoEventsByDocument({+ document_id: docId,});- });-- const durations = await Promise.all(durationsPromises);-- // Sum up durations for each view- const summedDurations = durations.map((duration) => {- return duration.data.reduce(- (totalDuration: number, data: { sum_duration: number }) =>- totalDuration + data.sum_duration,- 0,+ viewsWithDuration = await getVideoViews(+ limitedViews,+ document,+ videoEvents,);- });+ } else {+ viewsWithDuration = await getDocumentViews(limitedViews, document);+ }- // Construct the response combining views and their respective durations- const viewsWithDuration = limitedViews?.map(- (view: any, index: number) => {- // find the relevant document version for the view- const relevantDocumentVersion = document.versions.find(- (version) => version.createdAt <= view.viewedAt,- );-- // get the number of pages for the document version or the document- const numPages =- relevantDocumentVersion?.numPages || document.numPages || 0;-- // calculate the completion rate- const completionRate = numPages- ? (durations[index].data.length / numPages) * 100- : 0;-- return {- ...view,- internal: users.some((user) => user.email === view.viewerEmail), // set internal to true if view.viewerEmail is in the users list- duration: durations[index],- totalDuration: summedDurations[index],- completionRate: completionRate.toFixed(),- versionNumber: relevantDocumentVersion?.versionNumber || 0,- versionNumPages: numPages,- };- },- );+ // Add internal flag to all views+ viewsWithDuration = viewsWithDuration.map((view) => ({+ ...view,+ internal: users.some((user) => user.email === view.viewerEmail),+ }));return res.status(200).json({viewsWithDuration,@@ -192,7 +319,6 @@ export default async function handle(errorhandler(error, res);}} else {- // We only allow GET requestsres.setHeader("Allow", ["GET"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 7732b6bd..20d3f18d 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -7,6 +7,7 @@ import { useTeam } from "@/context/team-context";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import DocumentHeader from "@/components/documents/document-header";import { StatsComponent } from "@/components/documents/stats";+import VideoAnalytics from "@/components/documents/video-analytics";import AppLayout from "@/components/layouts/app";import LinkSheet from "@/components/links/link-sheet";import LinksTable from "@/components/links/links-table";@@ -69,26 +70,22 @@ export default function DocumentPage() {actions={[<AddLinkButton key={"create-link"} />]}/>- {/* <NavMenu- navigation={[- {- label: "Overview",- href: `/documents/${prismaDocument.id}`,- segment: `${prismaDocument.id}`,- },- {- label: "Settings",- href: `/documents/${prismaDocument.id}/settings`,- segment: "settings",- },- ]}- /> */}-- {/* Stats */}- <StatsComponent- documentId={prismaDocument.id}- numPages={primaryVersion.numPages!}- />+ {/* Document Analytics */}+ {primaryVersion.type !== "video" && (+ <StatsComponent+ documentId={prismaDocument.id}+ numPages={primaryVersion.numPages!}+ />+ )}++ {/* Video Analytics */}+ {primaryVersion.type === "video" && (+ <VideoAnalytics+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ teamId={teamInfo?.currentTeam?.id!}+ />+ )}{/* Links */}<LinksTable@@ -98,7 +95,7 @@ export default function DocumentPage() {/>{/* Visitors */}- <VisitorsTable />+ <VisitorsTable isVideo={primaryVersion.type === "video"} /><LinkSheetisOpen={isLinkSheetOpen}