Starting on siteview.

This commit is contained in:
Dessalines 2020-12-02 13:32:47 -06:00
parent b587e147b0
commit ca7224c086
14 changed files with 115 additions and 32 deletions

View file

@ -15,8 +15,8 @@ use lemmy_db::{
comment_view::*, comment_view::*,
moderator::*, moderator::*,
post::*, post::*,
site_view::*,
user::*, user::*,
views::site_view::SiteView,
Crud, Crud,
Likeable, Likeable,
ListingType, ListingType,
@ -552,8 +552,8 @@ impl Perform for CreateCommentLike {
// Don't do a downvote if site has downvotes disabled // Don't do a downvote if site has downvotes disabled
if data.score == -1 { if data.score == -1 {
let site = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
if !site.enable_downvotes { if !site_view.site.enable_downvotes {
return Err(APIError::err("downvotes_disabled").into()); return Err(APIError::err("downvotes_disabled").into());
} }
} }

View file

@ -17,7 +17,7 @@ use lemmy_db::{
post::*, post::*,
post_report::*, post_report::*,
post_view::*, post_view::*,
site_view::*, views::site_view::SiteView,
Crud, Crud,
Likeable, Likeable,
ListingType, ListingType,
@ -281,8 +281,8 @@ impl Perform for CreatePostLike {
// Don't do a downvote if site has downvotes disabled // Don't do a downvote if site has downvotes disabled
if data.score == -1 { if data.score == -1 {
let site = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??;
if !site.enable_downvotes { if !site_view.site.enable_downvotes {
return Err(APIError::err("downvotes_disabled").into()); return Err(APIError::err("downvotes_disabled").into());
} }
} }

View file

@ -19,8 +19,8 @@ use lemmy_db::{
naive_now, naive_now,
post_view::*, post_view::*,
site::*, site::*,
site_view::*,
user_view::*, user_view::*,
views::site_view::SiteView,
Crud, Crud,
SearchType, SearchType,
SortType, SortType,
@ -284,7 +284,7 @@ impl Perform for GetSite {
// Make sure the site creator is the top admin // Make sure the site creator is the top admin
if let Some(site_view) = site_view.to_owned() { if let Some(site_view) = site_view.to_owned() {
let site_creator_id = site_view.creator_id; let site_creator_id = site_view.creator.id;
// TODO investigate why this is sometimes coming back null // TODO investigate why this is sometimes coming back null
// Maybe user_.admin isn't being set to true? // Maybe user_.admin isn't being set to true?
if let Some(creator_index) = admins.iter().position(|r| r.id == site_creator_id) { if let Some(creator_index) = admins.iter().position(|r| r.id == site_creator_id) {
@ -318,6 +318,11 @@ impl Perform for GetSite {
version: version::VERSION.to_string(), version: version::VERSION.to_string(),
my_user, my_user,
federated_instances: linked_instances(context.pool()).await?, federated_instances: linked_instances(context.pool()).await?,
// TODO
number_of_users: 0,
number_of_posts: 0,
number_of_comments: 0,
number_of_communities: 0,
}) })
} }
} }
@ -534,7 +539,7 @@ impl Perform for TransferSite {
let mut admins = blocking(context.pool(), move |conn| UserView::admins(conn)).await??; let mut admins = blocking(context.pool(), move |conn| UserView::admins(conn)).await??;
let creator_index = admins let creator_index = admins
.iter() .iter()
.position(|r| r.id == site_view.creator_id) .position(|r| r.id == site_view.creator.id)
.context(location_info!())?; .context(location_info!())?;
let creator_user = admins.remove(creator_index); let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user); admins.insert(0, creator_user);
@ -549,6 +554,11 @@ impl Perform for TransferSite {
version: version::VERSION.to_string(), version: version::VERSION.to_string(),
my_user: Some(user), my_user: Some(user),
federated_instances: linked_instances(context.pool()).await?, federated_instances: linked_instances(context.pool()).await?,
// TODO
number_of_users: 0,
number_of_posts: 0,
number_of_comments: 0,
number_of_communities: 0,
}) })
} }
} }

View file

