no auth for file route, get config from channel id, (revert to old state)

This commit is contained in:
jb-alvarado 2023-10-30 23:03:53 +01:00
parent b475854578
commit 14a86fedbc
4 changed files with 39 additions and 27 deletions

View File

@ -328,6 +328,14 @@ curl -X PUT http://127.0.0.1:8787/api/file/1/upload/ -H 'Authorization: Bearer <
-F "file=@file.mp4" -F "file=@file.mp4"
``` ```
**Get File**
Can be used for preview video files
```BASH
curl -X GET http://127.0.0.1:8787/file/1/path/to/file.mp4
```
**Import playlist** **Import playlist**
Import text/m3u file and convert it to a playlist Import text/m3u file and convert it to a playlist

View File

@ -8,7 +8,7 @@
/// ///
/// For all endpoints an (Bearer) authentication is required.\ /// For all endpoints an (Bearer) authentication is required.\
/// `{id}` represent the channel id, and at default is 1. /// `{id}` represent the channel id, and at default is 1.
use std::{collections::HashMap, env, fs, path::PathBuf, sync::{Arc, Mutex}}; use std::{collections::HashMap, env, fs, path::PathBuf};
use actix_files; use actix_files;
use actix_multipart::Multipart; use actix_multipart::Multipart;
@ -18,7 +18,7 @@ use actix_web::{
header::{ContentDisposition, DispositionType}, header::{ContentDisposition, DispositionType},
StatusCode, StatusCode,
}, },
patch, post, put, web, Error, HttpRequest, HttpResponse, Responder, patch, post, put, web, HttpRequest, HttpResponse, Responder,
}; };
use actix_web_grants::{permissions::AuthDetails, proc_macro::has_any_role}; use actix_web_grants::{permissions::AuthDetails, proc_macro::has_any_role};
@ -46,7 +46,7 @@ use crate::utils::{
}, },
naive_date_time_from_str, naive_date_time_from_str,
playlist::{delete_playlist, generate_playlist, read_playlist, write_playlist}, playlist::{delete_playlist, generate_playlist, read_playlist, write_playlist},
read_log_file, read_playout_config, Role, playout_config, read_log_file, read_playout_config, Role,
}; };
use crate::{ use crate::{
auth::{create_jwt, Claims}, auth::{create_jwt, Claims},
@ -447,7 +447,6 @@ async fn update_playout_config(
pool: web::Data<Pool<Sqlite>>, pool: web::Data<Pool<Sqlite>>,
id: web::Path<i32>, id: web::Path<i32>,
data: web::Json<PlayoutConfig>, data: web::Json<PlayoutConfig>,
config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<impl Responder, ServiceError> { ) -> Result<impl Responder, ServiceError> {
if let Ok(channel) = handles::select_channel(&pool.into_inner(), &id).await { if let Ok(channel) = handles::select_channel(&pool.into_inner(), &id).await {
if let Ok(f) = std::fs::OpenOptions::new() if let Ok(f) = std::fs::OpenOptions::new()
@ -456,7 +455,6 @@ async fn update_playout_config(
.open(channel.config_path) .open(channel.config_path)
{ {
serde_yaml::to_writer(f, &data).unwrap(); serde_yaml::to_writer(f, &data).unwrap();
*config.lock().unwrap() = data.into_inner();
return Ok("Update playout config success."); return Ok("Update playout config success.");
} else { } else {
@ -776,10 +774,8 @@ pub async fn gen_playlist(
pool: web::Data<Pool<Sqlite>>, pool: web::Data<Pool<Sqlite>>,
params: web::Path<(i32, String)>, params: web::Path<(i32, String)>,
data: Option<web::Json<PathsObj>>, data: Option<web::Json<PathsObj>>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<impl Responder, ServiceError> { ) -> Result<impl Responder, ServiceError> {
let channel = handles::select_channel(&pool.into_inner(), &params.0).await?; let (mut config, channel) = playout_config(&pool.into_inner(), &params.0).await?;
let mut config = global_config.lock().unwrap();
config.general.generate = Some(vec![params.1.clone()]); config.general.generate = Some(vec![params.1.clone()]);
if let Some(obj) = data { if let Some(obj) = data {
@ -932,15 +928,25 @@ async fn save_file(
upload(&pool.into_inner(), *id, payload, &obj.path, false).await upload(&pool.into_inner(), *id, payload, &obj.path, false).await
} }
/// **Get File**
///
/// Can be used for preview video files
///
/// ```BASH
/// curl -X GET http://127.0.0.1:8787/file/1/path/to/file.mp4
/// ```
#[get("/file/{id}/{filename:.*}")] #[get("/file/{id}/{filename:.*}")]
#[has_any_role("Role::Admin", "Role::User", type = "Role")] async fn get_file(
async fn get_file(req: HttpRequest, config: web::Data<Arc<Mutex<PlayoutConfig>>>,) -> Result<actix_files::NamedFile, Error> { pool: web::Data<Pool<Sqlite>>,
let storage_path = &config.lock().unwrap().storage.path; req: HttpRequest,
) -> Result<actix_files::NamedFile, ServiceError> {
let id: i32 = req.match_info().query("id").parse()?;
let (config, _) = playout_config(&pool.into_inner(), &id).await?;
let storage_path = config.storage.path;
let file_path = req.match_info().query("filename"); let file_path = req.match_info().query("filename");
let (path, _, _) = norm_abs_path(storage_path, file_path); let (path, _, _) = norm_abs_path(&storage_path, file_path);
println!("{path:?}");
let file = actix_files::NamedFile::open(path)?; let file = actix_files::NamedFile::open(path)?;
Ok(file Ok(file
.use_last_modified(true) .use_last_modified(true)
.set_content_disposition(ContentDisposition { .set_content_disposition(ContentDisposition {
@ -965,12 +971,11 @@ async fn import_playlist(
id: web::Path<i32>, id: web::Path<i32>,
payload: Multipart, payload: Multipart,
obj: web::Query<ImportObj>, obj: web::Query<ImportObj>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<HttpResponse, ServiceError> { ) -> Result<HttpResponse, ServiceError> {
let file = obj.file.file_name().unwrap_or_default(); let file = obj.file.file_name().unwrap_or_default();
let path = env::temp_dir().join(file); let path = env::temp_dir().join(file);
let (config, _) = playout_config(&pool.clone().into_inner(), &id).await?;
let channel = handles::select_channel(&pool.clone().into_inner(), &id).await?; let channel = handles::select_channel(&pool.clone().into_inner(), &id).await?;
let config = global_config.lock().unwrap();
upload(&pool.into_inner(), *id, payload, &path, true).await?; upload(&pool.into_inner(), *id, payload, &path, true).await?;
import_file(&config, &obj.date, Some(channel.name), &path)?; import_file(&config, &obj.date, Some(channel.name), &path)?;
@ -1008,9 +1013,8 @@ async fn get_program(
pool: web::Data<Pool<Sqlite>>, pool: web::Data<Pool<Sqlite>>,
id: web::Path<i32>, id: web::Path<i32>,
obj: web::Query<ProgramObj>, obj: web::Query<ProgramObj>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<impl Responder, ServiceError> { ) -> Result<impl Responder, ServiceError> {
let config = global_config.lock().unwrap(); let (config, _) = playout_config(&pool.clone().into_inner(), &id).await?;
let start_sec = config.playlist.start_sec.unwrap(); let start_sec = config.playlist.start_sec.unwrap();
let mut days = 0; let mut days = 0;
let mut program = vec![]; let mut program = vec![];

View File

@ -1,4 +1,4 @@
use std::{path::Path, process::exit, sync::{Arc, Mutex}}; use std::{path::Path, process::exit};
use actix_files::Files; use actix_files::Files;
use actix_web::{dev::ServiceRequest, middleware, web, App, Error, HttpMessage, HttpServer}; use actix_web::{dev::ServiceRequest, middleware, web, App, Error, HttpMessage, HttpServer};
@ -12,10 +12,7 @@ pub mod api;
pub mod db; pub mod db;
pub mod utils; pub mod utils;
use api::{ use api::{auth, routes::*};
auth,
routes::*,
};
use db::{db_pool, models::LoginUser}; use db::{db_pool, models::LoginUser};
use utils::{args_parse::Args, control::ProcessControl, db_path, init_config, run_args, Role}; use utils::{args_parse::Args, control::ProcessControl, db_path, init_config, run_args, Role};
@ -85,7 +82,6 @@ async fn main() -> std::io::Result<()> {
let addr = ip_port[0]; let addr = ip_port[0];
let port = ip_port[1].parse::<u16>().unwrap(); let port = ip_port[1].parse::<u16>().unwrap();
let engine_process = web::Data::new(ProcessControl::new()); let engine_process = web::Data::new(ProcessControl::new());
let global_config = Arc::new(Mutex::new(config));
info!("running ffplayout API, listen on {conn}"); info!("running ffplayout API, listen on {conn}");
@ -93,11 +89,9 @@ async fn main() -> std::io::Result<()> {
HttpServer::new(move || { HttpServer::new(move || {
let auth = HttpAuthentication::bearer(validator); let auth = HttpAuthentication::bearer(validator);
let db_pool = web::Data::new(pool.clone()); let db_pool = web::Data::new(pool.clone());
let global = web::Data::new(global_config.clone());
App::new() App::new()
.app_data(db_pool) .app_data(db_pool)
.app_data(global)
.app_data(engine_process.clone()) .app_data(engine_process.clone())
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.service(login) .service(login)
@ -134,10 +128,10 @@ async fn main() -> std::io::Result<()> {
.service(move_rename) .service(move_rename)
.service(remove) .service(remove)
.service(save_file) .service(save_file)
.service(get_file)
.service(import_playlist) .service(import_playlist)
.service(get_program), .service(get_program),
) )
.service(get_file)
.service(Files::new("/", public_path()).index_file("index.html")) .service(Files::new("/", public_path()).index_file("index.html"))
}) })
.bind((addr, port))? .bind((addr, port))?

View File

@ -64,6 +64,12 @@ impl From<std::io::Error> for ServiceError {
} }
} }
impl From<std::num::ParseIntError> for ServiceError {
fn from(err: std::num::ParseIntError) -> ServiceError {
ServiceError::BadRequest(err.to_string())
}
}
impl From<actix_web::error::BlockingError> for ServiceError { impl From<actix_web::error::BlockingError> for ServiceError {
fn from(err: actix_web::error::BlockingError) -> ServiceError { fn from(err: actix_web::error::BlockingError) -> ServiceError {
ServiceError::BadRequest(err.to_string()) ServiceError::BadRequest(err.to_string())