Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip (#798)

Oscar Beaumontfe6484e4b75e
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2738e204f..040308cf7 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1039,7 +1039,14 @@ async fn upload_exported_video(
}
};
- create_or_get_video(&app, false, video_id, Some(meta.pretty_name.clone())).await
+ create_or_get_video(
+ &app,
+ false,
+ video_id,
+ Some(meta.pretty_name.clone()),
+ Some(duration.to_string()),
+ )
+ .await
}
.await?;
@@ -1051,6 +1058,7 @@ async fn upload_exported_video(
output_path,
Some(s3_config),
Some(meta.project_path.join("screenshots/display.jpg")),
+ Some(duration.to_string()),
)
.await
{
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index caddf5501..2f111f49c 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -10,7 +10,8 @@ use crate::{
open_external_link,
presets::PresetsStore,
upload::{
- create_or_get_video, prepare_screenshot_upload, upload_video, InstantMultipartUpload,
+ build_video_meta, create_or_get_video, prepare_screenshot_upload, upload_video,
+ InstantMultipartUpload,
},
web_api::ManagerExt,
windows::{CapWindowId, ShowCapWindow},
@@ -272,6 +273,7 @@ pub async fn start_recording(
"{target_name} {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
)),
+ None,
)
.await
{
@@ -723,6 +725,7 @@ async fn handle_recording_finish(
}
}
} else {
+ let meta = build_video_meta(&output_path).ok();
// The upload_video function handles screenshot upload, so we can pass it along
match upload_video(
&app,
@@ -730,6 +733,7 @@ async fn handle_recording_finish(
output_path,
Some(video_upload_info.config.clone()),
Some(display_screenshot.clone()),
+ meta.map(|v| v.duration),
)
.await
{
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 07d654abd..61ab74cdd 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -23,11 +23,14 @@ use tokio::sync::mpsc;
use tokio::sync::RwLock;
use tokio::task;
use tokio::time::sleep;
-use tracing::{info, trace, warn};
+use tracing::{error, info, trace, warn};
use crate::web_api::{self, ManagerExt};
-use crate::{notifications, App, MutableState, RecordingStopped, UploadProgress, VideoUploadInfo};
+use crate::{
+ get_video_metadata, notifications, App, MutableState, RecordingStopped, UploadProgress,
+ VideoUploadInfo,
+};
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -93,16 +96,24 @@ struct S3UploadBody {
subpath: String,
}
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct S3VideoMeta {
+ pub duration: String,
+ pub bandwidth: String,
+ pub resolution: String,
+ pub video_codec: String,
+ pub audio_codec: String,
+ pub framerate: String,
+}
+
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct S3VideoUploadBody {
#[serde(flatten)]
base: S3UploadBody,
- duration: String,
- resolution: String,
- framerate: String,
- bandwidth: String,
- video_codec: String,
+ #[serde(flatten)]
+ meta: S3VideoMeta,
}
#[derive(serde::Serialize)]
@@ -145,22 +156,23 @@ pub async fn upload_video(
file_path: PathBuf,
existing_config: Option<S3UploadMeta>,
screenshot_path: Option<PathBuf>,
+ duration: Option<String>,
) -> Result<UploadedVideo, String> {
println!("Uploading video {video_id}...");
let client = reqwest::Client::new();
let s3_config = match existing_config {
Some(config) => config,
- None => create_or_get_video(app, false, Some(video_id.clone()), None).await?,
+ None => create_or_get_video(app, false, Some(video_id.clone()), None, duration).await?,
};
- let body = build_video_upload_body(
- &file_path,
- S3UploadBody {
+ let body = S3VideoUploadBody {
+ base: S3UploadBody {
video_id: video_id.clone(),
subpath: "result.mp4".to_string(),
},
- )?;
+ meta: build_video_meta(&file_path)?,
+ };
let presigned_put = presigned_s3_put(app, body).await?;
@@ -265,7 +277,7 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploade
.to_string();
let client = reqwest::Client::new();
- let s3_config = create_or_get_video(app, true, None, None).await?;
+ let s3_config = create_or_get_video(app, true, None, None, None).await?;
let body = S3ImageUploadBody {
base: S3UploadBody {
@@ -317,6 +329,7 @@ pub async fn create_or_get_video(
is_screenshot: bool,
video_id: Option<String>,
name: Option<String>,
+ duration: Option<String>,
) -> Result<S3UploadMeta, String> {
let mut s3_config_url = if let Some(id) = video_id {
format!("/api/desktop/video/create?recordingMode=desktopMP4&videoId={id}")
@@ -330,6 +343,10 @@ pub async fn create_or_get_video(
s3_config_url.push_str(&format!("&name={}", name));
}
+ if let Some(duration) = duration {
+ s3_config_url.push_str(&format!("&duration={}", duration));
+ }
+
let response = app
.authed_api_request(s3_config_url, |client, url| client.get(url))
.await
@@ -388,23 +405,27 @@ async fn presigned_s3_put(app: &AppHandle, body: impl Serialize) -> Result<Strin
Ok(presigned_put_data.url)
}
-fn build_video_upload_body(
- path: &PathBuf,
- base: S3UploadBody,
-) -> Result<S3VideoUploadBody, String> {
+pub fn build_video_meta(path: &PathBuf) -> Result<S3VideoMeta, String> {
let input =
ffmpeg::format::input(path).map_err(|e| format!("Failed to read input file: {e}"))?;
- let stream = input
+ let video_stream = input
.streams()
.best(ffmpeg::media::Type::Video)
.ok_or_else(|| "Failed to find appropriate video stream in file".to_string())?;
+ let audio_stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .ok_or_else(|| "Failed to find appropriate audio stream in file".to_string())?;
let duration_millis = input.duration() as f64 / 1000.;
- let codec = ffmpeg::codec::context::Context::from_parameters(stream.parameters())
+ let video_codec = ffmpeg::codec::context::Context::from_parameters(video_stream.parameters())
.map_err(|e| format!("Unable to read video codec information: {e}"))?;
- let codec_name = codec.id();
- let video = codec.decoder().video().unwrap();
+ let audio_codec = ffmpeg::codec::context::Context::from_parameters(audio_stream.parameters())
+ .map_err(|e| format!("Unable to read audio codec information: {e}"))?;
+ let video_codec_name = video_codec.id();
+ let audio_codec_name = audio_codec.id();
+ let video = video_codec.decoder().video().unwrap();
let width = video.width();
let height = video.height();
let frame_rate = video
@@ -413,13 +434,17 @@ fn build_video_upload_body(
.unwrap_or("-".into());
let bit_rate = video.bit_rate();
- Ok(S3VideoUploadBody {
- base,
+ Ok(S3VideoMeta {
duration: duration_millis.to_string(),
resolution: format!("{}x{}", width, height),
framerate: frame_rate,
bandwidth: bit_rate.to_string(),
- video_codec: format!("{codec_name:?}").replace("Id::", "").to_lowercase(),
+ video_codec: format!("{video_codec_name:?}")
+ .replace("Id::", "")
+ .to_lowercase(),
+ audio_codec: format!("{audio_codec_name:?}")
+ .replace("Id::", "")
+ .to_lowercase(),
})
}
@@ -1013,6 +1038,10 @@ impl InstantMultipartUpload {
println!("File size on disk: {} bytes", file_final_size);
println!("Proceeding with multipart upload completion...");
+ let metadata = build_video_meta(file_path)
+ .map_err(|e| error!("Failed to get video metadata: {e}"))
+ .ok();
+
let complete_response = match app
.authed_api_request("/api/upload/multipart/complete", |c, url| {
c.post(url)
@@ -1020,7 +1049,13 @@ impl InstantMultipartUpload {
.json(&serde_json::json!({
"videoId": video_id,
"uploadId": upload_id,
- "parts": uploaded_parts
+ "parts": uploaded_parts,
+ "duration": metadata.as_ref().map(|m| m.duration.clone()),
+ "bandwidth": metadata.as_ref().map(|m| m.bandwidth.clone()),
+ "resolution": metadata.as_ref().map(|m| m.resolution.clone()),
+ "videoCodec": metadata.as_ref().map(|m| m.video_codec.clone()),
+ "audioCodec": metadata.as_ref().map(|m| m.audio_codec.clone()),
+ "framerate": metadata.as_ref().map(|m| m.framerate.clone()),
}))
})
.await
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index e8ab06ab9..6b97863af 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -80,27 +80,32 @@ app.get(
}
}
- const idToUse = videoId !== undefined ? videoId : nanoId();
+ const idToUse = nanoId();
- const videoData = {
- id: idToUse,
- name:
- name ??
- `Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`,
- ownerId: user.id,
- awsRegion: "auto",
- awsBucket: bucket.name,
- source:
- recordingMode === "hls"
- ? { type: "local" as const }
- : recordingMode === "desktopMP4"
- ? { type: "desktopMP4" as const }
- : undefined,
- isScreenshot,
- bucket: customBucket?.id,
- };
+ const videoName =
+ name ??
+ `Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`;
- await db().insert(videos).values(videoData);
+ await db()
+ .insert(videos)
+ .values({
+ id: idToUse,
+ name: videoName,
+ ownerId: user.id,
+ awsRegion: "auto",
+ awsBucket: bucket.name,
+ source:
+ recordingMode === "hls"
+ ? { type: "local" as const }
+ : recordingMode === "desktopMP4"
+ ? { type: "desktopMP4" as const }
+ : undefined,
+ isScreenshot,
+ bucket: customBucket?.id,
+ metadata: {
+ duration,
+ },
+ });
if (buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production")
await dub().links.create({
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts
index 8478fb77f..98e17ac44 100644
--- a/apps/web/app/api/upload/[...route]/multipart.ts
+++ b/apps/web/app/api/upload/[...route]/multipart.ts
@@ -1,13 +1,14 @@
import { Hono } from "hono";
import { createBucketProvider } from "@/utils/s3";
import { db } from "@cap/database";
-import { s3Buckets } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { serverEnv } from "@cap/env";
import { withAuth } from "@/app/api/utils";
import { parseVideoIdOrFileKey } from "../utils";
+import { VideoMetadata } from "@cap/database/types";
export const app = new Hono().use(withAuth);
@@ -161,14 +162,18 @@ app.post(
size: z.number(),
})
),
+ duration: z.string().optional(),
+ bandwidth: z.string().optional(),
+ resolution: z.string().optional(),
+ videoCodec: z.string().optional(),
+ audioCodec: z.string().optional(),
+ framerate: z.string().optional(),
})
.and(
z.union([
- z.object({
- // deprecated
- fileKey: z.string(),
- }),
z.object({ videoId: z.string() }),
+ // deprecated
+ z.object({ fileKey: z.string() }),
])
)
),
@@ -270,15 +275,32 @@ app.post(
console.error(`Warning: Unable to verify object: ${headError}`);
}
- const videoId = fileKey.split("/")[1];
- if (videoId) {
+ const videoMetadata: VideoMetadata = {
+ duration: body.duration,
+ bandwidth: body.bandwidth,
+ resolution: body.resolution,
+ videoCodec: body.videoCodec,
+ audioCodec: body.audioCodec,
+ framerate: body.framerate,
+ };
+
+ if (Object.values(videoMetadata).length > 1 && "videoId" in body)
+ await db()
+ .update(videos)
+ .set({
+ metadata: videoMetadata,
+ })
+ .where(eq(videos.id, body.videoId));
+
+ const videoIdFromFileKey = fileKey.split("/")[1];
+ if (videoIdFromFileKey) {
try {
await fetch(`${serverEnv().WEB_URL}/api/revalidate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ videoId }),
+ body: JSON.stringify({ videoId: videoIdFromFileKey }),
});
console.log(`Revalidation triggered for videoId: ${videoId}`);
} catch (revalidateError) {
diff --git a/apps/web/app/api/upload/[...route]/signed.ts b/apps/web/app/api/upload/[...route]/signed.ts
index 3d23c3c9d..13c95305f 100644
--- a/apps/web/app/api/upload/[...route]/signed.ts
+++ b/apps/web/app/api/upload/[...route]/signed.ts
@@ -4,7 +4,7 @@ import {
CreateInvalidationCommand,
} from "@aws-sdk/client-cloudfront";
import { db } from "@cap/database";
-import { s3Buckets } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { serverEnv } from "@cap/env";
import { Hono } from "hono";
@@ -13,6 +13,7 @@ import { z } from "zod";
import { withAuth } from "../../utils";
import { parseVideoIdOrFileKey } from "../utils";
+import { VideoMetadata } from "@cap/database/types";
export const app = new Hono().use(withAuth);
@@ -27,6 +28,7 @@ app.post(
resolution: z.string().optional(),
videoCodec: z.string().optional(),
audioCodec: z.string().optional(),
+ framerate: z.string().optional(),
method: z.union([z.literal("post"), z.literal("put")]).default("post"),
})
.and(
@@ -45,6 +47,7 @@ app.post(
resolution,
videoCodec,
audioCodec,
+ framerate,
method,
...body
} = c.req.valid("json");
@@ -154,16 +157,33 @@ app.post(
console.log("Presigned URL created successfully");
+ const videoMetadata: VideoMetadata = {
+ duration,
+ bandwidth,
+ resolution,
+ videoCodec,
+ audioCodec,
+ framerate,
+ };
+
+ if (Object.values(videoMetadata).length > 1 && "videoIn" in body)
+ await db()
+ .update(videos)
+ .set({
+ metadata: videoMetadata,
+ })
+ .where(eq(videos.id, body.videoId));
+
// After successful presigned URL creation, trigger revalidation
- const videoId = fileKey.split("/")[1]; // Assuming fileKey format is userId/videoId/...
- if (videoId) {
+ const videoIdFromKey = fileKey.split("/")[1]; // Assuming fileKey format is userId/videoId/...
+ if (videoIdFromKey) {
try {
await fetch(`${serverEnv().WEB_URL}/api/revalidate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ videoId }),
+ body: JSON.stringify({ videoId: videoIdFromKey }),
});
} catch (revalidateError) {
console.error("Failed to revalidate page:", revalidateError);
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index ea60fe87b..9ebe62285 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -18,7 +18,7 @@ export interface VideoMetadata {
/**
* Duration of the video in seconds
*/
- duration?: number;
+ duration?: string | number;
/**
* Resolution of the recording (e.g. 1920x1080)
*/
@@ -55,4 +55,4 @@ export interface SpaceMetadata {
*/
export interface UserMetadata {
[key: string]: any;
-}
\ No newline at end of file
+}