Try to stream the file in handler.

This commit is contained in:
Florian THIERRY
2026-07-24 15:38:36 +02:00
parent f8f86eeae1
commit cef96884c6
6 changed files with 35 additions and 17 deletions
+2 -1
View File
@@ -2,7 +2,7 @@ extern crate core;
use actix_web::web::ServiceConfig;
use actix_web::{get, web, HttpResponse, Responder};
use crate::video::handler::{download_file, get_root_folder_content};
use crate::video::handler::{download_file, get_root_folder_content, get_video_stream};
pub mod user;
pub mod video;
@@ -14,6 +14,7 @@ async fn health() -> impl Responder {
pub fn init(cfg: &mut ServiceConfig) {
cfg.service(download_file)
.service(get_video_stream)
.service(get_root_folder_content);
cfg.default_service(web::to(not_found));
}
+18 -10
View File
@@ -28,22 +28,30 @@ pub async fn get_video_stream(
) -> impl Responder {
let video_result = video_service.get_video_stream(video_id.into_inner());
match video_result {
Ok(video) => {
if let Some(tokioVideoFile) = video.file.as_any().downcast_ref::<TokioVideoFile>() {
HttpResponse::Ok()
.content_type("application/octet-stream")
.streaming(async_stream::stream! {
let mut stream = FramedRead::new(tokioVideoFile.file, BytesCodec::new());
while let Some(chunk) = stream.next().await {
yield chunk.map(|bytes| bytes.freeze());
}
})
if let Some(tokio_video_file) = video.file.as_any().downcast_ref::<TokioVideoFile>() {
// Clone the file to extend its lifetime into the streaming closure
let cloned_file = tokio_video_file.file.try_clone();
match cloned_file {
Ok(file) => HttpResponse::Ok()
.content_type("application/octet-stream")
.streaming(async_stream::stream! {
let mut stream = FramedRead::new(file, BytesCodec::new());
while let Some(chunk) = stream.next().await {
yield chunk.map(|bytes| bytes.freeze());
}
}),
Err(_) => HttpResponse::InternalServerError().body("Failed to clone video file")
}
} else {
HttpResponse::InternalServerError().body("Video file format is not handled.")
}
}
Err(error) => HttpResponse::InternalServerError().body("C P T")
Err(error) => HttpResponse::InternalServerError().body(format!("{:?}", error))
}
}