(add):push on dev branch
This commit is contained in:
parent
2265fd0263
commit
d7154bbc55
@ -12,37 +12,46 @@ pub struct DownloadRequest {
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ApiResponse {
|
||||
status: String,
|
||||
status: &'static str,
|
||||
message: String,
|
||||
file: Option<String>,
|
||||
}
|
||||
|
||||
/// Helper pour générer une réponse JSON cohérente
|
||||
fn json_response(status: &'static str, message: impl Into<String>, file: Option<String>) -> HttpResponse {
|
||||
HttpResponse::Ok().json(ApiResponse {
|
||||
status,
|
||||
message: message.into(),
|
||||
file,
|
||||
})
|
||||
}
|
||||
|
||||
#[post("/download")]
|
||||
pub async fn download(req: web::Json<DownloadRequest>) -> impl Responder {
|
||||
// ✅ Validation de la requête
|
||||
if let Err(msg) = validate_request(&req.url, &req.format) {
|
||||
return HttpResponse::BadRequest().json(serde_json::json!({
|
||||
"status": "error",
|
||||
"message": msg,
|
||||
"file": null
|
||||
}));
|
||||
return HttpResponse::BadRequest().json(ApiResponse {
|
||||
status: "error",
|
||||
message: msg,
|
||||
file: None,
|
||||
});
|
||||
}
|
||||
|
||||
// ✅ Téléchargement depuis YouTube
|
||||
match download_from_youtube(&req.url, &req.format).await {
|
||||
Ok(file_path) => {
|
||||
// ✅ Conversion audio
|
||||
match convert_file(&file_path, &req.format).await {
|
||||
Ok(final_file) => HttpResponse::Ok().json(ApiResponse {
|
||||
status: "ok".to_string(),
|
||||
message: "Téléchargement et conversion réussis".to_string(),
|
||||
file: Some(final_file),
|
||||
}),
|
||||
Ok(final_file) => json_response("ok", "Téléchargement et conversion réussis", Some(final_file)),
|
||||
Err(e) => HttpResponse::InternalServerError().json(ApiResponse {
|
||||
status: "error".to_string(),
|
||||
status: "error",
|
||||
message: format!("Erreur conversion: {}", e),
|
||||
file: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
Err(e) => HttpResponse::InternalServerError().json(ApiResponse {
|
||||
status: "error".to_string(),
|
||||
status: "error",
|
||||
message: format!("Erreur téléchargement: {}", e),
|
||||
file: None,
|
||||
}),
|
||||
|
||||
23
src/main.rs
23
src/main.rs
@ -1,27 +1,36 @@
|
||||
// Déclaration des modules internes
|
||||
mod routes;
|
||||
mod handlers;
|
||||
mod services;
|
||||
mod middleware;
|
||||
mod utils;
|
||||
|
||||
use actix_web::{App, HttpServer};
|
||||
use actix_web::{App, HttpServer, middleware::Logger};
|
||||
use middleware::auth::ApiKeyMiddleware;
|
||||
|
||||
|
||||
|
||||
use std::env;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
// Charger les variables d'environnement depuis .env (facultatif)
|
||||
dotenvy::dotenv().ok();
|
||||
|
||||
println!(" API Jellyfin sur http://192.168.1.107:8080");
|
||||
// Définir l'adresse du serveur (par défaut 0.0.0.0:8080)
|
||||
let host = env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
|
||||
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
|
||||
let bind_addr = format!("{}:{}", host, port);
|
||||
|
||||
println!("🚀 API Jellyfin démarrée sur http://{}", bind_addr);
|
||||
|
||||
HttpServer::new(|| {
|
||||
App::new()
|
||||
.wrap(ApiKeyMiddleware) //
|
||||
// Logger Actix (affiche les requêtes entrantes)
|
||||
.wrap(Logger::default())
|
||||
// Middleware Auth par clé API
|
||||
.wrap(ApiKeyMiddleware {})
|
||||
// Routes de l'application
|
||||
.configure(routes::config)
|
||||
})
|
||||
.bind("192.168.1.107:8080")?
|
||||
.bind(bind_addr)?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
@ -6,15 +6,16 @@ use actix_web::{
|
||||
use futures_util::future::{ok, Ready, LocalBoxFuture};
|
||||
use std::rc::Rc;
|
||||
use std::env;
|
||||
use serde_json::json;
|
||||
|
||||
pub struct ApiKeyMiddleware;
|
||||
|
||||
impl<S, B> Transform<S, ServiceRequest> for ApiKeyMiddleware
|
||||
where
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
||||
B: MessageBody + 'static, // ✅ contrainte ajoutée
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
type Response = ServiceResponse<BoxBody>; // ✅ on fige le type
|
||||
type Response = ServiceResponse<BoxBody>;
|
||||
type Error = Error;
|
||||
type Transform = ApiKeyMiddlewareInner<S>;
|
||||
type InitError = ();
|
||||
@ -23,20 +24,22 @@ where
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(ApiKeyMiddlewareInner {
|
||||
service: Rc::new(service),
|
||||
api_key: env::var("API_KEY").expect("⚠️ API_KEY must be set in .env"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApiKeyMiddlewareInner<S> {
|
||||
service: Rc<S>,
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
impl<S, B> Service<ServiceRequest> for ApiKeyMiddlewareInner<S>
|
||||
where
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
||||
B: MessageBody + 'static, // ✅ même contrainte ici
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
type Response = ServiceResponse<BoxBody>; // ✅ réponse homogène
|
||||
type Response = ServiceResponse<BoxBody>;
|
||||
type Error = Error;
|
||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||
|
||||
@ -48,26 +51,25 @@ where
|
||||
}
|
||||
|
||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||
let auth_header = req.headers().get("Authorization").cloned();
|
||||
let service = self.service.clone();
|
||||
let expected = format!("Bearer {}", self.api_key);
|
||||
|
||||
Box::pin(async move {
|
||||
let expected_key = env::var("API_KEY").unwrap_or_else(|_| "changeme".to_string());
|
||||
|
||||
if let Some(value) = auth_header {
|
||||
if value == format!("Bearer {}", expected_key) {
|
||||
// ✅ convertit en BoxBody
|
||||
return service.call(req).await.map(|res| res.map_into_boxed_body());
|
||||
match req.headers().get("Authorization") {
|
||||
Some(value) if value == expected.as_str() => {
|
||||
service.call(req).await.map(|res| res.map_into_boxed_body())
|
||||
}
|
||||
_ => {
|
||||
let (req, _) = req.into_parts();
|
||||
let res = HttpResponse::Unauthorized()
|
||||
.json(json!({
|
||||
"status": "error",
|
||||
"message": "Unauthorized"
|
||||
}))
|
||||
.map_into_boxed_body();
|
||||
Ok(ServiceResponse::new(req, res))
|
||||
}
|
||||
}
|
||||
|
||||
let (req, _) = req.into_parts();
|
||||
|
||||
let res = HttpResponse::Unauthorized()
|
||||
.body("Unauthorized")
|
||||
.map_into_boxed_body();
|
||||
|
||||
Ok(ServiceResponse::new(req, res))
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,11 @@
|
||||
use actix_web::web;
|
||||
|
||||
use crate::handlers::download::download;
|
||||
use crate::handlers::download;
|
||||
|
||||
/// Configuration des routes de l'API
|
||||
pub fn config(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(download);
|
||||
cfg.service(
|
||||
web::scope("/api")
|
||||
.service(download::download),
|
||||
);
|
||||
}
|
||||
@ -1,19 +1,29 @@
|
||||
use std::process::Command;
|
||||
use anyhow::Result;
|
||||
use std::path::Path;
|
||||
use anyhow::{Result, Context};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn convert_file(input: &str, format: &str) -> Result<String> {
|
||||
let output_file = format!("/tmp/{}_conv.{}", Uuid::new_v4(), format);
|
||||
|
||||
let status = Command::new("ffmpeg")
|
||||
.arg("-y")
|
||||
.arg("-i").arg(input)
|
||||
.arg(&output_file)
|
||||
.status()?;
|
||||
// Exécution de ffmpeg avec redirection des sorties
|
||||
let output = Command::new("ffmpeg")
|
||||
.arg("-y") // overwrite sans confirmation
|
||||
.arg("-i").arg(input) // input file
|
||||
.arg(&output_file) // output file
|
||||
.output()
|
||||
.with_context(|| "Impossible d'exécuter ffmpeg")?;
|
||||
|
||||
if status.success() {
|
||||
Ok(output_file)
|
||||
// Vérification du code retour
|
||||
if output.status.success() {
|
||||
// Vérification que le fichier existe vraiment
|
||||
if Path::new(&output_file).exists() {
|
||||
Ok(output_file)
|
||||
} else {
|
||||
Err(anyhow::anyhow!("ffmpeg n’a pas généré de fichier de sortie"))
|
||||
}
|
||||
} else {
|
||||
Err(anyhow::anyhow!("ffmpeg conversion failed"))
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
Err(anyhow::anyhow!("Échec ffmpeg: {}", stderr))
|
||||
}
|
||||
}
|
||||
@ -1,23 +1,34 @@
|
||||
use std::process::Command;
|
||||
use anyhow::Result;
|
||||
use std::path::Path;
|
||||
use anyhow::{Result, Context};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn download_from_youtube(url: &str, format: &str) -> Result<String> {
|
||||
let output_file = format!("/tmp/{}_out.{}", Uuid::new_v4(), format);
|
||||
// On laisse yt-dlp gérer l'extension, mais on contrôle le préfixe
|
||||
let output_template = format!("/tmp/{}_out.%(ext)s", Uuid::new_v4());
|
||||
|
||||
let status = Command::new("yt-dlp")
|
||||
.arg("-x")
|
||||
.arg("--audio-format")
|
||||
.arg(format)
|
||||
.arg("--no-playlist")
|
||||
.arg("-o")
|
||||
.arg(&output_file)
|
||||
// Exécution yt-dlp
|
||||
let output = Command::new("yt-dlp")
|
||||
.arg("-x") // extraire uniquement l’audio
|
||||
.arg("--audio-format").arg(format)
|
||||
.arg("--no-playlist")
|
||||
.arg("-o").arg(&output_template)
|
||||
.arg(url)
|
||||
.status()?;
|
||||
.output()
|
||||
.with_context(|| "Impossible d'exécuter yt-dlp")?;
|
||||
|
||||
if status.success() {
|
||||
Ok(output_file)
|
||||
// Vérification du code retour
|
||||
if output.status.success() {
|
||||
// yt-dlp remplace %(ext)s par la vraie extension
|
||||
let expected_file = output_template.replace("%(ext)s", format);
|
||||
|
||||
if Path::new(&expected_file).exists() {
|
||||
Ok(expected_file)
|
||||
} else {
|
||||
Err(anyhow::anyhow!("yt-dlp a terminé sans générer de fichier"))
|
||||
}
|
||||
} else {
|
||||
Err(anyhow::anyhow!("yt-dlp failed with status: {:?}", status))
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
Err(anyhow::anyhow!("Échec yt-dlp: {}", stderr))
|
||||
}
|
||||
}
|
||||
@ -1,18 +1,24 @@
|
||||
use url::Url;
|
||||
|
||||
pub fn validate_request(url: &str, format: &str) -> Result<(), String> {
|
||||
if let Ok(parsed) = Url::parse(url) {
|
||||
match parsed.domain() {
|
||||
Some("youtube.com") | Some("www.youtube.com") | Some("youtu.be") => {}
|
||||
_ => return Err("URL non autorisée.".into()),
|
||||
}
|
||||
} else {
|
||||
return Err("URL invalide.".into());
|
||||
// Vérification de l'URL
|
||||
let parsed = Url::parse(url).map_err(|_| "URL invalide.".to_string())?;
|
||||
|
||||
// Liste blanche des domaines
|
||||
let allowed_domains = ["youtube.com", "www.youtube.com", "youtu.be"];
|
||||
let domain = parsed.domain().unwrap_or_default();
|
||||
|
||||
if !allowed_domains.contains(&domain) {
|
||||
return Err(format!("Domaine non autorisé: {}", domain));
|
||||
}
|
||||
|
||||
let allowed = ["mp3", "flac", "wav"];
|
||||
if !allowed.contains(&format) {
|
||||
return Err("Format non supporté.".into());
|
||||
// Vérification du format
|
||||
let allowed_formats = ["mp3", "flac", "wav"];
|
||||
if !allowed_formats.contains(&format) {
|
||||
return Err(format!(
|
||||
"Format non supporté: {}. Formats valides: {:?}",
|
||||
format, allowed_formats
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user