@ -30,11 +30,11 @@ use lemmy_db::{
private_message::*, private_message::*,
private_message_view::*, private_message_view::*,
site::*, site::*,
site_view::*,
user::*, user::*,
user_mention::*, user_mention::*,
user_mention_view::*, user_mention_view::*,
user_view::*, user_view::*,
views::site_view::SiteView,
Crud, Crud,
Followable, Followable,
Joinable, Joinable,
@ -113,9 +113,8 @@ impl Perform for Register {
let data: &Register = &self; let data: &Register = &self;
// Make sure site has open registration // Make sure site has open registration
if let Ok(site) = blocking(context.pool(), move |conn| SiteView::read(conn)).await? { if let Ok(site_view) = blocking(context.pool(), move |conn| SiteView::read(conn)).await? {
let site: SiteView = site; if !site_view.site.open_registration {
if !site.open_registration {
return Err(APIError::err("registration_closed").into()); return Err(APIError::err("registration_closed").into());
} }
} }

View file

@ -33,6 +33,7 @@ pub mod user;
pub mod user_mention; pub mod user_mention;
pub mod user_mention_view; pub mod user_mention_view;
pub mod user_view; pub mod user_view;
pub mod views;
pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>; pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;

View file

@ -1,7 +1,8 @@
use crate::{naive_now, schema::site, Crud}; use crate::{naive_now, schema::site, Crud};
use diesel::{dsl::*, result::Error, *}; use diesel::{dsl::*, result::Error, *};
use serde::Serialize;
#[derive(Queryable, Identifiable, PartialEq, Debug)] #[derive(Queryable, Identifiable, PartialEq, Debug, Clone, Serialize)]
#[table_name = "site"] #[table_name = "site"]
pub struct Site { pub struct Site {
pub id: i32, pub id: i32,

View file

@ -69,6 +69,25 @@ pub struct UserForm {
pub banner: Option<Option<String>>, pub banner: Option<Option<String>>,
} }
/// A safe representation of user, without the sensitive info
#[derive(Clone, Debug, Serialize)]
pub struct UserSafe {
pub id: i32,
pub name: String,
pub preferred_username: Option<String>,
pub avatar: Option<String>,
pub admin: bool,
pub banned: bool,
pub published: chrono::NaiveDateTime,
pub updated: Option<chrono::NaiveDateTime>,
pub matrix_user_id: Option<String>,
pub actor_id: String,
pub bio: Option<String>,
pub local: bool,
pub banner: Option<String>,
pub deleted: bool,
}
impl Crud<UserForm> for User_ { impl Crud<UserForm> for User_ {
fn read(conn: &PgConnection, user_id: i32) -> Result<Self, Error> { fn read(conn: &PgConnection, user_id: i32) -> Result<Self, Error> {
user_ user_
@ -200,6 +219,25 @@ impl User_ {
)) ))
.get_result::<Self>(conn) .get_result::<Self>(conn)
} }
pub fn to_safe(&self) -> UserSafe {
UserSafe {
id: self.id,
name: self.name.to_owned(),
preferred_username: self.preferred_username.to_owned(),
avatar: self.avatar.to_owned(),
admin: self.admin,
banned: self.banned,
published: self.published,
updated: self.updated,
matrix_user_id: self.matrix_user_id.to_owned(),
actor_id: self.actor_id.to_owned(),
bio: self.bio.to_owned(),
local: self.local,
banner: self.banner.to_owned(),
deleted: self.deleted,
}
}
} }
#[cfg(test)] #[cfg(test)]
@ -265,6 +303,7 @@ mod tests {
private_key: None, private_key: None,
public_key: None, public_key: None,
last_refreshed_at: inserted_user.published, last_refreshed_at: inserted_user.published,
deleted: false,
}; };
let read_user = User_::read(&conn, inserted_user.id).unwrap(); let read_user = User_::read(&conn, inserted_user.id).unwrap();

View file

@ -0,0 +1 @@
pub mod site_view;

View file

@ -0,0 +1,26 @@
use crate::{
schema::{site as site_table, user_},
site::Site,
user::{UserSafe, User_},
};
use diesel::{result::Error, *};
use serde::Serialize;
#[derive(Debug, Serialize, Clone)]
pub struct SiteView {
pub site: Site,
pub creator: UserSafe,
}
impl SiteView {
pub fn read(conn: &PgConnection) -> Result<Self, Error> {
let site_join = site_table::table
.inner_join(user_::table)
.first::<(Site, User_)>(conn)?;
Ok(SiteView {
site: site_join.0,
creator: site_join.1.to_safe(),
})
}
}

View file

