Trying to add r2d2 connection pooling to websockets.

pull/722/head
Dessalines 2020-01-12 10:31:51 -05:00
parent 677d716ae6
commit dff8b947bb
25 changed files with 308 additions and 287 deletions

View File

@ -1,6 +1,7 @@
use super::*; use super::*;
use crate::send_email; use crate::send_email;
use crate::settings::Settings; use crate::settings::Settings;
use diesel::PgConnection;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct CreateComment { pub struct CreateComment {
@ -47,9 +48,8 @@ pub struct CreateCommentLike {
} }
impl Perform<CommentResponse> for Oper<CreateComment> { impl Perform<CommentResponse> for Oper<CreateComment> {
fn perform(&self) -> Result<CommentResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommentResponse, Error> {
let data: &CreateComment = &self.data; let data: &CreateComment = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -206,9 +206,8 @@ impl Perform<CommentResponse> for Oper<CreateComment> {
} }
impl Perform<CommentResponse> for Oper<EditComment> { impl Perform<CommentResponse> for Oper<EditComment> {
fn perform(&self) -> Result<CommentResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommentResponse, Error> {
let data: &EditComment = &self.data; let data: &EditComment = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -318,9 +317,8 @@ impl Perform<CommentResponse> for Oper<EditComment> {
} }
impl Perform<CommentResponse> for Oper<SaveComment> { impl Perform<CommentResponse> for Oper<SaveComment> {
fn perform(&self) -> Result<CommentResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommentResponse, Error> {
let data: &SaveComment = &self.data; let data: &SaveComment = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -356,9 +354,8 @@ impl Perform<CommentResponse> for Oper<SaveComment> {
} }
impl Perform<CommentResponse> for Oper<CreateCommentLike> { impl Perform<CommentResponse> for Oper<CreateCommentLike> {
fn perform(&self) -> Result<CommentResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommentResponse, Error> {
let data: &CreateCommentLike = &self.data; let data: &CreateCommentLike = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,

View File

@ -1,4 +1,5 @@
use super::*; use super::*;
use diesel::PgConnection;
use std::str::FromStr; use std::str::FromStr;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -118,9 +119,8 @@ pub struct TransferCommunity {
} }
impl Perform<GetCommunityResponse> for Oper<GetCommunity> { impl Perform<GetCommunityResponse> for Oper<GetCommunity> {
fn perform(&self) -> Result<GetCommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetCommunityResponse, Error> {
let data: &GetCommunity = &self.data; let data: &GetCommunity = &self.data;
let conn = establish_connection();
let user_id: Option<i32> = match &data.auth { let user_id: Option<i32> = match &data.auth {
Some(auth) => match Claims::decode(&auth) { Some(auth) => match Claims::decode(&auth) {
@ -173,9 +173,8 @@ impl Perform<GetCommunityResponse> for Oper<GetCommunity> {
} }
impl Perform<CommunityResponse> for Oper<CreateCommunity> { impl Perform<CommunityResponse> for Oper<CreateCommunity> {
fn perform(&self) -> Result<CommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommunityResponse, Error> {
let data: &CreateCommunity = &self.data; let data: &CreateCommunity = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -248,15 +247,13 @@ impl Perform<CommunityResponse> for Oper<CreateCommunity> {
} }
impl Perform<CommunityResponse> for Oper<EditCommunity> { impl Perform<CommunityResponse> for Oper<EditCommunity> {
fn perform(&self) -> Result<CommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommunityResponse, Error> {
let data: &EditCommunity = &self.data; let data: &EditCommunity = &self.data;
if has_slurs(&data.name) || has_slurs(&data.title) { if has_slurs(&data.name) || has_slurs(&data.title) {
return Err(APIError::err(&self.op, "no_slurs").into()); return Err(APIError::err(&self.op, "no_slurs").into());
} }
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()), Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()),
@ -325,9 +322,8 @@ impl Perform<CommunityResponse> for Oper<EditCommunity> {
} }
impl Perform<ListCommunitiesResponse> for Oper<ListCommunities> { impl Perform<ListCommunitiesResponse> for Oper<ListCommunities> {
fn perform(&self) -> Result<ListCommunitiesResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<ListCommunitiesResponse, Error> {
let data: &ListCommunities = &self.data; let data: &ListCommunities = &self.data;
let conn = establish_connection();
let user_claims: Option<Claims> = match &data.auth { let user_claims: Option<Claims> = match &data.auth {
Some(auth) => match Claims::decode(&auth) { Some(auth) => match Claims::decode(&auth) {
@ -366,9 +362,8 @@ impl Perform<ListCommunitiesResponse> for Oper<ListCommunities> {
} }
impl Perform<CommunityResponse> for Oper<FollowCommunity> { impl Perform<CommunityResponse> for Oper<FollowCommunity> {
fn perform(&self) -> Result<CommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CommunityResponse, Error> {
let data: &FollowCommunity = &self.data; let data: &FollowCommunity = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -404,9 +399,8 @@ impl Perform<CommunityResponse> for Oper<FollowCommunity> {
} }
impl Perform<GetFollowedCommunitiesResponse> for Oper<GetFollowedCommunities> { impl Perform<GetFollowedCommunitiesResponse> for Oper<GetFollowedCommunities> {
fn perform(&self) -> Result<GetFollowedCommunitiesResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetFollowedCommunitiesResponse, Error> {
let data: &GetFollowedCommunities = &self.data; let data: &GetFollowedCommunities = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -430,9 +424,8 @@ impl Perform<GetFollowedCommunitiesResponse> for Oper<GetFollowedCommunities> {
} }
impl Perform<BanFromCommunityResponse> for Oper<BanFromCommunity> { impl Perform<BanFromCommunityResponse> for Oper<BanFromCommunity> {
fn perform(&self) -> Result<BanFromCommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<BanFromCommunityResponse, Error> {
let data: &BanFromCommunity = &self.data; let data: &BanFromCommunity = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -485,9 +478,8 @@ impl Perform<BanFromCommunityResponse> for Oper<BanFromCommunity> {
} }
impl Perform<AddModToCommunityResponse> for Oper<AddModToCommunity> { impl Perform<AddModToCommunityResponse> for Oper<AddModToCommunity> {
fn perform(&self) -> Result<AddModToCommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<AddModToCommunityResponse, Error> {
let data: &AddModToCommunity = &self.data; let data: &AddModToCommunity = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -536,9 +528,8 @@ impl Perform<AddModToCommunityResponse> for Oper<AddModToCommunity> {
} }
impl Perform<GetCommunityResponse> for Oper<TransferCommunity> { impl Perform<GetCommunityResponse> for Oper<TransferCommunity> {
fn perform(&self) -> Result<GetCommunityResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetCommunityResponse, Error> {
let data: &TransferCommunity = &self.data; let data: &TransferCommunity = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,

View File

@ -16,6 +16,7 @@ use crate::db::user_mention_view::*;
use crate::db::user_view::*; use crate::db::user_view::*;
use crate::db::*; use crate::db::*;
use crate::{extract_usernames, has_slurs, naive_from_unix, naive_now, remove_slurs}; use crate::{extract_usernames, has_slurs, naive_from_unix, naive_now, remove_slurs};
use diesel::PgConnection;
use failure::Error; use failure::Error;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -96,7 +97,7 @@ impl<T> Oper<T> {
} }
pub trait Perform<T> { pub trait Perform<T> {
fn perform(&self) -> Result<T, Error> fn perform(&self, conn: &PgConnection) -> Result<T, Error>
where where
T: Sized; T: Sized;
} }

View File

@ -1,4 +1,5 @@
use super::*; use super::*;
use diesel::PgConnection;
use std::str::FromStr; use std::str::FromStr;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -87,9 +88,8 @@ pub struct SavePost {
} }
impl Perform<PostResponse> for Oper<CreatePost> { impl Perform<PostResponse> for Oper<CreatePost> {
fn perform(&self) -> Result<PostResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<PostResponse, Error> {
let data: &CreatePost = &self.data; let data: &CreatePost = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -158,9 +158,8 @@ impl Perform<PostResponse> for Oper<CreatePost> {
} }
impl Perform<GetPostResponse> for Oper<GetPost> { impl Perform<GetPostResponse> for Oper<GetPost> {
fn perform(&self) -> Result<GetPostResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetPostResponse, Error> {
let data: &GetPost = &self.data; let data: &GetPost = &self.data;
let conn = establish_connection();
let user_id: Option<i32> = match &data.auth { let user_id: Option<i32> = match &data.auth {
Some(auth) => match Claims::decode(&auth) { Some(auth) => match Claims::decode(&auth) {
@ -207,9 +206,8 @@ impl Perform<GetPostResponse> for Oper<GetPost> {
} }
impl Perform<GetPostsResponse> for Oper<GetPosts> { impl Perform<GetPostsResponse> for Oper<GetPosts> {
fn perform(&self) -> Result<GetPostsResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetPostsResponse, Error> {
let data: &GetPosts = &self.data; let data: &GetPosts = &self.data;
let conn = establish_connection();
let user_claims: Option<Claims> = match &data.auth { let user_claims: Option<Claims> = match &data.auth {
Some(auth) => match Claims::decode(&auth) { Some(auth) => match Claims::decode(&auth) {
@ -254,9 +252,8 @@ impl Perform<GetPostsResponse> for Oper<GetPosts> {
} }
impl Perform<CreatePostLikeResponse> for Oper<CreatePostLike> { impl Perform<CreatePostLikeResponse> for Oper<CreatePostLike> {
fn perform(&self) -> Result<CreatePostLikeResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<CreatePostLikeResponse, Error> {
let data: &CreatePostLike = &self.data; let data: &CreatePostLike = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -316,14 +313,12 @@ impl Perform<CreatePostLikeResponse> for Oper<CreatePostLike> {
} }
impl Perform<PostResponse> for Oper<EditPost> { impl Perform<PostResponse> for Oper<EditPost> {
fn perform(&self) -> Result<PostResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<PostResponse, Error> {
let data: &EditPost = &self.data; let data: &EditPost = &self.data;
if has_slurs(&data.name) || (data.body.is_some() && has_slurs(&data.body.to_owned().unwrap())) { if has_slurs(&data.name) || (data.body.is_some() && has_slurs(&data.body.to_owned().unwrap())) {
return Err(APIError::err(&self.op, "no_slurs").into()); return Err(APIError::err(&self.op, "no_slurs").into());
} }
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()), Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()),
@ -412,9 +407,8 @@ impl Perform<PostResponse> for Oper<EditPost> {
} }
impl Perform<PostResponse> for Oper<SavePost> { impl Perform<PostResponse> for Oper<SavePost> {
fn perform(&self) -> Result<PostResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<PostResponse, Error> {
let data: &SavePost = &self.data; let data: &SavePost = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,

View File

@ -1,4 +1,5 @@
use super::*; use super::*;
use diesel::PgConnection;
use std::str::FromStr; use std::str::FromStr;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -97,9 +98,8 @@ pub struct TransferSite {
} }
impl Perform<ListCategoriesResponse> for Oper<ListCategories> { impl Perform<ListCategoriesResponse> for Oper<ListCategories> {
fn perform(&self) -> Result<ListCategoriesResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<ListCategoriesResponse, Error> {
let _data: &ListCategories = &self.data; let _data: &ListCategories = &self.data;
let conn = establish_connection();
let categories: Vec<Category> = Category::list_all(&conn)?; let categories: Vec<Category> = Category::list_all(&conn)?;
@ -112,9 +112,8 @@ impl Perform<ListCategoriesResponse> for Oper<ListCategories> {
} }
impl Perform<GetModlogResponse> for Oper<GetModlog> { impl Perform<GetModlogResponse> for Oper<GetModlog> {
fn perform(&self) -> Result<GetModlogResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetModlogResponse, Error> {
let data: &GetModlog = &self.data; let data: &GetModlog = &self.data;
let conn = establish_connection();
let removed_posts = ModRemovePostView::list( let removed_posts = ModRemovePostView::list(
&conn, &conn,
@ -187,9 +186,8 @@ impl Perform<GetModlogResponse> for Oper<GetModlog> {
} }
impl Perform<SiteResponse> for Oper<CreateSite> { impl Perform<SiteResponse> for Oper<CreateSite> {
fn perform(&self) -> Result<SiteResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<SiteResponse, Error> {
let data: &CreateSite = &self.data; let data: &CreateSite = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -234,9 +232,8 @@ impl Perform<SiteResponse> for Oper<CreateSite> {
} }
impl Perform<SiteResponse> for Oper<EditSite> { impl Perform<SiteResponse> for Oper<EditSite> {
fn perform(&self) -> Result<SiteResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<SiteResponse, Error> {
let data: &EditSite = &self.data; let data: &EditSite = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -283,9 +280,8 @@ impl Perform<SiteResponse> for Oper<EditSite> {
} }
impl Perform<GetSiteResponse> for Oper<GetSite> { impl Perform<GetSiteResponse> for Oper<GetSite> {
fn perform(&self) -> Result<GetSiteResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetSiteResponse, Error> {
let _data: &GetSite = &self.data; let _data: &GetSite = &self.data;
let conn = establish_connection();
// It can return a null site in order to redirect // It can return a null site in order to redirect
let site_view = match Site::read(&conn, 1) { let site_view = match Site::read(&conn, 1) {
@ -314,9 +310,8 @@ impl Perform<GetSiteResponse> for Oper<GetSite> {
} }
impl Perform<SearchResponse> for Oper<Search> { impl Perform<SearchResponse> for Oper<Search> {
fn perform(&self) -> Result<SearchResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<SearchResponse, Error> {
let data: &Search = &self.data; let data: &Search = &self.data;
let conn = establish_connection();
let sort = SortType::from_str(&data.sort)?; let sort = SortType::from_str(&data.sort)?;
let type_ = SearchType::from_str(&data.type_)?; let type_ = SearchType::from_str(&data.type_)?;
@ -419,9 +414,8 @@ impl Perform<SearchResponse> for Oper<Search> {
} }
impl Perform<GetSiteResponse> for Oper<TransferSite> { impl Perform<GetSiteResponse> for Oper<TransferSite> {
fn perform(&self) -> Result<GetSiteResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetSiteResponse, Error> {
let data: &TransferSite = &self.data; let data: &TransferSite = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,

View File

@ -2,6 +2,7 @@ use super::*;
use crate::settings::Settings; use crate::settings::Settings;
use crate::{generate_random_string, send_email}; use crate::{generate_random_string, send_email};
use bcrypt::verify; use bcrypt::verify;
use diesel::PgConnection;
use std::str::FromStr; use std::str::FromStr;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@ -167,9 +168,8 @@ pub struct PasswordChange {
} }
impl Perform<LoginResponse> for Oper<Login> { impl Perform<LoginResponse> for Oper<Login> {
fn perform(&self) -> Result<LoginResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<LoginResponse, Error> {
let data: &Login = &self.data; let data: &Login = &self.data;
let conn = establish_connection();
// Fetch that username / email // Fetch that username / email
let user: User_ = match User_::find_by_email_or_username(&conn, &data.username_or_email) { let user: User_ = match User_::find_by_email_or_username(&conn, &data.username_or_email) {
@ -192,9 +192,8 @@ impl Perform<LoginResponse> for Oper<Login> {
} }
impl Perform<LoginResponse> for Oper<Register> { impl Perform<LoginResponse> for Oper<Register> {
fn perform(&self) -> Result<LoginResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<LoginResponse, Error> {
let data: &Register = &self.data; let data: &Register = &self.data;
let conn = establish_connection();
// Make sure site has open registration // Make sure site has open registration
if let Ok(site) = SiteView::read(&conn) { if let Ok(site) = SiteView::read(&conn) {
@ -299,9 +298,8 @@ impl Perform<LoginResponse> for Oper<Register> {
} }
impl Perform<LoginResponse> for Oper<SaveUserSettings> { impl Perform<LoginResponse> for Oper<SaveUserSettings> {
fn perform(&self) -> Result<LoginResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<LoginResponse, Error> {
let data: &SaveUserSettings = &self.data; let data: &SaveUserSettings = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -378,9 +376,8 @@ impl Perform<LoginResponse> for Oper<SaveUserSettings> {
} }
impl Perform<GetUserDetailsResponse> for Oper<GetUserDetails> { impl Perform<GetUserDetailsResponse> for Oper<GetUserDetails> {
fn perform(&self) -> Result<GetUserDetailsResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetUserDetailsResponse, Error> {
let data: &GetUserDetails = &self.data; let data: &GetUserDetails = &self.data;
let conn = establish_connection();
let user_claims: Option<Claims> = match &data.auth { let user_claims: Option<Claims> = match &data.auth {
Some(auth) => match Claims::decode(&auth) { Some(auth) => match Claims::decode(&auth) {
@ -470,9 +467,8 @@ impl Perform<GetUserDetailsResponse> for Oper<GetUserDetails> {
} }
impl Perform<AddAdminResponse> for Oper<AddAdmin> { impl Perform<AddAdminResponse> for Oper<AddAdmin> {
fn perform(&self) -> Result<AddAdminResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<AddAdminResponse, Error> {
let data: &AddAdmin = &self.data; let data: &AddAdmin = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -535,9 +531,8 @@ impl Perform<AddAdminResponse> for Oper<AddAdmin> {
} }
impl Perform<BanUserResponse> for Oper<BanUser> { impl Perform<BanUserResponse> for Oper<BanUser> {
fn perform(&self) -> Result<BanUserResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<BanUserResponse, Error> {
let data: &BanUser = &self.data; let data: &BanUser = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -604,9 +599,8 @@ impl Perform<BanUserResponse> for Oper<BanUser> {
} }
impl Perform<GetRepliesResponse> for Oper<GetReplies> { impl Perform<GetRepliesResponse> for Oper<GetReplies> {
fn perform(&self) -> Result<GetRepliesResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetRepliesResponse, Error> {
let data: &GetReplies = &self.data; let data: &GetReplies = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -632,9 +626,8 @@ impl Perform<GetRepliesResponse> for Oper<GetReplies> {
} }
impl Perform<GetUserMentionsResponse> for Oper<GetUserMentions> { impl Perform<GetUserMentionsResponse> for Oper<GetUserMentions> {
fn perform(&self) -> Result<GetUserMentionsResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetUserMentionsResponse, Error> {
let data: &GetUserMentions = &self.data; let data: &GetUserMentions = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -660,9 +653,8 @@ impl Perform<GetUserMentionsResponse> for Oper<GetUserMentions> {
} }
impl Perform<UserMentionResponse> for Oper<EditUserMention> { impl Perform<UserMentionResponse> for Oper<EditUserMention> {
fn perform(&self) -> Result<UserMentionResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<UserMentionResponse, Error> {
let data: &EditUserMention = &self.data; let data: &EditUserMention = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -695,9 +687,8 @@ impl Perform<UserMentionResponse> for Oper<EditUserMention> {
} }
impl Perform<GetRepliesResponse> for Oper<MarkAllAsRead> { impl Perform<GetRepliesResponse> for Oper<MarkAllAsRead> {
fn perform(&self) -> Result<GetRepliesResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<GetRepliesResponse, Error> {
let data: &MarkAllAsRead = &self.data; let data: &MarkAllAsRead = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -759,9 +750,8 @@ impl Perform<GetRepliesResponse> for Oper<MarkAllAsRead> {
} }
impl Perform<LoginResponse> for Oper<DeleteAccount> { impl Perform<LoginResponse> for Oper<DeleteAccount> {
fn perform(&self) -> Result<LoginResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<LoginResponse, Error> {
let data: &DeleteAccount = &self.data; let data: &DeleteAccount = &self.data;
let conn = establish_connection();
let claims = match Claims::decode(&data.auth) { let claims = match Claims::decode(&data.auth) {
Ok(claims) => claims.claims, Ok(claims) => claims.claims,
@ -838,9 +828,8 @@ impl Perform<LoginResponse> for Oper<DeleteAccount> {
} }
impl Perform<PasswordResetResponse> for Oper<PasswordReset> { impl Perform<PasswordResetResponse> for Oper<PasswordReset> {
fn perform(&self) -> Result<PasswordResetResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<PasswordResetResponse, Error> {
let data: &PasswordReset = &self.data; let data: &PasswordReset = &self.data;
let conn = establish_connection();
// Fetch that email // Fetch that email
let user: User_ = match User_::find_by_email(&conn, &data.email) { let user: User_ = match User_::find_by_email(&conn, &data.email) {
@ -872,9 +861,8 @@ impl Perform<PasswordResetResponse> for Oper<PasswordReset> {
} }
impl Perform<LoginResponse> for Oper<PasswordChange> { impl Perform<LoginResponse> for Oper<PasswordChange> {
fn perform(&self) -> Result<LoginResponse, Error> { fn perform(&self, conn: &PgConnection) -> Result<LoginResponse, Error> {
let data: &PasswordChange = &self.data; let data: &PasswordChange = &self.data;
let conn = establish_connection();
// Fetch the user_id from the token // Fetch the user_id from the token
let user_id = PasswordResetRequest::read_from_token(&conn, &data.token)?.user_id; let user_id = PasswordResetRequest::read_from_token(&conn, &data.token)?.user_id;

View File

@ -1,7 +1,7 @@
use crate::apub::make_apub_endpoint; use crate::apub::make_apub_endpoint;
use crate::db::community::Community; use crate::db::community::Community;
use crate::db::community_view::CommunityFollowerView; use crate::db::community_view::CommunityFollowerView;
use crate::db::establish_connection; use crate::db::establish_unpooled_connection;
use crate::to_datetime_utc; use crate::to_datetime_utc;
use activitypub::{actor::Group, collection::UnorderedCollection, context}; use activitypub::{actor::Group, collection::UnorderedCollection, context};
use actix_web::body::Body; use actix_web::body::Body;
@ -62,7 +62,7 @@ impl Community {
collection.object_props.set_context_object(context()).ok(); collection.object_props.set_context_object(context()).ok();
collection.object_props.set_id_string(base_url).ok(); collection.object_props.set_id_string(base_url).ok();
let connection = establish_connection(); let connection = establish_unpooled_connection();
//As we are an object, we validated that the community id was valid //As we are an object, we validated that the community id was valid
let community_followers = CommunityFollowerView::for_community(&connection, self.id).unwrap(); let community_followers = CommunityFollowerView::for_community(&connection, self.id).unwrap();
@ -85,7 +85,7 @@ pub struct CommunityQuery {
} }
pub async fn get_apub_community(info: Path<CommunityQuery>) -> HttpResponse<Body> { pub async fn get_apub_community(info: Path<CommunityQuery>) -> HttpResponse<Body> {
let connection = establish_connection(); let connection = establish_unpooled_connection();
if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) { if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) {
HttpResponse::Ok() HttpResponse::Ok()
@ -97,7 +97,7 @@ pub async fn get_apub_community(info: Path<CommunityQuery>) -> HttpResponse<Body
} }
pub async fn get_apub_community_followers(info: Path<CommunityQuery>) -> HttpResponse<Body> { pub async fn get_apub_community_followers(info: Path<CommunityQuery>) -> HttpResponse<Body> {
let connection = establish_connection(); let connection = establish_unpooled_connection();
if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) { if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) {
HttpResponse::Ok() HttpResponse::Ok()

View File

@ -1,5 +1,5 @@
use crate::apub::make_apub_endpoint; use crate::apub::make_apub_endpoint;
use crate::db::establish_connection; use crate::db::establish_unpooled_connection;
use crate::db::user::User_; use crate::db::user::User_;
use crate::to_datetime_utc; use crate::to_datetime_utc;
use activitypub::{actor::Person, context}; use activitypub::{actor::Person, context};
@ -62,7 +62,7 @@ pub struct UserQuery {
} }
pub async fn get_apub_user(info: Path<UserQuery>) -> HttpResponse<Body> { pub async fn get_apub_user(info: Path<UserQuery>) -> HttpResponse<Body> {
let connection = establish_connection(); let connection = establish_unpooled_connection();
if let Ok(user) = User_::find_by_email_or_username(&connection, &info.user_name) { if let Ok(user) = User_::find_by_email_or_username(&connection, &info.user_name) {
HttpResponse::Ok() HttpResponse::Ok()

View File

@ -52,7 +52,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let categories = Category::list_all(&conn).unwrap(); let categories = Category::list_all(&conn).unwrap();
let expected_first_category = Category { let expected_first_category = Category {

View File

@ -166,7 +166,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "terry".into(), name: "terry".into(),

View File

@ -364,7 +364,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "timmy".into(), name: "timmy".into(),

View File

@ -212,7 +212,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "bobbee".into(), name: "bobbee".into(),

View File

@ -1,7 +1,6 @@
extern crate lazy_static; extern crate lazy_static;
use crate::settings::Settings; use crate::settings::Settings;
use diesel::dsl::*; use diesel::dsl::*;
use diesel::r2d2::*;
use diesel::result::Error; use diesel::result::Error;
use diesel::*; use diesel::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -111,19 +110,9 @@ impl<T> MaybeOptional<T> for Option<T> {
} }
} }
lazy_static! { pub fn establish_unpooled_connection() -> PgConnection {
static ref PG_POOL: Pool<ConnectionManager<PgConnection>> = { let db_url = Settings::get().get_database_url();
let db_url = Settings::get().get_database_url(); PgConnection::establish(&db_url).expect(&format!("Error connecting to {}", db_url))
let manager = ConnectionManager::<PgConnection>::new(&db_url);
Pool::builder()
.max_size(Settings::get().database.pool_size)
.build(manager)
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url))
};
}
pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> {
PG_POOL.get().unwrap()
} }
#[derive(EnumString, ToString, Debug, Serialize, Deserialize)] #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]

View File

@ -434,7 +434,7 @@ mod tests {
// use Crud; // use Crud;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_mod = UserForm { let new_mod = UserForm {
name: "the mod".into(), name: "the mod".into(),

View File

@ -84,7 +84,7 @@ mod tests {
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "thommy prw".into(), name: "thommy prw".into(),

View File

@ -179,7 +179,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "jim".into(), name: "jim".into(),

View File

@ -290,7 +290,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let user_name = "tegan".to_string(); let user_name = "tegan".to_string();
let community_name = "test_community_3".to_string(); let community_name = "test_community_3".to_string();

View File

@ -176,7 +176,7 @@ mod tests {
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "thommy".into(), name: "thommy".into(),

View File

@ -60,7 +60,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
let conn = establish_connection(); let conn = establish_unpooled_connection();
let new_user = UserForm { let new_user = UserForm {
name: "terrylake".into(), name: "terrylake".into(),

View File

@ -3,7 +3,8 @@ extern crate lemmy_server;
extern crate diesel_migrations; extern crate diesel_migrations;
use actix_web::*; use actix_web::*;
use lemmy_server::db::establish_connection; use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use lemmy_server::routes::{federation, feeds, index, nodeinfo, webfinger, websocket}; use lemmy_server::routes::{federation, feeds, index, nodeinfo, webfinger, websocket};
use lemmy_server::settings::Settings; use lemmy_server::settings::Settings;
use std::io; use std::io;
@ -13,13 +14,19 @@ embed_migrations!();
#[actix_rt::main] #[actix_rt::main]
async fn main() -> io::Result<()> { async fn main() -> io::Result<()> {
env_logger::init(); env_logger::init();
let settings = Settings::get();
// Set up the r2d2 connection pool
let manager = ConnectionManager::<PgConnection>::new(&settings.get_database_url());
let pool = Pool::builder()
.max_size(settings.database.pool_size)
.build(manager)
.unwrap_or_else(|_| panic!("Error connecting to {}", settings.get_database_url()));
// Run the migrations from code // Run the migrations from code
let conn = establish_connection(); let conn = pool.get().unwrap();
embedded_migrations::run(&conn).unwrap(); embedded_migrations::run(&conn).unwrap();
let settings = Settings::get();
println!( println!(
"Starting http server at {}:{}", "Starting http server at {}:{}",
settings.bind, settings.port settings.bind, settings.port
@ -28,12 +35,18 @@ async fn main() -> io::Result<()> {
// Create Http server with websocket support // Create Http server with websocket support
HttpServer::new(move || { HttpServer::new(move || {
App::new() App::new()
.wrap(middleware::Logger::default())
.data(pool.clone())
// The routes
.configure(federation::config) .configure(federation::config)
.configure(feeds::config) .configure(feeds::config)
.configure(index::config) .configure(index::config)
.configure(nodeinfo::config) .configure(nodeinfo::config)
.configure(webfinger::config) .configure(webfinger::config)
.configure(websocket::config) .configure(websocket::config)
// .configure(websocket.config(pool))
// .configure(websocket.
// static files
.service(actix_files::Files::new( .service(actix_files::Files::new(
"/static", "/static",
settings.front_end_dir.to_owned(), settings.front_end_dir.to_owned(),

View File

@ -7,11 +7,12 @@ use crate::db::post_view::{PostQueryBuilder, PostView};
use crate::db::site_view::SiteView; use crate::db::site_view::SiteView;
use crate::db::user::{Claims, User_}; use crate::db::user::{Claims, User_};
use crate::db::user_mention_view::{UserMentionQueryBuilder, UserMentionView}; use crate::db::user_mention_view::{UserMentionQueryBuilder, UserMentionView};
use crate::db::{establish_connection, ListingType, SortType}; use crate::db::{ListingType, SortType};
use crate::Settings; use crate::Settings;
use actix_web::body::Body;
use actix_web::{web, HttpResponse, Result}; use actix_web::{web, HttpResponse, Result};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use failure::Error; use failure::Error;
use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder}; use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder};
use serde::Deserialize; use serde::Deserialize;
@ -37,54 +38,61 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.route("/feeds/all.xml", web::get().to(feeds::get_all_feed)); .route("/feeds/all.xml", web::get().to(feeds::get_all_feed));
} }
async fn get_all_feed(info: web::Query<Params>) -> HttpResponse<Body> { async fn get_all_feed(
let sort_type = match get_sort_type(info) { info: web::Query<Params>,
Ok(sort_type) => sort_type, db: web::Data<Pool<ConnectionManager<PgConnection>>>,
Err(_) => return HttpResponse::BadRequest().finish(), ) -> Result<HttpResponse, actix_web::Error> {
}; let res = web::block(move || {
let conn = db.get()?;
let feed_result = get_feed_all_data(&sort_type); let sort_type = get_sort_type(info)?;
get_feed_all_data(&conn, &sort_type)
match feed_result { })
Ok(rss) => HttpResponse::Ok() .await
.map(|rss| {
HttpResponse::Ok()
.content_type("application/rss+xml") .content_type("application/rss+xml")
.body(rss), .body(rss)
Err(_) => HttpResponse::NotFound().finish(), })
} .map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
} }
async fn get_feed( async fn get_feed(
path: web::Path<(String, String)>, path: web::Path<(String, String)>,
info: web::Query<Params>, info: web::Query<Params>,
) -> HttpResponse<Body> { db: web::Data<Pool<ConnectionManager<PgConnection>>>,
let sort_type = match get_sort_type(info) { ) -> Result<HttpResponse, actix_web::Error> {
Ok(sort_type) => sort_type, let res = web::block(move || {
Err(_) => return HttpResponse::BadRequest().finish(), let conn = db.get()?;
};
let request_type = match path.0.as_ref() { let sort_type = get_sort_type(info)?;
"u" => RequestType::User,
"c" => RequestType::Community,
"front" => RequestType::Front,
"inbox" => RequestType::Inbox,
_ => return HttpResponse::NotFound().finish(),
};
let param = path.1.to_owned(); let request_type = match path.0.as_ref() {
"u" => RequestType::User,
"c" => RequestType::Community,
"front" => RequestType::Front,
"inbox" => RequestType::Inbox,
_ => return Err(format_err!("wrong_type")),
};
let feed_result = match request_type { let param = path.1.to_owned();
RequestType::User => get_feed_user(&sort_type, param),
RequestType::Community => get_feed_community(&sort_type, param),
RequestType::Front => get_feed_front(&sort_type, param),
RequestType::Inbox => get_feed_inbox(param),
};
match feed_result { match request_type {
Ok(rss) => HttpResponse::Ok() RequestType::User => get_feed_user(&conn, &sort_type, param),
RequestType::Community => get_feed_community(&conn, &sort_type, param),
RequestType::Front => get_feed_front(&conn, &sort_type, param),
RequestType::Inbox => get_feed_inbox(&conn, param),
}
})
.await
.map(|rss| {
HttpResponse::Ok()
.content_type("application/rss+xml") .content_type("application/rss+xml")
.body(rss), .body(rss)
Err(_) => HttpResponse::NotFound().finish(), })
} .map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
} }
fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> { fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> {
@ -95,9 +103,7 @@ fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> {
SortType::from_str(&sort_query) SortType::from_str(&sort_query)
} }
fn get_feed_all_data(sort_type: &SortType) -> Result<String, Error> { fn get_feed_all_data(conn: &PgConnection, sort_type: &SortType) -> Result<String, failure::Error> {
let conn = establish_connection();
let site_view = SiteView::read(&conn)?; let site_view = SiteView::read(&conn)?;
let posts = PostQueryBuilder::create(&conn) let posts = PostQueryBuilder::create(&conn)
@ -120,9 +126,11 @@ fn get_feed_all_data(sort_type: &SortType) -> Result<String, Error> {
Ok(channel_builder.build().unwrap().to_string()) Ok(channel_builder.build().unwrap().to_string())
} }
fn get_feed_user(sort_type: &SortType, user_name: String) -> Result<String, Error> { fn get_feed_user(
let conn = establish_connection(); conn: &PgConnection,
sort_type: &SortType,
user_name: String,
) -> Result<String, 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();
@ -144,9 +152,11 @@ fn get_feed_user(sort_type: &SortType, user_name: String) -> Result<String, Erro
Ok(channel_builder.build().unwrap().to_string()) Ok(channel_builder.build().unwrap().to_string())
} }
fn get_feed_community(sort_type: &SortType, community_name: String) -> Result<String, Error> { fn get_feed_community(
let conn = establish_connection(); conn: &PgConnection,
sort_type: &SortType,
community_name: String,
) -> Result<String, 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,9 +182,7 @@ fn get_feed_community(sort_type: &SortType, community_name: String) -> Result<St
Ok(channel_builder.build().unwrap().to_string()) Ok(channel_builder.build().unwrap().to_string())
} }
fn get_feed_front(sort_type: &SortType, jwt: String) -> Result<String, Error> { fn get_feed_front(conn: &PgConnection, sort_type: &SortType, jwt: String) -> Result<String, Error> {
let conn = establish_connection();
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;
@ -199,9 +207,7 @@ fn get_feed_front(sort_type: &SortType, jwt: String) -> Result<String, Error> {
Ok(channel_builder.build().unwrap().to_string()) Ok(channel_builder.build().unwrap().to_string())
} }
fn get_feed_inbox(jwt: String) -> Result<String, Error> { fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<String, Error> {
let conn = establish_connection();
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

@ -1,10 +1,11 @@
use crate::db::establish_connection;
use crate::db::site_view::SiteView; use crate::db::site_view::SiteView;
use crate::version; use crate::version;
use crate::Settings; use crate::Settings;
use actix_web::body::Body; use actix_web::body::Body;
use actix_web::web; use actix_web::web;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use serde_json::json; use serde_json::json;
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
@ -26,34 +27,39 @@ async fn node_info_well_known() -> HttpResponse<Body> {
.body(json.to_string()) .body(json.to_string())
} }
async fn node_info() -> HttpResponse<Body> { async fn node_info(
let conn = establish_connection(); db: web::Data<Pool<ConnectionManager<PgConnection>>>,
let site_view = match SiteView::read(&conn) { ) -> Result<HttpResponse, actix_web::Error> {
Ok(site_view) => site_view, let res = web::block(move || {
Err(_e) => return HttpResponse::InternalServerError().finish(), let conn = db.get()?;
}; let site_view = match SiteView::read(&conn) {
let protocols = if Settings::get().federation_enabled { Ok(site_view) => site_view,
vec!["activitypub"] Err(_) => return Err(format_err!("not_found")),
} else { };
vec![] let protocols = if Settings::get().federation_enabled {
}; vec!["activitypub"]
let json = json!({ } else {
"version": "2.0", vec![]
"software": { };
"name": "lemmy", Ok(json!({
"version": version::VERSION, "version": "2.0",
}, "software": {
"protocols": protocols, "name": "lemmy",
"usage": { "version": version::VERSION,
"users": {
"total": site_view.number_of_users
}, },
"localPosts": site_view.number_of_posts, "protocols": protocols,
"localComments": site_view.number_of_comments, "usage": {
"openRegistrations": site_view.open_registration, "users": {
"total": site_view.number_of_users
},
"localPosts": site_view.number_of_posts,
"localComments": site_view.number_of_comments,
"openRegistrations": site_view.open_registration,
} }
}); }))
HttpResponse::Ok() })
.content_type("application/json") .await
.body(json.to_string()) .map(|json| HttpResponse::Ok().json(json))
.map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
} }

View File

@ -1,10 +1,10 @@
use crate::db::community::Community; use crate::db::community::Community;
use crate::db::establish_connection;
use crate::Settings; use crate::Settings;
use actix_web::body::Body;
use actix_web::web; use actix_web::web;
use actix_web::web::Query; use actix_web::web::Query;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use regex::Regex; use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
@ -37,54 +37,61 @@ lazy_static! {
/// ///
/// You can also view the webfinger response that Mastodon sends: /// You can also view the webfinger response that Mastodon sends:
/// https://radical.town/.well-known/webfinger?resource=acct:felix@radical.town /// https://radical.town/.well-known/webfinger?resource=acct:felix@radical.town
async fn get_webfinger_response(info: Query<Params>) -> HttpResponse<Body> { async fn get_webfinger_response(
let regex_parsed = WEBFINGER_COMMUNITY_REGEX info: Query<Params>,
.captures(&info.resource) db: web::Data<Pool<ConnectionManager<PgConnection>>>,
.map(|c| c.get(1)); ) -> Result<HttpResponse, actix_web::Error> {
// TODO: replace this with .flatten() once we are running rust 1.40 let res = web::block(move || {
let regex_parsed_flattened = match regex_parsed { let conn = db.get()?;
Some(s) => s,
None => None,
};
let community_name = match regex_parsed_flattened {
Some(c) => c.as_str(),
None => return HttpResponse::NotFound().finish(),
};
// Make sure the requested community exists. let regex_parsed = WEBFINGER_COMMUNITY_REGEX
let conn = establish_connection(); .captures(&info.resource)
let community = match Community::read_from_name(&conn, community_name.to_string()) { .map(|c| c.get(1));
Ok(o) => o, // TODO: replace this with .flatten() once we are running rust 1.40
Err(_) => return HttpResponse::NotFound().finish(), let regex_parsed_flattened = match regex_parsed {
}; Some(s) => s,
None => None,
};
let community_name = match regex_parsed_flattened {
Some(c) => c.as_str(),
None => return Err(format_err!("not_found")),
};
let community_url = community.get_url(); // Make sure the requested community exists.
let community = match Community::read_from_name(&conn, community_name.to_string()) {
Ok(o) => o,
Err(_) => return Err(format_err!("not_found")),
};
let json = json!({ let community_url = community.get_url();
Ok(json!({
"subject": info.resource, "subject": info.resource,
"aliases": [ "aliases": [
community_url, community_url,
], ],
"links": [ "links": [
{ {
"rel": "http://webfinger.net/rel/profile-page", "rel": "http://webfinger.net/rel/profile-page",
"type": "text/html", "type": "text/html",
"href": community_url "href": community_url
}, },
{ {
"rel": "self", "rel": "self",
"type": "application/activity+json", "type": "application/activity+json",
// Yes this is correct, this link doesn't include the `.json` extension // Yes this is correct, this link doesn't include the `.json` extension
"href": community_url "href": community_url
} }
// TODO: this also needs to return the subscribe link once that's implemented // TODO: this also needs to return the subscribe link once that's implemented
//{ //{
// "rel": "http://ostatus.org/schema/1.0/subscribe", // "rel": "http://ostatus.org/schema/1.0/subscribe",
// "template": "https://my_instance.com/authorize_interaction?uri={uri}" // "template": "https://my_instance.com/authorize_interaction?uri={uri}"
//} //}
] ]
}); }))
HttpResponse::Ok() })
.content_type("application/activity+json") .await
.body(json.to_string()) .map(|json| HttpResponse::Ok().json(json))
.map_err(|_| HttpResponse::InternalServerError())?;
Ok(res)
} }

View File

@ -1,13 +1,24 @@
use crate::websocket::server::*; use crate::websocket::server::*;
use crate::Settings;
use actix::prelude::*; use actix::prelude::*;
use actix_web::web; use actix_web::web;
use actix_web::*; use actix_web::*;
use actix_web_actors::ws; use actix_web_actors::ws;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
pub fn config(cfg: &mut web::ServiceConfig) { pub fn config(cfg: &mut web::ServiceConfig) {
// TODO couldn't figure out how to get this method to recieve the other pool
let settings = Settings::get();
let manager = ConnectionManager::<PgConnection>::new(&settings.get_database_url());
let pool = Pool::builder()
.max_size(settings.database.pool_size)
.build(manager)
.unwrap_or_else(|_| panic!("Error connecting to {}", settings.get_database_url()));
// Start chat server actor in separate thread // Start chat server actor in separate thread
let server = ChatServer::default().start(); let server = ChatServer::startup(pool).start();
cfg cfg
.data(server) .data(server)
.service(web::resource("/api/v1/ws").to(chat_route)); .service(web::resource("/api/v1/ws").to(chat_route));
@ -24,9 +35,11 @@ async fn chat_route(
stream: web::Payload, stream: web::Payload,
chat_server: web::Data<Addr<ChatServer>>, chat_server: web::Data<Addr<ChatServer>>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
// TODO not sure if the blocking should be here or not
ws::start( ws::start(
WSSession { WSSession {
cs_addr: chat_server.get_ref().to_owned(), // db: db.get_ref().clone(),
cs_addr: chat_server.get_ref().clone(),
id: 0, id: 0,
hb: Instant::now(), hb: Instant::now(),
ip: req ip: req
@ -51,6 +64,7 @@ struct WSSession {
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT), /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection. /// otherwise we drop connection.
hb: Instant, hb: Instant,
// db: Pool<ConnectionManager<PgConnection>>,
} }
impl Actor for WSSession { impl Actor for WSSession {
@ -127,7 +141,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WSSession {
} }
ws::Message::Text(text) => { ws::Message::Text(text) => {
let m = text.trim().to_owned(); let m = text.trim().to_owned();
println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id); // println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id);
self self
.cs_addr .cs_addr

View File

@ -3,6 +3,8 @@
//! room through `ChatServer`. //! room through `ChatServer`.
use actix::prelude::*; use actix::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
use failure::Error; use failure::Error;
use rand::{rngs::ThreadRng, Rng}; use rand::{rngs::ThreadRng, Rng};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -42,6 +44,7 @@ pub struct Disconnect {
pub ip: String, pub ip: String,
} }
// TODO this is unused rn
/// Send message to specific room /// Send message to specific room
#[derive(Message)] #[derive(Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
@ -81,10 +84,26 @@ pub struct ChatServer {
rate_limits: HashMap<String, RateLimitBucket>, rate_limits: HashMap<String, RateLimitBucket>,
rooms: HashMap<i32, HashSet<usize>>, // A map from room / post name to set of connectionIDs rooms: HashMap<i32, HashSet<usize>>, // A map from room / post name to set of connectionIDs
rng: ThreadRng, rng: ThreadRng,
db: Pool<ConnectionManager<PgConnection>>,
} }
impl Default for ChatServer { // impl Default for ChatServer {
fn default() -> ChatServer { // fn default(nah: String) -> ChatServer {
// // default room
// let rooms = HashMap::new();
// ChatServer {
// sessions: HashMap::new(),
// rate_limits: HashMap::new(),
// rooms,
// rng: rand::thread_rng(),
// nah: nah,
// }
// }
// }
impl ChatServer {
pub fn startup(db: Pool<ConnectionManager<PgConnection>>) -> ChatServer {
// default room // default room
let rooms = HashMap::new(); let rooms = HashMap::new();
@ -93,11 +112,10 @@ impl Default for ChatServer {
rate_limits: HashMap::new(), rate_limits: HashMap::new(),
rooms, rooms,
rng: rand::thread_rng(), rng: rand::thread_rng(),
db,
} }
} }
}
impl ChatServer {
/// Send message to all users in the room /// Send message to all users in the room
fn send_room_message(&self, room: i32, message: &str, skip_id: usize) { fn send_room_message(&self, room: i32, message: &str, skip_id: usize) {
if let Some(sessions) = self.rooms.get(&room) { if let Some(sessions) = self.rooms.get(&room) {
@ -133,7 +151,8 @@ impl ChatServer {
) -> Result<(), Error> { ) -> Result<(), Error> {
use crate::db::post_view::*; use crate::db::post_view::*;
use crate::db::*; use crate::db::*;
let conn = establish_connection();
let conn = self.db.get()?;
let posts = PostQueryBuilder::create(&conn) let posts = PostQueryBuilder::create(&conn)
.listing_type(ListingType::Community) .listing_type(ListingType::Community)
@ -299,17 +318,19 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
message: "Unknown op type".to_string(), message: "Unknown op type".to_string(),
})?; })?;
let conn = chat.db.get()?;
let user_operation: UserOperation = UserOperation::from_str(&op)?; let user_operation: UserOperation = UserOperation::from_str(&op)?;
match user_operation { match user_operation {
UserOperation::Login => { UserOperation::Login => {
let login: Login = serde_json::from_str(data)?; let login: Login = serde_json::from_str(data)?;
let res = Oper::new(user_operation, login).perform()?; let res = Oper::new(user_operation, login).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::Register => { UserOperation::Register => {
let register: Register = serde_json::from_str(data)?; let register: Register = serde_json::from_str(data)?;
let res = Oper::new(user_operation, register).perform(); let res = Oper::new(user_operation, register).perform(&conn);
if res.is_ok() { if res.is_ok() {
chat.check_rate_limit_register(msg.id)?; chat.check_rate_limit_register(msg.id)?;
} }
@ -317,63 +338,63 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
} }
UserOperation::GetUserDetails => { UserOperation::GetUserDetails => {
let get_user_details: GetUserDetails = serde_json::from_str(data)?; let get_user_details: GetUserDetails = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_user_details).perform()?; let res = Oper::new(user_operation, get_user_details).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::SaveUserSettings => { UserOperation::SaveUserSettings => {
let save_user_settings: SaveUserSettings = serde_json::from_str(data)?; let save_user_settings: SaveUserSettings = serde_json::from_str(data)?;
let res = Oper::new(user_operation, save_user_settings).perform()?; let res = Oper::new(user_operation, save_user_settings).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::AddAdmin => { UserOperation::AddAdmin => {
let add_admin: AddAdmin = serde_json::from_str(data)?; let add_admin: AddAdmin = serde_json::from_str(data)?;
let res = Oper::new(user_operation, add_admin).perform()?; let res = Oper::new(user_operation, add_admin).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::BanUser => { UserOperation::BanUser => {
let ban_user: BanUser = serde_json::from_str(data)?; let ban_user: BanUser = serde_json::from_str(data)?;
let res = Oper::new(user_operation, ban_user).perform()?; let res = Oper::new(user_operation, ban_user).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetReplies => { UserOperation::GetReplies => {
let get_replies: GetReplies = serde_json::from_str(data)?; let get_replies: GetReplies = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_replies).perform()?; let res = Oper::new(user_operation, get_replies).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetUserMentions => { UserOperation::GetUserMentions => {
let get_user_mentions: GetUserMentions = serde_json::from_str(data)?; let get_user_mentions: GetUserMentions = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_user_mentions).perform()?; let res = Oper::new(user_operation, get_user_mentions).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::EditUserMention => { UserOperation::EditUserMention => {
let edit_user_mention: EditUserMention = serde_json::from_str(data)?; let edit_user_mention: EditUserMention = serde_json::from_str(data)?;
let res = Oper::new(user_operation, edit_user_mention).perform()?; let res = Oper::new(user_operation, edit_user_mention).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::MarkAllAsRead => { UserOperation::MarkAllAsRead => {
let mark_all_as_read: MarkAllAsRead = serde_json::from_str(data)?; let mark_all_as_read: MarkAllAsRead = serde_json::from_str(data)?;
let res = Oper::new(user_operation, mark_all_as_read).perform()?; let res = Oper::new(user_operation, mark_all_as_read).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetCommunity => { UserOperation::GetCommunity => {
let get_community: GetCommunity = serde_json::from_str(data)?; let get_community: GetCommunity = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_community).perform()?; let res = Oper::new(user_operation, get_community).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::ListCommunities => { UserOperation::ListCommunities => {
let list_communities: ListCommunities = serde_json::from_str(data)?; let list_communities: ListCommunities = serde_json::from_str(data)?;
let res = Oper::new(user_operation, list_communities).perform()?; let res = Oper::new(user_operation, list_communities).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreateCommunity => { UserOperation::CreateCommunity => {
chat.check_rate_limit_register(msg.id)?; chat.check_rate_limit_register(msg.id)?;
let create_community: CreateCommunity = serde_json::from_str(data)?; let create_community: CreateCommunity = serde_json::from_str(data)?;
let res = Oper::new(user_operation, create_community).perform()?; let res = Oper::new(user_operation, create_community).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::EditCommunity => { UserOperation::EditCommunity => {
let edit_community: EditCommunity = serde_json::from_str(data)?; let edit_community: EditCommunity = serde_json::from_str(data)?;
let res = Oper::new(user_operation, edit_community).perform()?; let res = Oper::new(user_operation, edit_community).perform(&conn)?;
let mut community_sent: CommunityResponse = res.clone(); let mut community_sent: CommunityResponse = res.clone();
community_sent.community.user_id = None; community_sent.community.user_id = None;
community_sent.community.subscribed = None; community_sent.community.subscribed = None;
@ -383,18 +404,18 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
} }
UserOperation::FollowCommunity => { UserOperation::FollowCommunity => {
let follow_community: FollowCommunity = serde_json::from_str(data)?; let follow_community: FollowCommunity = serde_json::from_str(data)?;
let res = Oper::new(user_operation, follow_community).perform()?; let res = Oper::new(user_operation, follow_community).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetFollowedCommunities => { UserOperation::GetFollowedCommunities => {
let followed_communities: GetFollowedCommunities = serde_json::from_str(data)?; let followed_communities: GetFollowedCommunities = serde_json::from_str(data)?;
let res = Oper::new(user_operation, followed_communities).perform()?; let res = Oper::new(user_operation, followed_communities).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::BanFromCommunity => { UserOperation::BanFromCommunity => {
let ban_from_community: BanFromCommunity = serde_json::from_str(data)?; let ban_from_community: BanFromCommunity = serde_json::from_str(data)?;
let community_id = ban_from_community.community_id; let community_id = ban_from_community.community_id;
let res = Oper::new(user_operation, ban_from_community).perform()?; let res = Oper::new(user_operation, ban_from_community).perform(&conn)?;
let res_str = serde_json::to_string(&res)?; let res_str = serde_json::to_string(&res)?;
chat.send_community_message(community_id, &res_str, msg.id)?; chat.send_community_message(community_id, &res_str, msg.id)?;
Ok(res_str) Ok(res_str)
@ -402,42 +423,42 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
UserOperation::AddModToCommunity => { UserOperation::AddModToCommunity => {
let mod_add_to_community: AddModToCommunity = serde_json::from_str(data)?; let mod_add_to_community: AddModToCommunity = serde_json::from_str(data)?;
let community_id = mod_add_to_community.community_id; let community_id = mod_add_to_community.community_id;
let res = Oper::new(user_operation, mod_add_to_community).perform()?; let res = Oper::new(user_operation, mod_add_to_community).perform(&conn)?;
let res_str = serde_json::to_string(&res)?; let res_str = serde_json::to_string(&res)?;
chat.send_community_message(community_id, &res_str, msg.id)?; chat.send_community_message(community_id, &res_str, msg.id)?;
Ok(res_str) Ok(res_str)
} }
UserOperation::ListCategories => { UserOperation::ListCategories => {
let list_categories: ListCategories = ListCategories; let list_categories: ListCategories = ListCategories;
let res = Oper::new(user_operation, list_categories).perform()?; let res = Oper::new(user_operation, list_categories).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreatePost => { UserOperation::CreatePost => {
chat.check_rate_limit_post(msg.id)?; chat.check_rate_limit_post(msg.id)?;
let create_post: CreatePost = serde_json::from_str(data)?; let create_post: CreatePost = serde_json::from_str(data)?;
let res = Oper::new(user_operation, create_post).perform()?; let res = Oper::new(user_operation, create_post).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetPost => { UserOperation::GetPost => {
let get_post: GetPost = serde_json::from_str(data)?; let get_post: GetPost = serde_json::from_str(data)?;
chat.join_room(get_post.id, msg.id); chat.join_room(get_post.id, msg.id);
let res = Oper::new(user_operation, get_post).perform()?; let res = Oper::new(user_operation, get_post).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetPosts => { UserOperation::GetPosts => {
let get_posts: GetPosts = serde_json::from_str(data)?; let get_posts: GetPosts = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_posts).perform()?; let res = Oper::new(user_operation, get_posts).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreatePostLike => { UserOperation::CreatePostLike => {
chat.check_rate_limit_message(msg.id)?; chat.check_rate_limit_message(msg.id)?;
let create_post_like: CreatePostLike = serde_json::from_str(data)?; let create_post_like: CreatePostLike = serde_json::from_str(data)?;
let res = Oper::new(user_operation, create_post_like).perform()?; let res = Oper::new(user_operation, create_post_like).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::EditPost => { UserOperation::EditPost => {
let edit_post: EditPost = serde_json::from_str(data)?; let edit_post: EditPost = serde_json::from_str(data)?;
let res = Oper::new(user_operation, edit_post).perform()?; let res = Oper::new(user_operation, edit_post).perform(&conn)?;
let mut post_sent = res.clone(); let mut post_sent = res.clone();
post_sent.post.my_vote = None; post_sent.post.my_vote = None;
let post_sent_str = serde_json::to_string(&post_sent)?; let post_sent_str = serde_json::to_string(&post_sent)?;
@ -446,14 +467,14 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
} }
UserOperation::SavePost => { UserOperation::SavePost => {
let save_post: SavePost = serde_json::from_str(data)?; let save_post: SavePost = serde_json::from_str(data)?;
let res = Oper::new(user_operation, save_post).perform()?; let res = Oper::new(user_operation, save_post).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreateComment => { UserOperation::CreateComment => {
chat.check_rate_limit_message(msg.id)?; chat.check_rate_limit_message(msg.id)?;
let create_comment: CreateComment = serde_json::from_str(data)?; let create_comment: CreateComment = serde_json::from_str(data)?;
let post_id = create_comment.post_id; let post_id = create_comment.post_id;
let res = Oper::new(user_operation, create_comment).perform()?; let res = Oper::new(user_operation, create_comment).perform(&conn)?;
let mut comment_sent = res.clone(); let mut comment_sent = res.clone();
comment_sent.comment.my_vote = None; comment_sent.comment.my_vote = None;
comment_sent.comment.user_id = None; comment_sent.comment.user_id = None;
@ -464,7 +485,7 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
UserOperation::EditComment => { UserOperation::EditComment => {
let edit_comment: EditComment = serde_json::from_str(data)?; let edit_comment: EditComment = serde_json::from_str(data)?;
let post_id = edit_comment.post_id; let post_id = edit_comment.post_id;
let res = Oper::new(user_operation, edit_comment).perform()?; let res = Oper::new(user_operation, edit_comment).perform(&conn)?;
let mut comment_sent = res.clone(); let mut comment_sent = res.clone();
comment_sent.comment.my_vote = None; comment_sent.comment.my_vote = None;
comment_sent.comment.user_id = None; comment_sent.comment.user_id = None;
@ -474,14 +495,14 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
} }
UserOperation::SaveComment => { UserOperation::SaveComment => {
let save_comment: SaveComment = serde_json::from_str(data)?; let save_comment: SaveComment = serde_json::from_str(data)?;
let res = Oper::new(user_operation, save_comment).perform()?; let res = Oper::new(user_operation, save_comment).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreateCommentLike => { UserOperation::CreateCommentLike => {
chat.check_rate_limit_message(msg.id)?; chat.check_rate_limit_message(msg.id)?;
let create_comment_like: CreateCommentLike = serde_json::from_str(data)?; let create_comment_like: CreateCommentLike = serde_json::from_str(data)?;
let post_id = create_comment_like.post_id; let post_id = create_comment_like.post_id;
let res = Oper::new(user_operation, create_comment_like).perform()?; let res = Oper::new(user_operation, create_comment_like).perform(&conn)?;
let mut comment_sent = res.clone(); let mut comment_sent = res.clone();
comment_sent.comment.my_vote = None; comment_sent.comment.my_vote = None;
comment_sent.comment.user_id = None; comment_sent.comment.user_id = None;
@ -491,54 +512,54 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<Str
} }
UserOperation::GetModlog => { UserOperation::GetModlog => {
let get_modlog: GetModlog = serde_json::from_str(data)?; let get_modlog: GetModlog = serde_json::from_str(data)?;
let res = Oper::new(user_operation, get_modlog).perform()?; let res = Oper::new(user_operation, get_modlog).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::CreateSite => { UserOperation::CreateSite => {
let create_site: CreateSite = serde_json::from_str(data)?; let create_site: CreateSite = serde_json::from_str(data)?;
let res = Oper::new(user_operation, create_site).perform()?; let res = Oper::new(user_operation, create_site).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::EditSite => { UserOperation::EditSite => {
let edit_site: EditSite = serde_json::from_str(data)?; let edit_site: EditSite = serde_json::from_str(data)?;
let res = Oper::new(user_operation, edit_site).perform()?; let res = Oper::new(user_operation, edit_site).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::GetSite => { UserOperation::GetSite => {
let online: usize = chat.sessions.len(); let online: usize = chat.sessions.len();
let get_site: GetSite = serde_json::from_str(data)?; let get_site: GetSite = serde_json::from_str(data)?;
let mut res = Oper::new(user_operation, get_site).perform()?; let mut res = Oper::new(user_operation, get_site).perform(&conn)?;
res.online = online; res.online = online;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::Search => { UserOperation::Search => {
let search: Search = serde_json::from_str(data)?; let search: Search = serde_json::from_str(data)?;
let res = Oper::new(user_operation, search).perform()?; let res = Oper::new(user_operation, search).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::TransferCommunity => { UserOperation::TransferCommunity => {
let transfer_community: TransferCommunity = serde_json::from_str(data)?; let transfer_community: TransferCommunity = serde_json::from_str(data)?;
let res = Oper::new(user_operation, transfer_community).perform()?; let res = Oper::new(user_operation, transfer_community).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::TransferSite => { UserOperation::TransferSite => {
let transfer_site: TransferSite = serde_json::from_str(data)?; let transfer_site: TransferSite = serde_json::from_str(data)?;
let res = Oper::new(user_operation, transfer_site).perform()?; let res = Oper::new(user_operation, transfer_site).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::DeleteAccount => { UserOperation::DeleteAccount => {
let delete_account: DeleteAccount = serde_json::from_str(data)?; let delete_account: DeleteAccount = serde_json::from_str(data)?;
let res = Oper::new(user_operation, delete_account).perform()?; let res = Oper::new(user_operation, delete_account).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::PasswordReset => { UserOperation::PasswordReset => {
let password_reset: PasswordReset = serde_json::from_str(data)?; let password_reset: PasswordReset = serde_json::from_str(data)?;
let res = Oper::new(user_operation, password_reset).perform()?; let res = Oper::new(user_operation, password_reset).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
UserOperation::PasswordChange => { UserOperation::PasswordChange => {
let password_change: PasswordChange = serde_json::from_str(data)?; let password_change: PasswordChange = serde_json::from_str(data)?;
let res = Oper::new(user_operation, password_change).perform()?; let res = Oper::new(user_operation, password_change).perform(&conn)?;
Ok(serde_json::to_string(&res)?) Ok(serde_json::to_string(&res)?)
} }
} }