Skip to content

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

feat: add user agent to views

Marc Seitz49624432901a
diff --git a/components/visitors/visitor-useragent.tsx b/components/visitors/visitor-useragent.tsx
new file mode 100644
index 00000000..a9d90adb
--- /dev/null
+++ b/components/visitors/visitor-useragent.tsx
@@ -0,0 +1,37 @@
+import ErrorPage from "next/error";
+
+import { useVisitorUserAgent } from "@/lib/swr/use-stats";
+
+import UAIcon from "../user-agent-icon";
+
+export default function VisitorUserAgent({ viewId }: { viewId: string }) {
+ const { userAgent, error } = useVisitorUserAgent(viewId);
+
+ if (error && error.status === 404) {
+ return <ErrorPage statusCode={404} />;
+ }
+
+ if (!userAgent) {
+ return <div>Loading...</div>;
+ }
+
+ const { device, browser, os } = userAgent;
+
+ return (
+ <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">
+ <div className="flex items-center">
+ <div className="flex items-center gap-x-1 px-1">
+ <UAIcon display={device} type="devices" className="size-4" /> {device}
+ ,
+ </div>
+ <div className="flex items-center gap-x-1 px-1">
+ <UAIcon display={browser} type="browsers" className="size-4" />{" "}
+ {browser},
+ </div>
+ <div className="flex items-center gap-x-1 px-1">
+ <UAIcon display={os} type="os" className="size-4" /> {os}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsx
index 1ba99c9b..e1a34e4c 100644
--- a/components/visitors/visitors-table.tsx
+++ b/components/visitors/visitors-table.tsx
@@ -46,6 +46,7 @@ import {
} from "../ui/pagination";
import { VisitorAvatar } from "./visitor-avatar";
import VisitorChart from "./visitor-chart";
+import VisitorUserAgent from "./visitor-useragent";
export default function VisitorsTable({ numPages }: { numPages: number }) {
const [currentPage, setCurrentPage] = useState<number>(1);
@@ -198,6 +199,9 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {
<>
<TableRow className="hover:bg-transparent">
<TableCell colSpan={5}>
+ {!isFreePlan ? (
+ <VisitorUserAgent viewId={view.id} />
+ ) : null}
<VisitorChart
documentId={view.documentId!}
viewId={view.id}
diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.ts
index 91f9fccf..abb6c673 100644
--- a/lib/swr/use-stats.ts
+++ b/lib/swr/use-stats.ts
@@ -3,6 +3,7 @@ import { useRouter } from "next/router";
import { useTeam } from "@/context/team-context";
import { View } from "@prisma/client";
import useSWR from "swr";
+import useSWRImmutable from "swr/immutable";
import { fetcher } from "@/lib/utils";
@@ -80,3 +81,31 @@ export function useVisitorStats(viewId: string) {
error,
};
}
+
+export function useVisitorUserAgent(viewId: string) {
+ const router = useRouter();
+ const teamInfo = useTeam();
+
+ const { id: documentId } = router.query as {
+ id: string;
+ };
+
+ const { data: userAgent, error } = useSWRImmutable<{
+ country: string;
+ city: string;
+ os: string;
+ browser: string;
+ device: string;
+ }>(
+ documentId &&
+ viewId &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/documents/${documentId}/views/${viewId}/user-agent`,
+ fetcher,
+ );
+
+ return {
+ userAgent,
+ loading: !error && !userAgent,
+ error,
+ };
+}
diff --git a/lib/tinybird/README.md b/lib/tinybird/README.md
new file mode 100644
index 00000000..c0a305d7
--- /dev/null
+++ b/lib/tinybird/README.md
@@ -0,0 +1,7 @@
+## Add new pipes to Tinybird
+
+So you added a new pipe to Tinybird and want to push that to the server.
+
+```sh
+tb push lib/tinybird/endpoints/<PIPENAME>.pipe
+```
diff --git a/lib/tinybird/endpoints/get_useragent_per_view.pipe b/lib/tinybird/endpoints/get_useragent_per_view.pipe
new file mode 100644
index 00000000..ffd1e8fe
--- /dev/null
+++ b/lib/tinybird/endpoints/get_useragent_per_view.pipe
@@ -0,0 +1,20 @@
+VERSION 1
+
+NODE endpoint
+SQL >
+ %
+ SELECT
+ country,
+ city,
+ browser,
+ os,
+ device
+ FROM
+ page_views__v3
+ WHERE
+ documentId = {{ String(documentId, required=True) }}
+ AND viewId = {{ String(viewId, required=True) }}
+ AND time >= {{ Int64(since, required=True) }}
+ ORDER BY
+ viewId, time ASC
+ LIMIT 1
diff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index 135a39ec..41fa5eae 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -31,6 +31,22 @@ export const getViewPageDuration = tb.buildPipe({
}),
});
+export const getViewUserAgent = tb.buildPipe({
+ pipe: "get_useragent_per_view__v2",
+ parameters: z.object({
+ documentId: z.string(),
+ viewId: z.string(),
+ since: z.number(),
+ }),
+ data: z.object({
+ country: z.string(),
+ city: z.string(),
+ browser: z.string(),
+ os: z.string(),
+ device: z.string(),
+ }),
+});
+
export const getTotalDataroomDuration = tb.buildPipe({
pipe: "get_total_dataroom_duration__v1",
parameters: z.object({
diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts
new file mode 100644
index 00000000..f61513af
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts
@@ -0,0 +1,72 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { getViewUserAgent } from "@/lib/tinybird";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/documents/:id/views/:viewId/user-agent
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const {
+ teamId,
+ id: docId,
+ viewId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ viewId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userAgent = await getViewUserAgent({
+ documentId: docId,
+ viewId: viewId,
+ since: 0,
+ });
+
+ const userAgentData = userAgent.data[0];
+ // don't send location to the client
+ const { country, city, ...remainingResponse } = userAgentData;
+
+ return res.status(200).json(remainingResponse);
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}