2024-12-05 19:54:34 +01:00
|
|
|
use crate::api::model::app_state::AppState;
|
|
|
|
|
use crate::api::model::request::UserApiRequest;
|
|
|
|
|
use crate::api::model::shared_stream::{NotifyStream, SharedStream};
|
2024-05-03 01:47:41 +02:00
|
|
|
use crate::model::api_proxy::{ApiProxyServerInfo, ProxyUserCredentials};
|
2024-12-05 19:54:34 +01:00
|
|
|
use crate::model::config::{Config, ConfigInput, ConfigTarget};
|
2024-04-01 18:02:02 +02:00
|
|
|
use crate::utils::request_utils;
|
2024-11-10 14:17:24 +01:00
|
|
|
use crate::utils::request_utils::mask_sensitive_info;
|
2024-12-05 19:54:34 +01:00
|
|
|
use actix_web::http::header::{HeaderValue, CACHE_CONTROL};
|
|
|
|
|
use actix_web::{HttpRequest, HttpResponse};
|
2024-12-06 17:05:53 +01:00
|
|
|
use async_std::prelude::Stream;
|
|
|
|
|
use async_std::stream::StreamExt;
|
|
|
|
|
use bytes::Bytes;
|
2024-12-05 19:54:34 +01:00
|
|
|
use log::{debug, error, log_enabled, Level};
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
use std::path::Path;
|
|
|
|
|
use std::sync::atomic::AtomicU32;
|
2024-12-06 17:05:53 +01:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
use tokio_stream::wrappers::BroadcastStream;
|
2024-12-05 19:54:34 +01:00
|
|
|
use url::Url;
|
2023-10-20 12:18:44 +02:00
|
|
|
|
2024-11-04 18:46:56 +01:00
|
|
|
pub async fn serve_file(file_path: &Path, req: &HttpRequest, mime_type: mime::Mime) -> HttpResponse {
|
2023-10-20 12:18:44 +02:00
|
|
|
if file_path.exists() {
|
2023-12-01 21:38:23 +01:00
|
|
|
if let Ok(file) = actix_files::NamedFile::open_async(file_path).await {
|
2024-04-01 16:49:12 +02:00
|
|
|
let mut result = file.set_content_type(mime_type)
|
2023-12-01 21:38:23 +01:00
|
|
|
.disable_content_disposition().into_response(req);
|
|
|
|
|
let headers = result.headers_mut();
|
2024-11-04 18:46:56 +01:00
|
|
|
headers.insert(CACHE_CONTROL, HeaderValue::from_bytes(b"no-cache").unwrap());
|
2023-12-01 21:38:23 +01:00
|
|
|
return result;
|
|
|
|
|
}
|
2023-10-20 12:18:44 +02:00
|
|
|
}
|
2023-12-01 21:38:23 +01:00
|
|
|
HttpResponse::NoContent().finish()
|
2023-10-23 09:58:36 +02:00
|
|
|
}
|
|
|
|
|
|
2024-11-04 18:46:56 +01:00
|
|
|
pub fn get_user_target_by_credentials<'a>(username: &str, password: &str, api_req: &'a UserApiRequest,
|
2024-12-05 19:54:34 +01:00
|
|
|
app_state: &'a AppState) -> Option<(ProxyUserCredentials, &'a ConfigTarget)> {
|
2023-10-23 09:58:36 +02:00
|
|
|
if !username.is_empty() && !password.is_empty() {
|
2023-12-01 21:38:23 +01:00
|
|
|
app_state.config.get_target_for_user(username, password)
|
2023-10-23 09:58:36 +02:00
|
|
|
} else {
|
2023-10-25 21:07:38 +02:00
|
|
|
let token = api_req.token.as_str().trim();
|
2024-05-10 12:01:48 +02:00
|
|
|
if token.is_empty() {
|
2023-10-23 09:58:36 +02:00
|
|
|
None
|
2024-05-10 12:01:48 +02:00
|
|
|
} else {
|
|
|
|
|
app_state.config.get_target_for_user_by_token(token)
|
2023-10-23 09:58:36 +02:00
|
|
|
}
|
|
|
|
|
}
|
2023-11-22 21:06:58 +01:00
|
|
|
}
|
|
|
|
|
|
2024-12-03 14:54:42 +01:00
|
|
|
pub fn get_user_target<'a>(api_req: &'a UserApiRequest, app_state: &'a AppState) -> Option<(ProxyUserCredentials, &'a ConfigTarget)> {
|
2023-11-22 21:06:58 +01:00
|
|
|
let username = api_req.username.as_str().trim();
|
|
|
|
|
let password = api_req.password.as_str().trim();
|
|
|
|
|
get_user_target_by_credentials(username, password, api_req, app_state)
|
2024-04-01 16:49:12 +02:00
|
|
|
}
|
|
|
|
|
|
2024-11-04 18:46:56 +01:00
|
|
|
pub fn get_user_server_info(cfg: &Config, user: &ProxyUserCredentials) -> ApiProxyServerInfo {
|
2024-05-10 12:01:48 +02:00
|
|
|
let server_info_list = cfg.t_api_proxy.read().unwrap().as_ref().unwrap().server.clone();
|
2024-11-04 18:46:56 +01:00
|
|
|
let server_info_name = user.server.as_ref().map_or("default", |server_name| server_name.as_str());
|
|
|
|
|
server_info_list.iter().find(|c| c.name.eq(server_info_name)).map_or_else(|| server_info_list.first().unwrap().clone(), std::clone::Clone::clone)
|
2024-04-01 18:02:02 +02:00
|
|
|
}
|
|
|
|
|
|
2024-12-06 17:05:53 +01:00
|
|
|
async fn create_notify_stream(app_state: &AppState, stream_url: &str) -> Option<NotifyStream<BroadcastStream<Bytes>>> {
|
|
|
|
|
let notify_stream_url = stream_url.to_string();
|
|
|
|
|
let shared_streams_map = app_state.shared_streams.clone();
|
|
|
|
|
let shared_streams = shared_streams_map.lock().await;
|
|
|
|
|
if let Some(shared_stream) = shared_streams.get(¬ify_stream_url) {
|
|
|
|
|
let rx = shared_stream.data_stream.subscribe();
|
|
|
|
|
drop(shared_streams);
|
|
|
|
|
let (stream, notify) = NotifyStream::new(tokio_stream::wrappers::BroadcastStream::new(rx));
|
|
|
|
|
actix_rt::spawn(async move {
|
|
|
|
|
let _ = notify.await;
|
|
|
|
|
let mut shared_streams = shared_streams_map.lock().await;
|
|
|
|
|
if let Some(shared_stream) = shared_streams.get(¬ify_stream_url) {
|
|
|
|
|
let cur_count = shared_stream.client_count.fetch_sub(1u32, std::sync::atomic::Ordering::SeqCst);
|
|
|
|
|
if cur_count == 1 {
|
|
|
|
|
shared_streams.remove(¬ify_stream_url);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
return Some(stream);
|
|
|
|
|
}
|
|
|
|
|
drop(shared_streams);
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn create_shared_stream<S, E>(app_state: &AppState, bytes_stream: S, stream_url: &str)
|
|
|
|
|
where
|
|
|
|
|
S: Stream<Item=Result<Bytes, E>> + Unpin + 'static,
|
|
|
|
|
{
|
|
|
|
|
let (tx, _) = tokio::sync::broadcast::channel(1);
|
|
|
|
|
let sender = Arc::new(tx);
|
|
|
|
|
let _ = app_state.shared_streams.lock().await.insert(
|
|
|
|
|
stream_url.to_string(),
|
|
|
|
|
SharedStream {
|
|
|
|
|
data_stream: sender.clone(),
|
|
|
|
|
client_count: AtomicU32::new(1),
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
let mut source_stream = Box::pin(bytes_stream);
|
|
|
|
|
actix_rt::spawn(async move {
|
|
|
|
|
while let Some(Ok(item)) = source_stream.next().await {
|
|
|
|
|
if sender.send(item).is_err() {
|
|
|
|
|
// ignore
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-05 19:57:13 +01:00
|
|
|
pub async fn stream_response(app_state: &AppState, stream_url: &str, req: &HttpRequest, input: Option<&ConfigInput>, share_stream: bool) -> HttpResponse {
|
2024-04-01 18:02:02 +02:00
|
|
|
let req_headers: HashMap<&str, &[u8]> = req.headers().iter().map(|(k, v)| (k.as_str(), v.as_bytes())).collect();
|
2024-12-03 14:49:23 +01:00
|
|
|
if log_enabled!(Level::Debug) {
|
|
|
|
|
debug!("Try to open stream {}", mask_sensitive_info(stream_url));
|
|
|
|
|
}
|
2024-12-05 19:57:13 +01:00
|
|
|
if share_stream {
|
2024-12-06 17:05:53 +01:00
|
|
|
let shared_streams = app_state.shared_streams.lock().await;
|
|
|
|
|
if let Some(shared_stream) = shared_streams.get(stream_url) {
|
|
|
|
|
shared_stream.client_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
2024-12-05 19:54:34 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-01 18:02:02 +02:00
|
|
|
if let Ok(url) = Url::parse(stream_url) {
|
2024-09-23 16:51:50 +02:00
|
|
|
let client = request_utils::get_client_request(input, &url, Some(&req_headers));
|
2024-04-01 18:02:02 +02:00
|
|
|
match client.send().await {
|
|
|
|
|
Ok(response) => {
|
2024-12-06 17:05:53 +01:00
|
|
|
let status = response.status();
|
|
|
|
|
if status.is_success() {
|
2024-04-01 18:02:02 +02:00
|
|
|
let mut response_builder = HttpResponse::Ok();
|
|
|
|
|
response.headers().iter().for_each(|(k, v)| {
|
|
|
|
|
response_builder.insert_header((k.as_str(), v.as_ref()));
|
|
|
|
|
});
|
2024-12-06 17:05:53 +01:00
|
|
|
if share_stream {
|
|
|
|
|
create_shared_stream(app_state, response.bytes_stream(), stream_url).await;
|
|
|
|
|
if let Some(stream) = create_notify_stream(app_state, stream_url).await {
|
|
|
|
|
return response_builder.body(actix_web::body::BodyStream::new(stream));
|
|
|
|
|
}
|
2024-12-05 19:57:13 +01:00
|
|
|
} else {
|
2024-12-06 17:05:53 +01:00
|
|
|
return response_builder.body(actix_web::body::BodyStream::new(response.bytes_stream()));
|
|
|
|
|
}
|
2024-04-01 18:02:02 +02:00
|
|
|
}
|
2024-12-03 14:49:23 +01:00
|
|
|
if log_enabled!(Level::Debug) {
|
2024-12-06 17:05:53 +01:00
|
|
|
debug!("Failed to open stream got status {} for {}", status, mask_sensitive_info(stream_url));
|
2024-12-03 14:49:23 +01:00
|
|
|
}
|
2024-04-01 18:02:02 +02:00
|
|
|
}
|
|
|
|
|
Err(err) => {
|
2024-11-10 14:17:24 +01:00
|
|
|
error!("Received failure from server {}: {}", mask_sensitive_info(stream_url), err);
|
2024-04-01 18:02:02 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
2024-11-10 14:17:24 +01:00
|
|
|
error!("Url is malformed {}", mask_sensitive_info(stream_url));
|
2024-04-01 18:02:02 +02:00
|
|
|
}
|
|
|
|
|
HttpResponse::BadRequest().finish()
|
2024-04-02 17:00:28 +02:00
|
|
|
}
|