from fastapi import FastAPI, File, UploadFile
import shutil
import os
from datetime import datetime
import subprocess
from [Link] import HTMLResponse
from [Link] import StaticFiles
import requests
import uvicorn
from [Link] import CORSMiddleware
from [Link] import quote
import aiofiles
app = FastAPI()
# Serve static files (like CSS)
[Link]("/static", StaticFiles(directory="static"), name="static")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Or specify the allowed domains
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
DESKTOP_DIR = r"\\[Link]\Users\Klajdi\Desktop\New folder"
[Link](DESKTOP_DIR, exist_ok=True)
FFMPEG_PATH = "ffmpeg" # Ensure ffmpeg is in your PATH or provide the full path.
# Serve the HTML file
@[Link]("/", response_class=HTMLResponse)
async def get_video_recorder():
with open("[Link]", "r") as file:
return [Link]()
# Endpoint to upload video (timestamped filename)
@[Link]("/upload_video")
async def upload_video(video: UploadFile = File(...)):
timestamp = [Link]().strftime("%Y-%m-%d_%H-%M-%S") # Timestamp for
filenames
video_filename = f"video_{timestamp}.mp4" # Add timestamp to video filename
video_path = [Link](DESKTOP_DIR, video_filename) # Save to desktop
try:
# Use aiofiles to handle the file asynchronously
async with [Link](video_path, 'wb') as out_file:
# Read the file in chunks and write it to the server
while content := await [Link](1024): # 1 KB chunks
await out_file.write(content)
# Ensure the file was saved correctly
if [Link](video_path):
print(f"File {video_filename} saved successfully.")
else:
print(f"Error: File {video_filename} not saved.")
# Communicate with the external API if needed
encoded_file_path = quote(video_path)
api_url = f"[Link]
file_path={encoded_file_path}"
# Send the file to the external API
response = [Link](api_url)
if response.status_code == 200:
print(f"API response: {[Link]()}")
else:
print(f"API Error: {response.status_code} - {[Link]}")
except Exception as e:
return {"message": f"An error occurred while uploading the video:
{str(e)}"}
return {"message": "Video uploaded successfully", "filename": video_filename}
# Endpoint to upload snapshot (timestamped filename)
@[Link]("/upload_snapshot")
async def upload_snapshot(snapshot: UploadFile = File(...)):
timestamp = [Link]().strftime("%Y-%m-%d_%H-%M-%S") # Timestamp for
filenames
snapshot_filename = f"screenshot_{timestamp}.jpg" # Add timestamp to snapshot
filename
snapshot_path = [Link](DESKTOP_DIR, snapshot_filename) # Save to desktop
with open(snapshot_path, "wb") as buffer:
[Link]([Link], buffer)
try:
from [Link] import quote
encoded_file_path = quote(snapshot_path)
api_url = f"[Link]
file_path={encoded_file_path}"
response = [Link](api_url)
if response.status_code == 200:
print(f"API response: {[Link]()}")
else:
print(
f"Failed to communicate with API. Status code:
{response.status_code}, Response: {[Link]}")
except [Link] as e:
print(f"Error communicating with the API: {e}")
return {"message": "Snapshot uploaded successfully", "filename":
snapshot_filename}
if __name__ == "__main__":
[Link](app, host="[Link]", port=8000, ssl_keyfile="[Link]",
ssl_certfile="[Link]")
//[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Recorder</title>
<link rel="stylesheet" href="/static/[Link]">
<link href="[Link]
css/[Link]" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Video Recorder</h1>
<video id="video" autoplay></video>
<div class="controls">
<button id="record-btn"><i class="fa-solid fa-play"></i></button>
<button id="pause-btn" disabled><i class="fa-solid
fa-pause"></i></button>
<button id="stop-btn" disabled><i class="fa-solid
fa-stop"></i></button>
<button id="snapshot-btn"><i class="fa-solid fa-camera"></i></button>
</div>
</div>
<script>
let mediaRecorder;
let recordedChunks = [];
const videoElement = [Link]('video');
const recordButton = [Link]('record-btn');
const pauseButton = [Link]('pause-btn');
const stopButton = [Link]('stop-btn');
const snapshotButton = [Link]('snapshot-btn');
async function setupCamera() {
try {
// Request both video and audio permissions
const stream = await [Link]({
video: { width: 1920, height: 1080 }, // Set video resolution
to 1280x720
audio: true // Optionally request audio as well if needed
});
[Link] = stream;
[Link] = 1920; // Set video element width
[Link] = 1080; // Set video element height
return stream;
} catch (error) {
[Link]('Camera permission denied:', error);
alert('Camera permission denied. Please allow camera access.');
}
}
async function startRecording(stream) {
mediaRecorder = new MediaRecorder(stream);
[Link] = event =>
[Link]([Link]);
[Link] = () => {
const blob = new Blob(recordedChunks, { type: 'video/mp4' });
const formData = new FormData();
[Link]('video', blob, 'recorded_video.mp4');
fetch('/upload_video', { method: 'POST', body: formData });
recordedChunks = [];
};
[Link]();
}
function takeSnapshot() {
const canvas = [Link]('canvas');
[Link] = 640;
[Link] = 480;
const ctx = [Link]('2d');
[Link](videoElement, 0, 0, [Link], [Link]);
[Link](blob => {
const formData = new FormData();
[Link]('snapshot', blob, '[Link]');
fetch('/upload_snapshot', { method: 'POST', body: formData });
});
}
[Link]('click', async () => {
const stream = await setupCamera();
await startRecording(stream);
[Link] = true;
[Link] = false;
[Link] = false;
});
[Link]('click', () => {
if ([Link] === 'recording') {
[Link]();
[Link] = 'Resume';
} else {
[Link]();
[Link] = 'Pause';
}
});
[Link]('click', () => {
[Link]();
[Link] = false;
[Link] = true;
[Link] = true;
});
[Link]('click', takeSnapshot);
</script>
</body>
</html>