fix video stream

This commit is contained in:
Logan Cusano
2025-07-13 21:17:54 -04:00
parent 5896165cfd
commit eb3cee1b66
2 changed files with 66 additions and 15 deletions

View File

@@ -1,24 +1,66 @@
'use client';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth';
import { apiRequest, API_URL } from '@/lib/api';
import { apiRequest } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
const VotingPage = () => {
const [video, setVideo] = useState<any>(null);
const [videoUrl, setVideoUrl] = useState<string | null>(null); // State for the blob URL
const [reason, setReason] = useState('');
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const auth = useAuth();
// This effect runs when the `video` metadata is fetched
useEffect(() => {
// If there's no video metadata, do nothing.
if (!video) {
return;
}
let objectUrl: string; // To keep track of the URL for cleanup
const fetchVideoBlob = async () => {
try {
// Fetch the video stream as a raw response, not JSON
const response = await apiRequest(`/videos/${video.id}/stream`, {
token: auth.token,
wantsJson: false // We expect a blob, not JSON
});
const blob = await response.blob();
objectUrl = URL.createObjectURL(blob);
setVideoUrl(objectUrl);
} catch (err: any) {
setError(`Failed to load video: ${err.message}`);
}
};
fetchVideoBlob();
// Cleanup function: revoke the object URL to free up memory
return () => {
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
};
}, [video, auth.token]);
const fetchNextVideo = async () => {
// Reset all states for the new video
setError('');
setMessage('');
setVideo(null);
setVideoUrl(null);
setReason('');
try {
// This just gets the video metadata (id, person, game)
const data = await apiRequest('/videos/vote-next', { token: auth.token });
setVideo(data);
} catch (err: any) {
@@ -38,7 +80,9 @@ const VotingPage = () => {
token: auth.token
});
setMessage(`Vote '${decision}' submitted successfully!`);
// Reset state to prepare for the next video
setVideo(null);
setVideoUrl(null);
setReason('');
} catch (err: any) {
setError(err.message);
@@ -61,14 +105,15 @@ const VotingPage = () => {
{error && <p className="text-center text-red-500">{error}</p>}
{message && <p className="text-center text-green-500">{message}</p>}
{video && (
{/* The video player now uses the local blob URL */}
{video && videoUrl && (
<div className="space-y-4">
<div>
<video
key={video.id}
className="w-full rounded-lg bg-black"
controls
src={`${API_URL}/videos/${video.id}/stream?token=${auth.token}`}
src={videoUrl} // Use the state variable for the src
>
Your browser does not support the video tag.
</video>

View File

@@ -1,20 +1,26 @@
// We still export this for use in components where the raw URL is needed,
// like the <video> src attribute.
// webapp/lib/api.ts
export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000';
type ApiRequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
body?: any;
token?: string | null;
wantsJson?: boolean; // Add this to control response parsing
};
export const apiRequest = async (endpoint: string, options: ApiRequestOptions = {}) => {
const { method = 'GET', body = null, token = null } = options;
// Set wantsJson to true by default, false for specific cases like file streams
const { method = 'GET', body = null, token = null, wantsJson = true } = options;
const headers: HeadersInit = {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
// Only set Content-Type for requests with a body
if (body) {
headers['Content-Type'] = 'application/json';
}
if (token) {
headers['Authorization'] = `Bearer ${token}`;
@@ -29,20 +35,20 @@ export const apiRequest = async (endpoint: string, options: ApiRequestOptions =
config.body = JSON.stringify(body);
}
// Use the API_URL variable to construct the full URL inside the function
const response = await fetch(`${API_URL}${endpoint}`, config);
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: 'An unknown error occurred' }));
throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
}
// Handle cases where the response might not be JSON
const contentType = response.headers.get("content-type");
if (contentType?.includes("application/json")) {
return response.json();
if (wantsJson) {
const contentType = response.headers.get("content-type");
if (contentType?.includes("application/json")) {
return response.json();
}
}
// For non-json responses (like video streams or simple text), return the raw response
// For non-JSON requests, return the raw response object
return response;
};