Merge branch 'routes_web_block'

This commit is contained in:
Dessalines 2020-04-21 20:28:44 -04:00
commit 4abca69328
9 changed files with 38 additions and 30 deletions

View file

@ -69,7 +69,7 @@ impl<T> Oper<T> {
} }
pub trait Perform { pub trait Perform {
type Response: serde::ser::Serialize; type Response: serde::ser::Serialize + Send;
fn perform( fn perform(
&self, &self,

View file

@ -5,7 +5,6 @@ use crate::api::post::*;
use crate::api::site::*; use crate::api::site::*;
use crate::api::user::*; use crate::api::user::*;
use crate::rate_limit::RateLimit; use crate::rate_limit::RateLimit;
use actix_web::guard;
pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimit) { pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimit) {
cfg.service( cfg.service(
@ -140,13 +139,14 @@ pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimit) {
); );
} }
fn perform<Request>( async fn perform<Request>(
data: Request, data: Request,
db: DbPoolParam, db: DbPoolParam,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, Error> ) -> Result<HttpResponse, Error>
where where
Oper<Request>: Perform, Oper<Request>: Perform,
Request: Send + 'static,
{ {
let ws_info = WebsocketInfo { let ws_info = WebsocketInfo {
chatserver: chat_server.get_ref().to_owned(), chatserver: chat_server.get_ref().to_owned(),
@ -155,9 +155,11 @@ where
let oper: Oper<Request> = Oper::new(data); let oper: Oper<Request> = Oper::new(data);
let res = oper.perform(db.get_ref().to_owned(), Some(ws_info)); let res = web::block(move || oper.perform(db.get_ref().to_owned(), Some(ws_info)))
.await
Ok(HttpResponse::Ok().json(res?)) .map(|json| HttpResponse::Ok().json(json))
.map_err(ErrorBadRequest)?;
Ok(res)
} }
async fn route_get<Data>( async fn route_get<Data>(
@ -166,10 +168,10 @@ async fn route_get<Data>(
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, Error> ) -> Result<HttpResponse, Error>
where where
Data: Serialize, Data: Serialize + Send + 'static,
Oper<Data>: Perform, Oper<Data>: Perform,
{ {
perform::<Data>(data.0, db, chat_server) perform::<Data>(data.0, db, chat_server).await
} }
async fn route_post<Data>( async fn route_post<Data>(
@ -178,8 +180,8 @@ async fn route_post<Data>(
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, Error> ) -> Result<HttpResponse, Error>
where where
Data: Serialize, Data: Serialize + Send + 'static,
Oper<Data>: Perform, Oper<Data>: Perform,
{ {
perform::<Data>(data.0, db, chat_server) perform::<Data>(data.0, db, chat_server).await
} }

View file

@ -28,7 +28,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
async fn get_all_feed( async fn get_all_feed(
info: web::Query<Params>, info: web::Query<Params>,
db: web::Data<Pool<ConnectionManager<PgConnection>>>, db: web::Data<Pool<ConnectionManager<PgConnection>>>,
) -> Result<HttpResponse, actix_web::Error> { ) -> Result<HttpResponse, Error> {
let res = web::block(move || { let res = web::block(move || {
let conn = db.get()?; let conn = db.get()?;
get_feed_all_data(&conn, &get_sort_type(info)?) get_feed_all_data(&conn, &get_sort_type(info)?)
@ -39,7 +39,7 @@ async fn get_all_feed(
.content_type("application/rss+xml") .content_type("application/rss+xml")
.body(rss) .body(rss)
}) })
.map_err(|_| HttpResponse::InternalServerError())?; .map_err(ErrorBadRequest)?;
Ok(res) Ok(res)
} }
@ -70,7 +70,7 @@ async fn get_feed(
path: web::Path<(String, String)>, path: web::Path<(String, String)>,
info: web::Query<Params>, info: web::Query<Params>,
db: web::Data<Pool<ConnectionManager<PgConnection>>>, db: web::Data<Pool<ConnectionManager<PgConnection>>>,
) -> Result<HttpResponse, actix_web::Error> { ) -> Result<HttpResponse, Error> {
let res = web::block(move || { let res = web::block(move || {
let conn = db.get()?; let conn = db.get()?;
@ -100,7 +100,7 @@ async fn get_feed(
.content_type("application/rss+xml") .content_type("application/rss+xml")
.body(rss) .body(rss)
}) })
.map_err(|_| HttpResponse::InternalServerError())?; .map_err(ErrorBadRequest)?;
Ok(res) Ok(res)
} }
@ -116,7 +116,7 @@ fn get_feed_user(
conn: &PgConnection, conn: &PgConnection,
sort_type: &SortType, sort_type: &SortType,
user_name: String, user_name: String,
) -> Result<ChannelBuilder, Error> { ) -> Result<ChannelBuilder, failure::Error> {
let site_view = SiteView::read(&conn)?; let site_view = SiteView::read(&conn)?;
let user = User_::find_by_username(&conn, &user_name)?; let user = User_::find_by_username(&conn, &user_name)?;
let user_url = user.get_profile_url(); let user_url = user.get_profile_url();
@ -142,7 +142,7 @@ fn get_feed_community(
conn: &PgConnection, conn: &PgConnection,
sort_type: &SortType, sort_type: &SortType,
community_name: String, community_name: String,
) -> Result<ChannelBuilder, Error> { ) -> Result<ChannelBuilder, failure::Error> {
let site_view = SiteView::read(&conn)?; let site_view = SiteView::read(&conn)?;
let community = Community::read_from_name(&conn, community_name)?; let community = Community::read_from_name(&conn, community_name)?;
let community_url = community.get_url(); let community_url = community.get_url();
@ -172,7 +172,7 @@ fn get_feed_front(
conn: &PgConnection, conn: &PgConnection,
sort_type: &SortType, sort_type: &SortType,
jwt: String, jwt: String,
) -> Result<ChannelBuilder, Error> { ) -> Result<ChannelBuilder, failure::Error> {
let site_view = SiteView::read(&conn)?; let site_view = SiteView::read(&conn)?;
let user_id = Claims::decode(&jwt)?.claims.id; let user_id = Claims::decode(&jwt)?.claims.id;
@ -197,7 +197,7 @@ fn get_feed_front(
Ok(channel_builder) Ok(channel_builder)
} }
fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, Error> { fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, failure::Error> {
let site_view = SiteView::read(&conn)?; let site_view = SiteView::read(&conn)?;
let user_id = Claims::decode(&jwt)?.claims.id; let user_id = Claims::decode(&jwt)?.claims.id;

View file

@ -41,7 +41,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.route("/password_change/{token}", web::get().to(index)); .route("/password_change/{token}", web::get().to(index));
} }
async fn index() -> Result<NamedFile, actix_web::error::Error> { async fn index() -> Result<NamedFile, Error> {
Ok(NamedFile::open( Ok(NamedFile::open(
Settings::get().front_end_dir + "/index.html", Settings::get().front_end_dir + "/index.html",
)?) )?)

View file

@ -5,14 +5,13 @@ use crate::websocket::{server::ChatServer, WebsocketInfo};
use crate::{get_ip, markdown_to_html, version, Settings}; use crate::{get_ip, markdown_to_html, version, Settings};
use actix::prelude::*; use actix::prelude::*;
use actix_files::NamedFile; use actix_files::NamedFile;
use actix_web::{body::Body, web::Query, *}; use actix_web::{body::Body, error::ErrorBadRequest, web::Query, *};
use actix_web_actors::ws; use actix_web_actors::ws;
use chrono::{DateTime, NaiveDateTime, Utc}; use chrono::{DateTime, NaiveDateTime, Utc};
use diesel::{ use diesel::{
r2d2::{ConnectionManager, Pool}, r2d2::{ConnectionManager, Pool},
PgConnection, PgConnection,
}; };
use failure::Error;
use log::{error, info}; use log::{error, info};
use regex::Regex; use regex::Regex;
use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder}; use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder};

View file

@ -18,7 +18,7 @@ async fn node_info_well_known() -> HttpResponse<Body> {
async fn node_info( async fn node_info(
db: web::Data<Pool<ConnectionManager<PgConnection>>>, db: web::Data<Pool<ConnectionManager<PgConnection>>>,
) -> Result<HttpResponse, actix_web::Error> { ) -> Result<HttpResponse, Error> {
let res = web::block(move || { let res = web::block(move || {
let conn = db.get()?; let conn = db.get()?;
let site_view = match SiteView::read(&conn) { let site_view = match SiteView::read(&conn) {
@ -49,7 +49,7 @@ async fn node_info(
}) })
.await .await
.map(|json| HttpResponse::Ok().json(json)) .map(|json| HttpResponse::Ok().json(json))
.map_err(|_| HttpResponse::InternalServerError())?; .map_err(ErrorBadRequest)?;
Ok(res) Ok(res)
} }

View file

@ -32,7 +32,7 @@ lazy_static! {
async fn get_webfinger_response( async fn get_webfinger_response(
info: Query<Params>, info: Query<Params>,
db: web::Data<Pool<ConnectionManager<PgConnection>>>, db: web::Data<Pool<ConnectionManager<PgConnection>>>,
) -> Result<HttpResponse, actix_web::Error> { ) -> Result<HttpResponse, Error> {
let res = web::block(move || { let res = web::block(move || {
let conn = db.get()?; let conn = db.get()?;
@ -84,6 +84,6 @@ async fn get_webfinger_response(
}) })
.await .await
.map(|json| HttpResponse::Ok().json(json)) .map(|json| HttpResponse::Ok().json(json))
.map_err(|_| HttpResponse::InternalServerError())?; .map_err(ErrorBadRequest)?;
Ok(res) Ok(res)
} }

View file

@ -1,6 +1,5 @@
use super::*; use super::*;
use crate::websocket::server::*; use crate::websocket::server::*;
use actix_web::{Error, Result};
/// How often heartbeat pings are sent /// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
@ -120,7 +119,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WSSession {
.then(|res, _, ctx| { .then(|res, _, ctx| {
match res { match res {
Ok(Ok(res)) => ctx.text(res), Ok(Ok(res)) => ctx.text(res),
Ok(Err(e)) => match e {}, Ok(Err(_)) => {}
Err(e) => error!("{}", &e), Err(e) => error!("{}", &e),
} }
actix::fut::ready(()) actix::fut::ready(())

View file

@ -896,10 +896,18 @@ where
let data = data.to_string(); let data = data.to_string();
let op2 = op.clone(); let op2 = op.clone();
let fut = async move { let fut = async move {
let parsed_data: Data = serde_json::from_str(&data)?; actix_web::web::block(move || {
let res = Oper::new(parsed_data).perform(pool, Some(ws_info))?; let parsed_data: Data = serde_json::from_str(&data)?;
to_json_string(&op, &res) let res = Oper::new(parsed_data).perform(pool, Some(ws_info))?;
to_json_string(&op, &res)
})
.await
.map_err(|e| match e {
actix_web::error::BlockingError::Error(e) => e,
_ => APIError::err("Operation canceled").into(),
})
}; };
match op2 { match op2 {