1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2024-11-22 13:29:21 +00:00

Update actix

This commit is contained in:
Pierre HUBERT 2022-03-09 19:58:46 +01:00
parent 4aa7657e28
commit c874d1c964
7 changed files with 404 additions and 1005 deletions

1312
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -9,13 +9,12 @@ edition = "2018"
[dependencies] [dependencies]
yaml-rust = "0.4.5" yaml-rust = "0.4.5"
mysql = "22.1.0" mysql = "22.1.0"
actix = "0.10.0" actix = "0.13.0"
actix-web = "3.3.2" actix-web = "4.0.1"
actix-files = "0.5.0" actix-files = "0.6.0"
actix-rt = "1.1.1" actix-multipart = "0.4.0"
actix-multipart = "0.3.0" actix-web-actors = "4.1.0"
actix-web-actors = "3.0.0" actix-http = "3.0.2"
actix-http = "2.2.0"
serde = { version = "1.0.123", features = ["derive"] } serde = { version = "1.0.123", features = ["derive"] }
serde_json = "1.0.62" serde_json = "1.0.62"
futures = "0.3.12" futures = "0.3.12"
@ -41,6 +40,5 @@ mp4 = "0.9.2"
zip = "0.5.10" zip = "0.5.10"
webpage = "1.2.0" webpage = "1.2.0"
gouth = "0.2.0" gouth = "0.2.0"
tokio = { version = "0.2" }
webauthn-rs = "0.3.2" webauthn-rs = "0.3.2"
url = "2.2.2" url = "2.2.2"

View File

