use crate::api::api_error;
use crate::api::authorize_request;
use crate::api::ok_json_with_trace;
use crate::api::parse_json_payload;
use crate::api::BearerToken;
use crate::core::network_analyzer::{ConnectionType, NetworkInfoProvider};
use crate::AppState;
use actix_web::http::StatusCode;
use actix_web::{post, web, HttpRequest, Responder};
use serde::Deserialize;
use std::net::IpAddr;
struct SimpleProvider {
ip: IpAddr,
conn_type: ConnectionType,
}
#[async_trait::async_trait]
impl NetworkInfoProvider for SimpleProvider {
async fn get_connection_type(&self) -> ConnectionType {
self.conn_type.clone()
}
async fn get_public_ip(&self) -> Option<IpAddr> {
Some(self.ip)
}
}
#[derive(Deserialize)]
pub struct NetworkAnalyzeRequest {
pub ip: IpAddr, pub conn_type: ConnectionType, }
#[post("/network/analyze")]
pub async fn analyze_network(
app_data: web::Data<AppState>,
req: HttpRequest,
bearer: BearerToken,
payload_bytes: web::Bytes,
) -> impl Responder {
if let Err(resp) = authorize_request(&app_data, &req, &bearer, &payload_bytes).await {
return resp;
}
let payload: NetworkAnalyzeRequest = match parse_json_payload(&payload_bytes) {
Ok(v) => v,
Err(resp) => return resp,
};
let provider = SimpleProvider {
ip: payload.ip,
conn_type: payload.conn_type.clone(),
};
let engine = &app_data.x_engine.network_engine;
match engine.analyze(&provider).await {
Ok(result) => ok_json_with_trace(&req, result),
Err(_) => api_error(
StatusCode::INTERNAL_SERVER_ERROR,
"NETWORK_ANALYSIS_INTERNAL_ERROR",
"Internal error while analyzing network",
),
}
}