Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Client-side ffmpeg pipe upload handler
Richie McIlroy2f657663fa58
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex f9fa5485d..c2f824db8 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -21,8 +21,7 @@ pub async fn upload_file(let file_key = format!("{}/{}/{}/{}", options.user_id, options.video_id, file_type, file_name);- // Here we assume your server listens on localhost:3000 and the route is `api/upload/new`- let server_url = format!("http://localhost:3000/api/upload/new");+ let server_url = format!("http://localhost:3000/api/upload/signed");// Create the request body for the Next.js handlerlet body = serde_json::json!({diff --git a/apps/web/app/api/upload/new/route.ts b/apps/web/app/api/upload/new/route.tsindex 355ba93e6..ae9b71493 100644--- a/apps/web/app/api/upload/new/route.ts+++ b/apps/web/app/api/upload/new/route.ts@@ -1,60 +1,58 @@-import { S3Client } from "@aws-sdk/client-s3";-import { createPresignedPost, PresignedPost } from "@aws-sdk/s3-presigned-post";-import { NextRequest } from "next/server";--const s3Client = new S3Client({- region: process.env.CAP_AWS_REGION || "",- credentials: {- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",- },-});+import { type NextRequest } from "next/server";+import { getCurrentUser } from "@cap/database/auth/session";+import { uploadToS3 } from "@/utils/video/upload/helpers";export async function POST(request: NextRequest) {- try {- const { userId, fileKey, awsBucket, awsRegion } = await request.json();-- if (!userId || !fileKey || !awsBucket || !awsRegion) {- return new Response(- JSON.stringify({ error: "Missing required fields" }),- {- status: 400,- headers: {- "Content-Type": "application/json",- },- }- );- }-- const Fields = {- "x-amz-meta-userid": userId,- };-- const presignedPostData: PresignedPost = await createPresignedPost(- s3Client,- {- Bucket: awsBucket,- Key: fileKey,- Fields,- Expires: 1800,- }- );-- return new Response(JSON.stringify({ presignedPostData }), {+ const user = await getCurrentUser();+ const awsRegion = process.env.CAP_AWS_REGION;+ const awsBucket = process.env.CAP_AWS_BUCKET;+ const formData = await request.formData();+ const filename = formData.get("filename");+ const videoId = formData.get("videoId");+ const blobData = formData.get("blobData");++ console.log("filename:", filename);++ if (!user || !awsRegion || !awsBucket || !filename || !blobData) {+ console.error("Missing required data in /api/upload/new/route.ts");++ return new Response(JSON.stringify({ error: true }), {+ status: 401,headers: {"Content-Type": "application/json",},});- } catch (error) {- console.error("Error creating presigned URL", error);- return new Response(- JSON.stringify({ error: "Error creating presigned URL" }),- {- status: 500,- headers: {- "Content-Type": "application/json",- },- }- );}++ const fullFilepath = `${user.userId}/${videoId}/${filename}`;++ const upload = await uploadToS3(+ fullFilepath,+ blobData,+ user.userId,+ awsBucket,+ awsRegion+ );++ if (!upload) {+ console.error("Upload failed");++ return new Response(JSON.stringify({ error: true }), {+ status: 500,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log("Upload successful");++ return new Response(+ JSON.stringify({+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ })+ );}diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.tsnew file mode 100644index 000000000..8312bb518--- /dev/null+++ b/apps/web/app/api/upload/signed/route.ts@@ -0,0 +1,64 @@+import { S3Client } from "@aws-sdk/client-s3";+import { createPresignedPost, PresignedPost } from "@aws-sdk/s3-presigned-post";+import { NextRequest } from "next/server";++const s3Client = new S3Client({+ region: process.env.CAP_AWS_REGION || "",+ credentials: {+ accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",+ secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",+ },+});++export async function POST(request: NextRequest) {+ try {+ const { userId, fileKey, awsBucket, awsRegion } = await request.json();++ if (!userId || !fileKey || !awsBucket || !awsRegion) {+ console.error("Missing required fields in /api/upload/signed/route.ts");++ return new Response(+ JSON.stringify({ error: "Missing required fields" }),+ {+ status: 400,+ headers: {+ "Content-Type": "application/json",+ },+ }+ );+ }++ const Fields = {+ "x-amz-meta-userid": userId,+ };++ const presignedPostData: PresignedPost = await createPresignedPost(+ s3Client,+ {+ Bucket: awsBucket,+ Key: fileKey,+ Fields,+ Expires: 1800,+ }+ );++ console.log("Presigned URL created successfully");++ return new Response(JSON.stringify({ presignedPostData }), {+ headers: {+ "Content-Type": "application/json",+ },+ });+ } catch (error) {+ console.error("Error creating presigned URL", error);+ return new Response(+ JSON.stringify({ error: "Error creating presigned URL" }),+ {+ status: 500,+ headers: {+ "Content-Type": "application/json",+ },+ }+ );+ }+}diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsxindex aba3a308a..6f0350bab 100644--- a/apps/web/app/dashboard/caps/Caps.tsx+++ b/apps/web/app/dashboard/caps/Caps.tsx@@ -1,6 +1,7 @@"use client";import { Button } from "@cap/ui";import { videos } from "@cap/database/schema";+import moment from "moment";export const Caps = ({ data }: { data: (typeof videos.$inferSelect)[] }) => {return (@@ -32,13 +33,21 @@ export const Caps = ({ data }: { data: (typeof videos.$inferSelect)[] }) => {<h1 className="text-2xl font-semibold mb-1">My Caps</h1><p>These are all of your videos created with Cap.</p></div>- <div className="grid grid-cols-2 md:grid-cols-3 gap-6">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-6">{data.map((cap, index) => {return (- <div key={index}>+ <div+ key={index}+ className="rounded-xl border border-filler overflow-hidden"+ ><a href={`/share/${cap.id}`}>- <div className="aspect-video bg-gray-100 rounded-lg mb-1"></div>- <p>{cap.name}</p>+ <div className="aspect-video bg-gray-100"></div>+ <div className="p-4">+ <p className="font-medium">{cap.name}</p>+ <p className="text-sm text-gray-400">+ {moment(cap.createdAt).fromNow()}+ </p>+ </div></a></div>);diff --git a/apps/web/app/share/[videoId]/Share.tsx b/apps/web/app/share/[videoId]/Share.tsxindex 134f0ce89..9af7fdf17 100644--- a/apps/web/app/share/[videoId]/Share.tsx+++ b/apps/web/app/share/[videoId]/Share.tsx@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "react";import { ShareHeader } from "./_components/ShareHeader";import { videos } from "@cap/database/schema";import { FFmpeg as FfmpegType } from "@ffmpeg/ffmpeg";+import { concatenateSegments } from "@/utils/video/ffmpeg/helpers";export const Share = ({data,@@ -38,72 +39,25 @@ export const Share = ({}}, [ffmpegLoaded]);- const concatenateSegments = async (- ffmpeg: FfmpegType,- segmentsUrls: string[],- outputFilename: string,- inputFormat: string,- outputFormat: string- ) => {- if (!ffmpegRef.current) {- throw new Error("FFmpeg not loaded");- }-- console.log("concatenateSegments:", segmentsUrls);-- await ffmpegRef.current.load();-- // Feed the video segments to FFmpeg- for (let i = 0; i < segmentsUrls.length; i++) {- console.log("Fetching file...");- const fetchedFile = await fetchFile(segmentsUrls[i]);- ffmpeg.writeFile(`file${i}.${inputFormat}`, fetchedFile);- }-- // Create a file with all the file names- const fileList = "file_list.txt";- const concatList = segmentsUrls- .map((url, index) => `file file${index}.${inputFormat}`)- .join("\n");- ffmpeg.writeFile(fileList, concatList);-- console.log("Concatenating using ffmpeg script...");-- await ffmpeg.exec([- "-f",- "concat",- "-safe",- "0",- "-i",- fileList,- "-r",- `${outputFilename === "video_output.mp4" ? 30 : 60}`,- "-c",- "copy",- outputFilename,- ]);-- // Read the resulting file- const data = ffmpeg.readFile(outputFilename);-- // Convert the data to a Blob- // const videoBlob = new Blob([data.buffer], { type: `video/${outputFormat}` });-- // // Create a URL for the Blob- // const videoUrl = URL.createObjectURL(videoBlob);-- // Return the URL to the MP4 on S3- return data;- };-useEffect(() => {const loadVideos = async () => {setLoading(true);try {+ console.log("urls", urls);++ if (urls.singleVideoUrl) {+ setVideoSrc(urls.singleVideoUrl);+ }++ if (urls.singleScreenUrl) {+ setScreenSrc(urls.singleScreenUrl);+ }+if (urls.videoUrls.length > 0 && ffmpegRef.current) {const concatenatedVideoData = await concatenateSegments(ffmpegRef.current,urls.videoUrls,+ data.id,"video_output.mp4","webm","mp4"@@ -113,14 +67,13 @@ export const Share = ({new Blob([concatenatedVideoData], { type: "video/mp4" })));- } else if (urls.singleVideoUrl) {- setVideoSrc(urls.singleVideoUrl);}if (urls.screenUrls.length > 0 && ffmpegRef.current) {const concatenatedScreenData = await concatenateSegments(ffmpegRef.current,urls.screenUrls,+ data.id,"screen_output.mp4","mkv","mp4"@@ -130,8 +83,6 @@ export const Share = ({new Blob([concatenatedScreenData], { type: "video/mp4" })));- } else if (urls.singleScreenUrl) {- setScreenSrc(urls.singleScreenUrl);}} catch (error) {console.error("Error loading videos", error);diff --git a/apps/web/app/share/[videoId]/page.tsx b/apps/web/app/share/[videoId]/page.tsxindex 2963bcea6..3f6c5cd96 100644--- a/apps/web/app/share/[videoId]/page.tsx+++ b/apps/web/app/share/[videoId]/page.tsx@@ -15,8 +15,6 @@ type Props = {params: { [key: string]: string | string[] | undefined };};-const revalidate = 0;-const s3Client = new S3Client({region: process.env.CAP_AWS_REGION || "",credentials: {diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.tsindex 986303689..5f45fa18a 100644--- a/apps/web/utils/video/ffmpeg/helpers.ts+++ b/apps/web/utils/video/ffmpeg/helpers.ts@@ -1,20 +1,27 @@-import { FFmpeg } from "@ffmpeg/ffmpeg";+import { FFmpeg as FfmpegType } from "@ffmpeg/ffmpeg";import { fetchFile } from "@ffmpeg/util";-import { useRef, useEffect } from "react";export const concatenateSegments = async (+ ffmpeg: FfmpegType,segmentsUrls: string[],+ videoId: string,outputFilename: string,inputFormat: string,outputFormat: string) => {- const ffmpegRef = useRef(new FFmpeg());- const ffmpeg = ffmpegRef.current;+ if (!ffmpeg) {+ throw new Error("FFmpeg not loaded");+ }++ console.log("Running concatenateSegments...");++ console.log("concatenateSegments:", segmentsUrls);await ffmpeg.load();// Feed the video segments to FFmpegfor (let i = 0; i < segmentsUrls.length; i++) {+ console.log("Fetching file...");const fetchedFile = await fetchFile(segmentsUrls[i]);ffmpeg.writeFile(`file${i}.${inputFormat}`, fetchedFile);}@@ -26,7 +33,8 @@ export const concatenateSegments = async (.join("\n");ffmpeg.writeFile(fileList, concatList);- // Run the FFmpeg command to concatenate+ console.log("Concatenating using ffmpeg script...");+await ffmpeg.exec(["-f","concat",@@ -34,19 +42,32 @@ export const concatenateSegments = async ("0","-i",fileList,+ "-r",+ `${outputFilename === "video_output.mp4" ? 30 : 60}`,"-c","copy",outputFilename,]);// Read the resulting file- const data = ffmpeg.readFile(outputFilename);+ const data = await ffmpeg.readFile(outputFilename);// Convert the data to a Blob- // const videoBlob = new Blob([data.buffer], { type: `video/${outputFormat}` });+ const blob = new Blob([data], {+ type: `video/${outputFormat}`,+ });++ console.log("Uploading to S3...");++ const formData = new FormData();+ formData.append("filename", outputFilename);+ formData.append("videoId", videoId);+ formData.append("blobData", blob);- // // Create a URL for the Blob- // const videoUrl = URL.createObjectURL(videoBlob);+ await fetch(`${process.env.NEXT_PUBLIC_URL}/api/upload/new`, {+ method: "POST",+ body: formData,+ });// Return the URL to the MP4 on S3return data;diff --git a/apps/web/utils/video/upload/helpers.ts b/apps/web/utils/video/upload/helpers.tsnew file mode 100644index 000000000..aa7ea27e4--- /dev/null+++ b/apps/web/utils/video/upload/helpers.ts@@ -0,0 +1,45 @@+export async function uploadToS3(+ filename: string,+ blobData: string | Blob,+ userId: string,+ awsBucket: string,+ awsRegion: string+) {+ const response = await fetch(+ `${process.env.NEXT_PUBLIC_URL}/api/upload/signed`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ userId: userId,+ fileKey: filename,+ awsBucket: awsBucket,+ awsRegion: awsRegion,+ }),+ }+ );++ const { presignedPostData } = await response.json();++ const formData = new FormData();+ Object.entries(presignedPostData.fields).forEach(([key, value]) => {+ formData.append(key, value as string);+ });+ // Append the file (blobData) to the formData+ formData.append("file", blobData);++ // Execute the upload using the presigned URL+ const uploadResponse = await fetch(presignedPostData.url, {+ method: "POST",+ body: formData,+ });++ if (!uploadResponse.ok) {+ return false;+ }++ // Optionally return the S3 URL or any other info you need+ return true;+}