@ -4,6 +4,7 @@
use actix::{ActorContext, Addr, AsyncContext, Handler, StreamHandler}; use actix::{ActorContext, Addr, AsyncContext, Handler, StreamHandler};
use actix::prelude::*; use actix::prelude::*;
use actix_http::ws::Item;
use actix_web_actors::ws::{Message, ProtocolError}; use actix_web_actors::ws::{Message, ProtocolError};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
@ -14,7 +15,6 @@ use crate::data::error::{ExecError, Res};
use crate::helpers::events_helper; use crate::helpers::events_helper;
use crate::helpers::events_helper::Event; use crate::helpers::events_helper::Event;
use crate::utils::network_utils::match_ip; use crate::utils::network_utils::match_ip;
use actix_http::ws::Item;
#[derive(Default)] #[derive(Default)]
struct RtcRelayActor { struct RtcRelayActor {

View File

@ -1,9 +1,9 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr; use std::str::FromStr;
use actix_http::header::{HeaderName, HeaderValue};
use actix_web::{HttpRequest, HttpResponse, web}; use actix_web::{HttpRequest, HttpResponse, HttpResponseBuilder};
use actix_web::dev::HttpResponseBuilder; use actix_web::http::StatusCode;
use actix_web::http::{HeaderName, HeaderValue, StatusCode};
use serde::Serialize; use serde::Serialize;
use crate::api_data::http_error::HttpError; use crate::api_data::http_error::HttpError;
@ -22,9 +22,9 @@ use crate::utils::network_utils::match_ip;
/// @author Pierre Hubert /// @author Pierre Hubert
pub struct HttpRequestHandler { pub struct HttpRequestHandler {
request: web::HttpRequest, request: HttpRequest,
body: HashMap<String, RequestValue>, body: HashMap<String, RequestValue>,
response: Option<web::HttpResponse>, response: Option<HttpResponse>,
headers: HashMap<String, String>, headers: HashMap<String, String>,
client: Option<APIClient>, client: Option<APIClient>,
curr_user_token: Option<UserAccessToken>, curr_user_token: Option<UserAccessToken>,

View File

@ -3,7 +3,8 @@
//! @author Pierre Hubert //! @author Pierre Hubert
use actix_web::http::{HeaderValue, StatusCode}; use actix_http::header::HeaderValue;
use actix_web::http::StatusCode;
use reqwest::blocking::Client; use reqwest::blocking::Client;
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -14,7 +15,7 @@ use crate::data::push_notification::PushNotification;
#[derive(Deserialize)] #[derive(Deserialize)]
struct CreateTokenResult { struct CreateTokenResult {
token: String token: String,
} }
#[derive(Serialize)] #[derive(Serialize)]

View File

@ -89,12 +89,12 @@ fn get_actions() -> Vec<Action> {
description: "Grant a role to an admin", description: "Grant a role to an admin",
arguments: vec!["mail", "role_id"], arguments: vec!["mail", "role_id"],
function: Box::new(grant_admin_role), function: Box::new(grant_admin_role),
} },
] ]
} }
#[actix_rt::main]
async fn main() -> std::io::Result<()> { fn main() {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
let conf_file = match args.get(1) { let conf_file = match args.get(1) {
Some(el) => el.to_string(), Some(el) => el.to_string(),
@ -144,30 +144,15 @@ async fn main() -> std::io::Result<()> {
let res = (selected_action.function)(args.to_vec()); let res = (selected_action.function)(args.to_vec());
res.expect("Failed to execute action!"); res.expect("Failed to execute action!");
Ok(())
} }
/// Start Comunic Server (main action) /// Start Comunic Server (main action)
fn serve(_a: Vec<String>) -> Res { fn serve(_a: Vec<String>) -> Res {
let t = std::thread::spawn(|| {
let sys = actix::System::new("sys");
let promise = async {
// Start cleanup thread // Start cleanup thread
cleanup_thread::start().expect("Failed to start cleanup thread!"); cleanup_thread::start().expect("Failed to start cleanup thread!");
// Start the server // Start the server
server::start_server(conf()).await Ok(server::start_server(conf())?)
};
tokio::runtime::Runtime::new().unwrap().block_on(promise)
.expect("Failed to start server!");
let _ = sys.run();
});
t.join().unwrap();
Ok(())
} }
fn help(_a: Vec<String>) -> Res { fn help(_a: Vec<String>) -> Res {

View File

@ -2,9 +2,9 @@ use std::collections::HashMap;
use std::pin::Pin; use std::pin::Pin;
use actix_web::{App, FromRequest, http, HttpMessage, HttpRequest, HttpResponse, HttpServer, web}; use actix_web::{App, FromRequest, http, HttpMessage, HttpRequest, HttpResponse, HttpServer, web};
use actix_web::dev::{Decompress, Payload, PayloadStream}; use actix_web::dev::{Decompress, Payload};
use actix_web::error::{ErrorBadRequest, ErrorInternalServerError, PayloadError}; use actix_web::error::{ErrorBadRequest, ErrorInternalServerError, PayloadError};
use actix_web::web::{Buf, BufMut, Bytes, BytesMut}; use actix_web::web::{BufMut, Bytes, BytesMut};
use encoding_rs::UTF_8; use encoding_rs::UTF_8;
use futures::{FutureExt, Stream, StreamExt}; use futures::{FutureExt, Stream, StreamExt};
use futures::future::LocalBoxFuture; use futures::future::LocalBoxFuture;
@ -54,7 +54,7 @@ impl<'a> Stream for LimitedStream
/// Custom request value /// Custom request value
struct CustomRequest { struct CustomRequest {
req: web::HttpRequest, req: HttpRequest,
body: HashMap<String, RequestValue>, body: HashMap<String, RequestValue>,
} }
@ -62,9 +62,8 @@ struct CustomRequest {
impl FromRequest for CustomRequest { impl FromRequest for CustomRequest {
type Error = actix_web::Error; type Error = actix_web::Error;
type Future = LocalBoxFuture<'static, Result<CustomRequest, actix_web::Error>>; type Future = LocalBoxFuture<'static, Result<CustomRequest, actix_web::Error>>;
type Config = ();
fn from_request(req: &HttpRequest, payload: &mut Payload<PayloadStream>) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req = req.clone(); let req = req.clone();
let payload = Box::new(payload.take()); let payload = Box::new(payload.take());
@ -159,8 +158,7 @@ impl FromRequest for CustomRequest {
while let Some(el) = req.next().await { while let Some(el) = req.next().await {
let mut field = el?; let mut field = el?;
let content_type = field.content_disposition().ok_or( let content_type = field.content_disposition().clone();
ErrorInternalServerError("Missing content type"))?;
let name = content_type.get_name().ok_or( let name = content_type.get_name().ok_or(
ErrorInternalServerError("Missing field name!"))?; ErrorInternalServerError("Missing field name!"))?;
@ -177,7 +175,7 @@ impl FromRequest for CustomRequest {
body_args.insert(name.to_string(), body_args.insert(name.to_string(),
RequestValue::File(PostFile { RequestValue::File(PostFile {
name: filename.to_string(), name: filename.to_string(),
buff: buf.to_bytes(), buff: buf.freeze(),
})); }));
} }
@ -187,7 +185,7 @@ impl FromRequest for CustomRequest {
// Get content // Get content
while let Some(chunk) = field.next().await { while let Some(chunk) = field.next().await {
content = format!("{}{}", content, String::from_utf8_lossy(chunk?.bytes())); content = format!("{}{}", content, String::from_utf8_lossy(chunk?.as_ref()));
} }
body_args.insert(name.to_string(), RequestValue::String(content)); body_args.insert(name.to_string(), RequestValue::String(content));
@ -342,14 +340,15 @@ async fn handle_options_request(r: HttpRequest) -> HttpResponse {
// Accept request // Accept request
HttpResponse::NoContent() HttpResponse::NoContent()
.header("Access-Control-Allow-Origin", origin) .append_header(("Access-Control-Allow-Origin", origin))
.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") .append_header(("Access-Control-Allow-Methods", "POST, GET, OPTIONS"))
.finish() .finish()
} }
/// Given the configuration, start the server /// Given the configuration, start the server
pub async fn start_server(conf: &Config) -> std::io::Result<()> { pub fn start_server(conf: &Config) -> std::io::Result<()> {
let sys = actix::System::new();
// Initialize limit helper // Initialize limit helper
requests_limit_helper::init(); requests_limit_helper::init();
@ -362,7 +361,7 @@ pub async fn start_server(conf: &Config) -> std::io::Result<()> {
let serve_storage_file = conf.serve_storage_file; let serve_storage_file = conf.serve_storage_file;
HttpServer::new(move || { let server = HttpServer::new(move || {
let mut app = App::new(); let mut app = App::new();
if serve_storage_file { if serve_storage_file {
@ -376,10 +375,14 @@ pub async fn start_server(conf: &Config) -> std::io::Result<()> {
.service(actix_web::web::resource("/rtc_proxy/ws").to(rtc_relay_controller::open_ws)) .service(actix_web::web::resource("/rtc_proxy/ws").to(rtc_relay_controller::open_ws))
// Option // Option
.route("**", web::method(http::Method::OPTIONS).to(handle_options_request)) .route("{tail:.*}", web::method(http::Method::OPTIONS).to(handle_options_request))
// API routes // API routes
.route("**", web::get().to(process_request)) .route("{tail:.*}", web::get().to(process_request))
.route("**", web::post().to(process_request)) .route("{tail:.*}", web::post().to(process_request))
}).bind(&addr)?.run().await }).bind(&addr)?.run();
sys.block_on(server)?;
Ok(())
} }