Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: add media validation and update video component (#1010)

tribhuwanfd098e9c88f8
diff --git a/pipes/identify-speakers/bun.lockb b/pipes/identify-speakers/bun.lockb
index ab47763d5..b9e52cc76 100755
Binary files a/pipes/identify-speakers/bun.lockb and b/pipes/identify-speakers/bun.lockb differ
diff --git a/pipes/identify-speakers/src/components/video.tsx b/pipes/identify-speakers/src/components/video.tsx
index 2d71a82e3..87bbacba5 100644
--- a/pipes/identify-speakers/src/components/video.tsx
+++ b/pipes/identify-speakers/src/components/video.tsx
@@ -33,47 +33,50 @@ export const VideoComponent = memo(function VideoComponent({
</p>
);
- const getMimeType = (path: string): string => {
- const ext = path.split(".").pop()?.toLowerCase();
- switch (ext) {
- case "mp4":
- return "video/mp4";
- case "webm":
- return "video/webm";
- case "ogg":
- return "video/ogg";
- case "mp3":
- return "audio/mpeg";
- case "wav":
- return "audio/wav";
- default:
- return isAudio ? "audio/mpeg" : "video/mp4";
+ const validateMedia = async(path: string): Promise<string> => {
+ try {
+ const response = await fetch(`http://localhost:3030/experimental/validate/media?file_path=${encodeURIComponent(path)}`);
+ const result = await response.json();
+ return result.status;
+ } catch (error) {
+ console.error("Failed to validate media:", error);
+ return "Failed to validate media";
}
};
useEffect(() => {
async function loadMedia() {
try {
- console.log("Loading media:", filePath);
const sanitizedPath = sanitizeFilePath(filePath);
console.log("Sanitized path:", sanitizedPath);
+
if (!sanitizedPath) {
throw new Error("Invalid file path");
}
- setIsAudio(
- sanitizedPath.toLowerCase().includes("input") ||
- sanitizedPath.toLowerCase().includes("output")
- );
+ const validationStatus = await validateMedia(sanitizedPath);
+ console.log("Media file:", validationStatus)
- const { data, mimeType } = await getMediaFile(sanitizedPath);
- const binaryData = atob(data);
- const bytes = new Uint8Array(binaryData.length);
- for (let i = 0; i < binaryData.length; i++) {
- bytes[i] = binaryData.charCodeAt(i);
+ if (validationStatus === "valid media file") {
+ setIsAudio(
+ sanitizedPath.toLowerCase().includes("input") ||
+ sanitizedPath.toLowerCase().includes("output")
+ );
+ const { data, mimeType } = await getMediaFile(sanitizedPath);
+ const binaryData = atob(data);
+ const bytes = new Uint8Array(binaryData.length);
+ for (let i = 0; i < binaryData.length; i++) {
+ bytes[i] = binaryData.charCodeAt(i);
+ }
+ const blob = new Blob([bytes], { type: mimeType });
+ setMediaSrc(URL.createObjectURL(blob));
+ } else if (validationStatus.startsWith("media file does not exist")) {
+ throw new Error(`${isAudio ? "audio" : "video" } file not exists, it might get deleted`);
+ } else if (validationStatus.startsWith("invalid media file")) {
+ throw new Error(`the ${isAudio ? "audio" : "video" } file is not written completely`);
+ } else {
+ throw new Error("unknown media validation status");
}
- const blob = new Blob([bytes], { type: mimeType });
- setMediaSrc(URL.createObjectURL(blob));
} catch (error) {
console.error("Failed to load media:", error);
setError(
diff --git a/pipes/pipe-for-loom/app/favicon.ico b/pipes/pipe-for-loom/app/favicon.ico
index 718d6fea4..5be4ba27a 100644
Binary files a/pipes/pipe-for-loom/app/favicon.ico and b/pipes/pipe-for-loom/app/favicon.ico differ
diff --git a/pipes/search/bun.lockb b/pipes/search/bun.lockb
index ab47763d5..b9e52cc76 100755
Binary files a/pipes/search/bun.lockb and b/pipes/search/bun.lockb differ
diff --git a/pipes/search/src/app/favicon.ico b/pipes/search/src/app/favicon.ico
index 718d6fea4..5be4ba27a 100644
Binary files a/pipes/search/src/app/favicon.ico and b/pipes/search/src/app/favicon.ico differ
diff --git a/pipes/search/src/app/layout.tsx b/pipes/search/src/app/layout.tsx
index 140191d39..7fef7d66a 100644
--- a/pipes/search/src/app/layout.tsx
+++ b/pipes/search/src/app/layout.tsx
@@ -14,8 +14,8 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = {
- title: "Create Next App",
- description: "Generated by create next app",
+ title: "Search • Screenpipe",
+ description: "Search your spent time through Screenpipe",
};
export default function RootLayout({
diff --git a/pipes/search/src/components/video.tsx b/pipes/search/src/components/video.tsx
index 0028a7f23..04dc84cc4 100644
--- a/pipes/search/src/components/video.tsx
+++ b/pipes/search/src/components/video.tsx
@@ -37,27 +37,50 @@ export const VideoComponent = memo(function VideoComponent({
</div>
);
+ const validateMedia = async(path: string): Promise<string> => {
+ try {
+ const response = await fetch(`http://localhost:3030/experimental/validate/media?file_path=${encodeURIComponent(path)}`);
+ const result = await response.json();
+ return result.status;
+ } catch (error) {
+ console.error("Failed to validate media:", error);
+ return "Failed to validate media";
+ }
+ };
+
useEffect(() => {
async function loadMedia() {
try {
- console.log("Loading media:", filePath);
const sanitizedPath = sanitizeFilePath(filePath);
console.log("Sanitized path:", sanitizedPath);
- // Set isAudio based on path check
- setIsAudio(
- sanitizedPath.toLowerCase().includes("input") ||
- sanitizedPath.toLowerCase().includes("output")
- );
+ if (!sanitizedPath) {
+ throw new Error("Invalid file path");
+ }
+
+ const validationStatus = await validateMedia(sanitizedPath);
+ console.log("Media file:", validationStatus)
- const { data, mimeType } = await getMediaFile(sanitizedPath);
- const binaryData = atob(data);
- const bytes = new Uint8Array(binaryData.length);
- for (let i = 0; i < binaryData.length; i++) {
- bytes[i] = binaryData.charCodeAt(i);
+ if (validationStatus === "valid media file") {
+ setIsAudio(
+ sanitizedPath.toLowerCase().includes("input") ||
+ sanitizedPath.toLowerCase().includes("output")
+ );
+ const { data, mimeType } = await getMediaFile(sanitizedPath);
+ const binaryData = atob(data);
+ const bytes = new Uint8Array(binaryData.length);
+ for (let i = 0; i < binaryData.length; i++) {
+ bytes[i] = binaryData.charCodeAt(i);
+ }
+ const blob = new Blob([bytes], { type: mimeType });
+ setMediaSrc(URL.createObjectURL(blob));
+ } else if (validationStatus.startsWith("media file does not exist")) {
+ throw new Error(`${isAudio ? "audio" : "video" } file not exists, it might get deleted`);
+ } else if (validationStatus.startsWith("invalid media file")) {
+ throw new Error(`the ${isAudio ? "audio" : "video" } file is not written completely, please try again later`);
+ } else {
+ throw new Error("unknown media validation status");
}
- const blob = new Blob([bytes], { type: mimeType });
- setMediaSrc(URL.createObjectURL(blob));
} catch (error) {
console.error("Failed to load media:", error);
setError(
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index b00eceda6..23cf8003b 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -17,7 +17,13 @@ use crate::{
pipe_manager::PipeManager,
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
video_cache::{FrameCache, TimeSeriesFrame},
- video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},
+ video_utils::{
+ merge_videos,
+ validate_media,
+ MergeVideosRequest,
+ MergeVideosResponse,
+ ValidateMediaParams
+ },
DatabaseManager,
};
use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};
@@ -910,6 +916,22 @@ async fn merge_frames_handler(
}
}
+async fn validate_media_handler(
+ State(_state): State<Arc<AppState>>,
+ Query(params): Query<ValidateMediaParams>,
+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
+
+ match validate_media(&params.file_path).await {
+ Ok(_) => Ok(Json(json!({"status": "valid media file"}))),
+ Err(e) => {
+ Err((
+ StatusCode::EXPECTATION_FAILED,
+ Json(json!({"status": e.to_string()})),
+ ))
+ }
+ }
+}
+
#[derive(Deserialize)]
struct RawSqlQuery {
query: String,
@@ -1589,6 +1611,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/speakers/merge", post(merge_speakers_handler))
.route("/speakers/similar", get(get_similar_speakers_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))
+ .route("/experimental/validate/media", get(validate_media_handler))
.layer(cors);
#[cfg(feature = "experimental")]
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index d2b891318..d61303f23 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -71,8 +71,18 @@ pub struct MergeVideosResponse {
video_path: String,
}
-pub async fn validate_video(file_path: &str) -> Result<()> {
- // command: ffmpeg -v error -i <file> -f null -
+#[derive(Deserialize)]
+pub struct ValidateMediaParams {
+ pub file_path: String,
+}
+
+pub async fn validate_media(file_path: &str) -> Result<()> {
+ use tokio::fs::try_exists;
+
+ if !try_exists(file_path).await? {
+ return Err(anyhow::anyhow!("media file does not exist: {}", file_path));
+ }
+
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
let status = Command::new(ffmpeg_path)
.args(&[
@@ -90,7 +100,7 @@ pub async fn validate_video(file_path: &str) -> Result<()> {
if status.status.success() {
Ok(())
} else {
- Err(anyhow::anyhow!("invalid video file: {}", file_path))
+ Err(anyhow::anyhow!("invalid media file: {}", file_path))
}
}
@@ -113,7 +123,7 @@ pub async fn merge_videos(
let mut file = tokio::fs::File::create(&temp_file).await?;
for video_path in &request.video_paths {
// video validation before writing in txt
- if let Err(e) = validate_video(video_path).await{
+ if let Err(e) = validate_media(video_path).await{
error!("invalid file in merging, skipping: {:?}", e);
continue;
}