@ -4,9 +4,9 @@ use lemmy_db::{
community_view::*, community_view::*,
moderator_views::*, moderator_views::*,
post_view::*, post_view::*,
site_view::*,
user::*, user::*,
user_view::*, user_view::*,
views::site_view::SiteView,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -89,6 +89,7 @@ pub struct GetSite {
pub auth: Option<String>, pub auth: Option<String>,
} }
// TODO combine siteresponse and getsiteresponse
#[derive(Serialize, Clone)] #[derive(Serialize, Clone)]
pub struct SiteResponse { pub struct SiteResponse {
pub site: SiteView, pub site: SiteView,
@ -96,7 +97,11 @@ pub struct SiteResponse {
#[derive(Serialize)] #[derive(Serialize)]
pub struct GetSiteResponse { pub struct GetSiteResponse {
pub site: Option<SiteView>, pub site: Option<SiteView>, // Because the site might not be set up yet
pub number_of_users: i64,
pub number_of_posts: i64,
pub number_of_comments: i64,
pub number_of_communities: i64,
pub admins: Vec<UserView>, pub admins: Vec<UserView>,
pub banned: Vec<UserView>, pub banned: Vec<UserView>,
pub online: usize, pub online: usize,

View file

@ -0,0 +1 @@
-- This file should undo anything in `up.sql`

View file

@ -0,0 +1 @@
-- Your SQL goes here

View file

@ -7,9 +7,9 @@ use lemmy_db::{
comment_view::{ReplyQueryBuilder, ReplyView}, comment_view::{ReplyQueryBuilder, ReplyView},
community::Community, community::Community,
post_view::{PostQueryBuilder, PostView}, post_view::{PostQueryBuilder, PostView},
site_view::SiteView,
user::User_, user::User_,
user_mention_view::{UserMentionQueryBuilder, UserMentionView}, user_mention_view::{UserMentionQueryBuilder, UserMentionView},
views::site_view::SiteView,
ListingType, ListingType,
SortType, SortType,
}; };
@ -96,13 +96,13 @@ async fn get_feed_data(
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.to_owned())
.title(&format!( .title(&format!(
"{} - {}", "{} - {}",
site_view.name, site_view.site.name,
listing_type.to_string() listing_type.to_string()
)) ))
.link(Settings::get().get_protocol_and_hostname()) .link(Settings::get().get_protocol_and_hostname())
.items(items); .items(items);
if let Some(site_desc) = site_view.description { if let Some(site_desc) = site_view.site.description {
channel_builder.description(&site_desc); channel_builder.description(&site_desc);
} }
@ -175,7 +175,7 @@ fn get_feed_user(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.to_owned())
.title(&format!("{} - {}", site_view.name, user.name)) .title(&format!("{} - {}", site_view.site.name, user.name))
.link(user_url) .link(user_url)
.items(items); .items(items);
@ -201,7 +201,7 @@ fn get_feed_community(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.to_owned())
.title(&format!("{} - {}", site_view.name, community.name)) .title(&format!("{} - {}", site_view.site.name, community.name))
.link(community.actor_id) .link(community.actor_id)
.items(items); .items(items);
@ -231,11 +231,11 @@ fn get_feed_front(
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.to_owned())
.title(&format!("{} - Subscribed", site_view.name)) .title(&format!("{} - Subscribed", site_view.site.name))
.link(Settings::get().get_protocol_and_hostname()) .link(Settings::get().get_protocol_and_hostname())
.items(items); .items(items);
if let Some(site_desc) = site_view.description { if let Some(site_desc) = site_view.site.description {
channel_builder.description(&site_desc); channel_builder.description(&site_desc);
} }
@ -261,14 +261,14 @@ fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, Le
let mut channel_builder = ChannelBuilder::default(); let mut channel_builder = ChannelBuilder::default();
channel_builder channel_builder
.namespaces(RSS_NAMESPACE.to_owned()) .namespaces(RSS_NAMESPACE.to_owned())
.title(&format!("{} - Inbox", site_view.name)) .title(&format!("{} - Inbox", site_view.site.name))
.link(format!( .link(format!(
"{}/inbox", "{}/inbox",
Settings::get().get_protocol_and_hostname() Settings::get().get_protocol_and_hostname()
)) ))
.items(items); .items(items);
if let Some(site_desc) = site_view.description { if let Some(site_desc) = site_view.site.description {
channel_builder.description(&site_desc); channel_builder.description(&site_desc);
} }

View file

@ -1,7 +1,7 @@
use actix_web::{body::Body, error::ErrorBadRequest, *}; use actix_web::{body::Body, error::ErrorBadRequest, *};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api::version; use lemmy_api::version;
use lemmy_db::site_view::SiteView; use lemmy_db::views::site_view::SiteView;
use lemmy_structs::blocking; use lemmy_structs::blocking;
use lemmy_utils::{settings::Settings, LemmyError}; use lemmy_utils::{settings::Settings, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
@ -46,12 +46,11 @@ async fn node_info(context: web::Data<LemmyContext>) -> Result<HttpResponse, Err
}, },
protocols, protocols,
usage: NodeInfoUsage { usage: NodeInfoUsage {
users: NodeInfoUsers { // TODO get these again
total: site_view.number_of_users, users: NodeInfoUsers { total: 0 },
}, local_posts: 0,
local_posts: site_view.number_of_posts, local_comments: 0,
local_comments: site_view.number_of_comments, open_registrations: site_view.site.open_registration,
open_registrations: site_view.open_registration,
}, },
}; };