Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Dashboard analytics
Richie McIlroy9daf487471bb
diff --git a/apps/desktop/src-tauri/src/devices.rs b/apps/desktop/src-tauri/src/devices.rsdeleted file mode 100644index 527de7261..000000000--- a/apps/desktop/src-tauri/src/devices.rs+++ /dev/null@@ -1,106 +0,0 @@-use serde::{Serialize, Deserialize};--use crate::utils::run_command;-use crate::utils::ffmpeg_path_as_str;--#[derive(Debug, Serialize, Deserialize)]-pub struct DeviceList {- video_devices: Vec<String>,- audio_devices: Vec<String>,-}--#[tauri::command]-pub fn list_devices() -> Result<DeviceList, String> {- let os_type = std::env::consts::OS;- let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;-- println!("OS: {}", os_type);- println!("FFmpeg binary path: {}", ffmpeg_binary_path_str);-- match os_type {- "macos" => {- let (output, stderr) = run_command(&ffmpeg_binary_path_str, vec!["-f", "avfoundation", "-list_devices", "true", "-i", ""])?;- let raw_output = if !stderr.trim().is_empty() { stderr } else { output };- let (video_devices, audio_devices) = parse_devices_macos(&raw_output);-- println!("Video devices: {:?}", video_devices);- println!("Audio devices: {:?}", audio_devices);-- Ok(DeviceList { video_devices, audio_devices })- }- "linux" => {- let (raw_output, _) = run_command("v4l2-ctl", vec!["--list-devices"])?;- let video_devices = raw_output.split('\n').map(|s| s.to_string()).collect();-- let (raw_output, _) = run_command("arecord", vec!["-l"])?;- let audio_devices = raw_output.split('\n').map(|s| s.to_string()).collect();- Ok(DeviceList { video_devices, audio_devices })- }- "windows" => {- let (raw_output, _) = run_command(&ffmpeg_binary_path_str, vec!["-f", "dshow", "-list_devices", "true", "-i", ""])?;- let (video_devices, audio_devices) = parse_devices_windows(&raw_output);- Ok(DeviceList { video_devices, audio_devices })- }- _ => Err("Unsupported OS".to_string()),- }-}--fn parse_devices_macos(raw_output: &str) -> (Vec<String>, Vec<String>) {- let lines: Vec<&str> = raw_output.lines().collect();- let video_start_index = lines.iter().position(|&x| x.contains("AVFoundation video devices:")).unwrap_or(0) + 1;- let audio_start_index = lines.iter().position(|&x| x.contains("AVFoundation audio devices:")).unwrap_or(0) + 1;-- let video_devices = lines[video_start_index..audio_start_index-1]- .iter()- .filter_map(|&line| {- if line.contains("]") {- Some(line.split("]").last()?.trim().to_string())- } else {- None- }- })- .collect();-- let audio_devices = lines[audio_start_index..]- .iter()- .filter_map(|&line| {- if line.contains("]") {- Some(line.split("]").last()?.trim().to_string())- } else {- None- }- })- .collect();-- (video_devices, audio_devices)-}--fn parse_devices_windows(raw_output: &str) -> (Vec<String>, Vec<String>) {- let lines: Vec<&str> = raw_output.lines().collect();- let video_start_index = lines.iter().position(|&x| x.contains("DirectShow video devices")).unwrap_or(0) + 1;- let audio_start_index = lines.iter().position(|&x| x.contains("DirectShow audio devices")).unwrap_or(0) + 1;-- let video_devices = lines[video_start_index..audio_start_index-1]- .iter()- .filter_map(|&line| {- if line.contains("]") {- Some(line.split("]").last()?.trim().to_string())- } else {- None- }- })- .collect();-- let audio_devices = lines[audio_start_index..]- .iter()- .filter_map(|&line| {- if line.contains("]") {- Some(line.split("]").last()?.trim().to_string())- } else {- None- }- })- .collect();-- (video_devices, audio_devices)-}diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 296155ff4..2f671d929 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -13,7 +13,6 @@ use tauri_plugin_oauth::start;mod recording;mod upload;-mod devices;mod utils;mod media;@@ -35,12 +34,6 @@ fn main() {eprintln!("Thread panicked: {:?}", info);}));- if which::which("ffmpeg").is_err() {- if let Err(e) = handle_ffmpeg_installation() {- eprintln!("Failed to handle FFmpeg installation: {}", e);- }- }-fn handle_ffmpeg_installation() -> FfmpegResult<()> {if ffmpeg_is_installed() {println!("FFmpeg is already installed! 🎉");@@ -69,6 +62,8 @@ fn main() {Ok(())}+ handle_ffmpeg_installation().expect("Failed to install FFmpeg");+#[command]async fn start_server(window: Window) -> Result<u16, String> {start(move |url| {diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rsindex 6ed132775..d86df7387 100644--- a/apps/desktop/src-tauri/src/media.rs+++ b/apps/desktop/src-tauri/src/media.rs@@ -5,7 +5,6 @@ use byteorder::{ByteOrder, LittleEndian};use std::sync::{Arc, atomic::{AtomicBool, Ordering}};use std::io::{ErrorKind::WouldBlock, Error};use std::time::{Instant, Duration};-use std::fs::File;use std::path::Path;use image::{ImageBuffer, Rgba};@@ -56,6 +55,8 @@ impl MediaRecorder {pub async fn start_media_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, screenshot_file_path: &str, custom_device: Option<&str>) -> Result<(), String> {self.options = Some(options.clone());++ println!("Custom device: {:?}", custom_device);let host = cpal::default_host();let devices = host.devices().expect("Failed to get devices");@@ -126,6 +127,9 @@ impl MediaRecorder {println!("Sample format: {}", sample_format);let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();++ println!("FFmpeg binary path: {}", ffmpeg_binary_path_str);+let audio_file_path_owned = audio_file_path.to_owned();let video_file_path_owned = video_file_path.to_owned();let sample_rate_str = sample_rate.to_string();@@ -421,7 +425,7 @@ impl MediaRecorder {"-r", "30","-thread_queue_size", "4096","-i", "pipe:0",- "-vf", "fps=30",+ "-vf", "fps=30,scale=in_range=full:out_range=limited,eq=saturation=1.15","-c:v", "libx264","-preset", "ultrafast","-pix_fmt", "yuv420p",@@ -454,23 +458,28 @@ impl MediaRecorder {let (child, stdin) = self.start_audio_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_audio_command).await.map_err(|e| e.to_string())?;audio_child = Some(child);audio_stdin = Some(stdin);+ println!("Audio process started");}let (video_child, video_stdin) = self.start_video_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_video_command).await.map_err(|e| e.to_string())?;+ println!("Video process started");if let Some(ffmpeg_audio_stdin) = &self.ffmpeg_audio_stdin {let mut audio_stdin_lock = ffmpeg_audio_stdin.lock().await;*audio_stdin_lock = audio_stdin;drop(audio_stdin_lock);+ println!("Audio stdin set");}if let Some(ffmpeg_video_stdin) = &self.ffmpeg_video_stdin {let mut video_stdin_lock = ffmpeg_video_stdin.lock().await;*video_stdin_lock = Some(video_stdin);drop(video_stdin_lock);+ println!("Video stdin set");}if custom_device != Some("None") {+ println!("Starting audio channel senders...");tokio::spawn(async move {while let Some(bytes) = &audio_channel_receiver.lock().await.as_mut().unwrap().recv().await {if let Some(audio_stdin_arc) = &ffmpeg_audio_stdin{@@ -484,6 +493,7 @@ impl MediaRecorder {});}+ println!("Starting video channel senders...");tokio::spawn(async move {while let Some(bytes) = &video_channel_receiver.lock().await.as_mut().unwrap().recv().await {if let Some(video_stdin_arc) = &ffmpeg_video_stdin {@@ -567,24 +577,36 @@ impl MediaRecorder {&self,ffmpeg_binary_path: &str,audio_ffmpeg_command: &[String],- ) -> Result<((Child, ChildStdin)), Error> {- let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;-- let audio_stdin = audio_process.stdin.take().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "Failed to take audio stdin"))?;-- Ok(((audio_process, audio_stdin)))+ ) -> Result<(Child, ChildStdin), Error> {+ let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| {+ eprintln!("Failed to start audio recording process: {}", e);+ std::io::Error::new(std::io::ErrorKind::Other, e.to_string())+ })?;++ let audio_stdin = audio_process.stdin.take().ok_or_else(|| {+ eprintln!("Failed to take audio stdin");+ std::io::Error::new(std::io::ErrorKind::Other, "Failed to take audio stdin")+ })?;++ Ok((audio_process, audio_stdin))}async fn start_video_ffmpeg_processes(&self,ffmpeg_binary_path: &str,video_ffmpeg_command: &[String],- ) -> Result<((Child, ChildStdin)), Error> {- let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command).await.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;-- let video_stdin = video_process.stdin.take().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin"))?;-- Ok(((video_process, video_stdin)))+ ) -> Result<(Child, ChildStdin), Error> {+ let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command).await.map_err(|e| {+ eprintln!("Failed to start video recording process: {}", e);+ std::io::Error::new(std::io::ErrorKind::Other, e.to_string())+ })?;++ let video_stdin = video_process.stdin.take().ok_or_else(|| {+ eprintln!("Failed to take video stdin");+ std::io::Error::new(std::io::ErrorKind::Other, "Failed to take video stdin")+ })?;++ Ok((video_process, video_stdin))}}diff --git a/apps/web/app/api/desktop/video/create/route.ts b/apps/web/app/api/desktop/video/create/route.tsindex 7930e756f..9f80a43dd 100644--- a/apps/web/app/api/desktop/video/create/route.ts+++ b/apps/web/app/api/desktop/video/create/route.ts@@ -74,14 +74,38 @@ export async function GET(req: NextRequest) {}const id = nanoId();+ const date = new Date();+ const formattedDate = `${date.getDate()} ${date.toLocaleString("default", {+ month: "long",+ })} ${date.getFullYear()}`;await db.insert(videos).values({id: id,+ name: `My Cap Recording - ${formattedDate}`,ownerId: user.userId,awsRegion: awsRegion,awsBucket: awsBucket,});+ if (process.env.NEXT_PUBLIC_IS_CAP && process.env.NODE_ENV === "production") {+ const dubOptions = {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.DUB_API_KEY}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ url: process.env.NEXT_PUBLIC_URL + "/s/" + id,+ key: id,+ }),+ };++ await fetch("https://api.dub.co/links?projectSlug=cap", dubOptions)+ .then((response) => response.json())+ .then((response) => console.log(response))+ .catch((err) => console.error(err));+ }+return new Response(JSON.stringify({id: id,diff --git a/apps/web/app/api/video/analytics/route.ts b/apps/web/app/api/video/analytics/route.tsnew file mode 100644index 000000000..dbd05f724--- /dev/null+++ b/apps/web/app/api/video/analytics/route.ts@@ -0,0 +1,44 @@+import { NextRequest } from "next/server";++export async function GET(request: NextRequest) {+ const { searchParams } = request.nextUrl;+ const videoId = searchParams.get("videoId");++ if (!videoId) {+ return new Response(JSON.stringify({ error: true }), {+ status: 401,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ const dubOptions = {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.DUB_API_KEY}`,+ "Content-Type": "application/json",+ },+ };++ const analytics = await fetch(+ `https://api.dub.co/analytics/clicks?projectSlug=cap&domain=cap.link&key=${videoId}`,+ dubOptions+ ).then((response) => response.json());++ if (typeof analytics !== "number") {+ return new Response(JSON.stringify({ error: true }), {+ status: 401,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ return new Response(JSON.stringify({ count: analytics }), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ });+}diff --git a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsxindex 0228fa724..d11a50be7 100644--- a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx+++ b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx@@ -116,7 +116,7 @@ export const AdminNavItems = () => {href={item.href}className={classNames(pathname == item.href- ? "bg-gradient-to-l from-tertiary-3 to-tertiary ring-4 ring-tertiary-2"+ ? "bg-gray-200": "opacity-75 hover:opacity-100",navItemClass)}diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsxindex 813dee3bb..6436262db 100644--- a/apps/web/app/dashboard/caps/Caps.tsx+++ b/apps/web/app/dashboard/caps/Caps.tsx@@ -1,13 +1,46 @@"use client";import { Button } from "@cap/ui";-import { videos } from "@cap/database/schema";import moment from "moment";import { VideoThumbnail } from "@/components/VideoThumbnail";import { useRouter } from "next/navigation";import toast from "react-hot-toast";+import { EyeIcon, LinkIcon, MessageSquareIcon, SmileIcon } from "lucide-react";+import { useEffect, useState } from "react";-export const Caps = ({ data }: { data: (typeof videos.$inferSelect)[] }) => {+type videoData = {+ id: string;+ ownerId: string;+ name: string;+ createdAt: Date;+ totalComments: number;+ totalReactions: number;+}[];++export const Caps = ({ data }: { data: videoData }) => {const { push } = useRouter();+ const [analytics, setAnalytics] = useState<Record<string, number>>({});++ useEffect(() => {+ const fetchAnalytics = async () => {+ const analyticsData: Record<string, number> = {};++ for (const video of data) {+ const response = await fetch(+ `/api/video/analytics?videoId=${video.id}`+ );+ const data = await response.json();++ if (!data.count) {+ analyticsData[video.id] = 0;+ } else {+ analyticsData[video.id] = data.count;+ }+ }+ setAnalytics(analyticsData);+ };++ fetchAnalytics();+ }, [data]);return (<div className="py-12">@@ -42,58 +75,77 @@ export const Caps = ({ data }: { data: (typeof videos.$inferSelect)[] }) => {) : (<><div className="mb-8">- <h1 className="text-2xl font-semibold mb-1">My Caps</h1>- <p>These are all of your videos created with Cap.</p>+ <h1 className="text-3xl font-semibold mb-1">My Caps</h1></div><div className="grid grid-cols-2 md:grid-cols-4 gap-6">{data.map((cap, index) => {+ const videoAnalytics = analytics[cap.id];+return (<divkey={index}- className="rounded-xl border border-filler overflow-hidden"+ className="rounded-xl border border-filler overflow-hidden relative">+ <button+ type="button"+ className="cursor-pointer border border-gray-300 absolute top-2 right-2 z-20 bg-white hover:bg-gray-300 w-6 h-6 m-0 p-0 rounded-full flex items-center justify-center transition-all"+ onClick={() => {+ if (+ process.env.NEXT_PUBLIC_IS_CAP &&+ process.env.NEXT_ENV === "production"+ ) {+ navigator.clipboard.writeText(+ `https://cap.link/${cap.id}`+ );+ } else {+ navigator.clipboard.writeText(+ `${process.env.NEXT_PUBLIC_URL}/s/${cap.id}`+ );+ }+ toast.success("Link copied to clipboard!");+ }}+ >+ <LinkIcon className="w-3 h-3" />+ </button><a- className="group"+ className="group block"href={- process.env.NEXT_PUBLIC_IS_CAP+ process.env.NEXT_PUBLIC_IS_CAP &&+ process.env.NEXT_ENV === "production"? `https://cap.link/${cap.id}`: `${process.env.NEXT_PUBLIC_URL}/s/${cap.id}`}>- <div>- <VideoThumbnail- userId={cap.ownerId}- videoId={cap.id}- alt={`${cap.name} Thumbnail`}- />- </div>+ <VideoThumbnail+ userId={cap.ownerId}+ videoId={cap.id}+ alt={`${cap.name} Thumbnail`}+ /></a><div className="p-4"><p className="font-medium">{cap.name}</p><p className="text-sm text-gray-400">{moment(cap.createdAt).fromNow()}</p>- <div className="mt-3">- <input- className="text-sm cursor-pointer bg-white p-2 w-full rounded-lg flex items-center justify-center border hover:border-primary-3 transition-all"- onClick={(event) => {- if (process.env.NEXT_PUBLIC_IS_CAP) {- navigator.clipboard.writeText(- `https://cap.link/${cap.id}`- );- } else {- navigator.clipboard.writeText(- `${process.env.NEXT_PUBLIC_URL}/s/${cap.id}`- );- }- toast.success("Link copied to clipboard!");- }}- value={- process.env.NEXT_PUBLIC_IS_CAP- ? `https://cap.link/${cap.id}`- : `${process.env.NEXT_PUBLIC_URL}/s/${cap.id}`- }- ></input>+ <div className="flex items-center space-x-3 mt-2 text-sm text-gray-600">+ <div className="flex items-center">+ <EyeIcon className="w-4 h-4 mr-1" />+ <span className="text-gray-600">+ {videoAnalytics ?? "-"}+ </span>+ </div>+ <div className="flex items-center">+ <MessageSquareIcon className="w-4 h-4 mr-1" />+ <span className="text-gray-600">+ {cap.totalComments}+ </span>+ </div>+ <div className="flex items-center">+ <SmileIcon className="w-4 h-4 mr-1" />+ <span className="text-gray-600">+ {cap.totalReactions}+ </span>+ </div></div></div></div>diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsxindex 1db8440c5..3a59265ed 100644--- a/apps/web/app/dashboard/caps/page.tsx+++ b/apps/web/app/dashboard/caps/page.tsx@@ -1,7 +1,7 @@import { Caps } from "./Caps";import { db } from "@cap/database";-import { videos } from "@cap/database/schema";-import { desc, eq } from "drizzle-orm";+import { comments, videos } from "@cap/database/schema";+import { desc, eq, sql } from "drizzle-orm";import { getCurrentUser } from "@cap/database/auth/session";export const revalidate = 0;@@ -11,10 +11,19 @@ export default async function CapsPage() {const userId = user?.userId as string;const videoData = await db- .select()+ .select({+ id: videos.id,+ ownerId: videos.ownerId,+ name: videos.name,+ createdAt: videos.createdAt,+ totalComments: sql<number>`COUNT(CASE WHEN ${comments.type} = 'text' THEN 1 END)`,+ totalReactions: sql<number>`COUNT(CASE WHEN ${comments.type} = 'emoji' THEN 1 END)`,+ }).from(videos)- .orderBy(desc(videos.createdAt))- .where(eq(videos.ownerId, userId));+ .leftJoin(comments, eq(videos.id, comments.videoId))+ .where(eq(videos.ownerId, userId))+ .groupBy(videos.id, videos.ownerId, videos.name, videos.createdAt)+ .orderBy(desc(videos.createdAt));return <Caps data={videoData} />;}diff --git a/apps/web/components/VideoThumbnail.tsx b/apps/web/components/VideoThumbnail.tsxindex 0cc1b6784..03d8756a4 100644--- a/apps/web/components/VideoThumbnail.tsx+++ b/apps/web/components/VideoThumbnail.tsx@@ -1,13 +1,23 @@+import { Logo, LogoBadge, LogoSpinner } from "@cap/ui";import Image from "next/image";import { useEffect, useState } from "react";+import { classNames } from "../utils/helpers";-// Define your props interfaceinterface VideoThumbnailProps {userId: string;videoId: string;alt: string;}+function generateRandomGrayScaleColor() {+ const minGrayScaleValue = 190;+ const maxGrayScaleValue = 235;+ const grayScaleValue = Math.floor(+ Math.random() * (maxGrayScaleValue - minGrayScaleValue) + minGrayScaleValue+ );+ return `rgb(${grayScaleValue}, ${grayScaleValue}, ${grayScaleValue})`;+}+export const VideoThumbnail = ({userId,videoId,@@ -15,8 +25,8 @@ export const VideoThumbnail = ({}: VideoThumbnailProps) => {const [imageUrls, setImageUrls] = useState({ screen: "" });const [loading, setLoading] = useState(true);+ const [failed, setFailed] = useState(false);- // Fetch the pre-signed URLs on component mountuseEffect(() => {const fetchPreSignedUrls = async () => {try {@@ -32,18 +42,29 @@ export const VideoThumbnail = ({} catch (error) {console.error("Error fetching pre-signed URLs:", error);}- setLoading(false);};fetchPreSignedUrls();}, [userId, videoId]);+ const randomGradient = `linear-gradient(to right, ${generateRandomGrayScaleColor()}, ${generateRandomGrayScaleColor()})`;+return (<div- className={`aspect-video relative overflow-hidden rounded-lg ${- loading ? "bg-gray-200" : "bg-black"- }`}+ className={`aspect-video relative overflow-hidden rounded-tr-lg rounded-tl-lg bg-black`}>+ <div className="absolute top-0 left-0 flex items-center justify-center w-full h-full z-10">+ {failed ? (+ <div+ className="w-full h-full"+ style={{ backgroundImage: randomGradient }}+ ></div>+ ) : (+ loading === true && (+ <LogoSpinner className="w-10 h-auto animate-spin" />+ )+ )}+ </div>{imageUrls.screen && (<Imagesrc={imageUrls.screen}@@ -51,7 +72,11 @@ export const VideoThumbnail = ({layout="fill"objectFit="cover"className="group-hover:scale-[1.02] transition-all w-full h-full"- onLoadingComplete={() => setLoading(false)}+ onLoad={() => setLoading(false)}+ onError={() => {+ setFailed(true);+ setLoading(false);+ }}/>)}<div className="bg-black opacity-0 z-10 absolute top-0 left-0 w-full h-full group-hover:opacity-50 transition-all"></div>diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.tsindex c42fc5fe8..426ec2449 100644--- a/packages/database/auth/auth-options.ts+++ b/packages/database/auth/auth-options.ts@@ -54,9 +54,6 @@ export const authOptions: NextAuthOptions = {return session;},- async redirect({ url, baseUrl }) {- return baseUrl;- },async jwt({ token, user }) {const [dbUser] = await db.select()