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"
```
**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 text/m3u file and convert it to a playlist

View File

@ -8,7 +8,7 @@
///
/// For all endpoints an (Bearer) authentication is required.\
/// `{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_multipart::Multipart;
@ -18,7 +18,7 @@ use actix_web::{
header::{ContentDisposition, DispositionType},
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};
@ -46,7 +46,7 @@ use crate::utils::{
},
naive_date_time_from_str,
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::{
auth::{create_jwt, Claims},
@ -447,7 +447,6 @@ async fn update_playout_config(
pool: web::Data<Pool<Sqlite>>,
id: web::Path<i32>,
data: web::Json<PlayoutConfig>,
config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<impl Responder, ServiceError> {
if let Ok(channel) = handles::select_channel(&pool.into_inner(), &id).await {
if let Ok(f) = std::fs::OpenOptions::new()
@ -456,7 +455,6 @@ async fn update_playout_config(
.open(channel.config_path)
{
serde_yaml::to_writer(f, &data).unwrap();
*config.lock().unwrap() = data.into_inner();
return Ok("Update playout config success.");
} else {
@ -776,10 +774,8 @@ pub async fn gen_playlist(
pool: web::Data<Pool<Sqlite>>,
params: web::Path<(i32, String)>,
data: Option<web::Json<PathsObj>>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<impl Responder, ServiceError> {
let channel = handles::select_channel(&pool.into_inner(), &params.0).await?;
let mut config = global_config.lock().unwrap();
let (mut config, channel) = playout_config(&pool.into_inner(), &params.0).await?;
config.general.generate = Some(vec![params.1.clone()]);
if let Some(obj) = data {
@ -932,15 +928,25 @@ async fn save_file(
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:.*}")]
#[has_any_role("Role::Admin", "Role::User", type = "Role")]
async fn get_file(req: HttpRequest, config: web::Data<Arc<Mutex<PlayoutConfig>>>,) -> Result<actix_files::NamedFile, Error> {
let storage_path = &config.lock().unwrap().storage.path;
async fn get_file(
pool: web::Data<Pool<Sqlite>>,
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 (path, _, _) = norm_abs_path(storage_path, file_path);
println!("{path:?}");
let (path, _, _) = norm_abs_path(&storage_path, file_path);
let file = actix_files::NamedFile::open(path)?;
Ok(file
.use_last_modified(true)
.set_content_disposition(ContentDisposition {
@ -965,12 +971,11 @@ async fn import_playlist(
id: web::Path<i32>,
payload: Multipart,
obj: web::Query<ImportObj>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> Result<HttpResponse, ServiceError> {
let file = obj.file.file_name().unwrap_or_default();
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 config = global_config.lock().unwrap();
upload(&pool.into_inner(), *id, payload, &path, true).await?;
import_file(&config, &obj.date, Some(channel.name), &path)?;
@ -1008,9 +1013,8 @@ async fn get_program(
pool: web::Data<Pool<Sqlite>>,
id: web::Path<i32>,
obj: web::Query<ProgramObj>,
global_config: web::Data<Arc<Mutex<PlayoutConfig>>>,
) -> 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 mut days = 0;
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_web::{dev::ServiceRequest, middleware, web, App, Error, HttpMessage, HttpServer};
@ -12,10 +12,7 @@ pub mod api;
pub mod db;
pub mod utils;
use api::{
auth,
routes::*,
};
use api::{auth, routes::*};
use db::{db_pool, models::LoginUser};
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 port = ip_port[1].parse::<u16>().unwrap();
let engine_process = web::Data::new(ProcessControl::new());
let global_config = Arc::new(Mutex::new(config));
info!("running ffplayout API, listen on {conn}");
@ -93,11 +89,9 @@ async fn main() -> std::io::Result<()> {
HttpServer::new(move || {
let auth = HttpAuthentication::bearer(validator);
let db_pool = web::Data::new(pool.clone());
let global = web::Data::new(global_config.clone());
App::new()
.app_data(db_pool)
.app_data(global)
.app_data(engine_process.clone())
.wrap(middleware::Logger::default())
.service(login)
@ -134,10 +128,10 @@ async fn main() -> std::io::Result<()> {
.service(move_rename)
.service(remove)
.service(save_file)
.service(get_file)
.service(import_playlist)
.service(get_program),
)
.service(get_file)
.service(Files::new("/", public_path()).index_file("index.html"))
})
.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 {
fn from(err: actix_web::error::BlockingError) -> ServiceError {
ServiceError::BadRequest(err.to_string())