8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
12 community::{CommunityModerator_, Community_},
18 use lemmy_db_schema::{
21 community::{Community, CommunityModerator},
23 person_mention::{PersonMention, PersonMentionForm},
32 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
33 use lemmy_db_views_actor::{
34 community_person_ban_view::CommunityPersonBanView,
35 community_view::CommunityView,
40 settings::structs::Settings,
46 use serde::{Deserialize, Serialize};
49 #[derive(Serialize, Deserialize, Debug)]
50 pub struct WebFingerLink {
51 pub rel: Option<String>,
52 #[serde(rename(serialize = "type", deserialize = "type"))]
53 pub type_: Option<String>,
54 pub href: Option<Url>,
55 #[serde(skip_serializing_if = "Option::is_none")]
56 pub template: Option<String>,
59 #[derive(Serialize, Deserialize, Debug)]
60 pub struct WebFingerResponse {
62 pub aliases: Vec<Url>,
63 pub links: Vec<WebFingerLink>,
66 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
68 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
71 let pool = pool.clone();
72 let res = actix_web::web::block(move || {
73 let conn = pool.get()?;
75 Ok(res) as Result<_, LemmyError>
82 pub async fn send_local_notifs(
83 mentions: Vec<MentionData>,
89 ) -> Result<Vec<LocalUserId>, LemmyError> {
90 let ids = blocking(pool, move |conn| {
91 do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
98 fn do_send_local_notifs(
100 mentions: &[MentionData],
105 ) -> Vec<LocalUserId> {
106 let mut recipient_ids = Vec::new();
108 // Send the local mentions
109 for mention in mentions
111 .filter(|m| m.is_local() && m.name.ne(&person.name))
112 .collect::<Vec<&MentionData>>()
114 if let Ok(mention_user_view) = LocalUserView::read_from_name(&conn, &mention.name) {
116 // At some point, make it so you can't tag the parent creator either
117 // This can cause two notifications, one for reply and the other for mention
118 recipient_ids.push(mention_user_view.local_user.id);
120 let user_mention_form = PersonMentionForm {
121 recipient_id: mention_user_view.person.id,
122 comment_id: comment.id,
126 // Allow this to fail softly, since comment edits might re-update or replace it
127 // Let the uniqueness handle this fail
128 PersonMention::create(&conn, &user_mention_form).ok();
130 // Send an email to those local users that have notifications on
142 // Send notifs to the parent commenter / poster
143 match comment.parent_id {
145 if let Ok(parent_comment) = Comment::read(&conn, parent_id) {
146 // Don't send a notif to yourself
147 if parent_comment.creator_id != person.id {
148 // Get the parent commenter local_user
149 if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id)
151 recipient_ids.push(parent_user_view.local_user.id);
167 if post.creator_id != person.id {
168 if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) {
169 recipient_ids.push(parent_user_view.local_user.id);
186 pub fn send_email_to_user(
187 local_user_view: &LocalUserView,
190 comment_content: &str,
192 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
196 if let Some(user_email) = &local_user_view.local_user.email {
197 let subject = &format!(
200 Settings::get().hostname(),
201 local_user_view.person.name,
204 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
206 local_user_view.person.name,
208 Settings::get().get_protocol_and_hostname()
210 match send_email(subject, &user_email, &local_user_view.person.name, html) {
212 Err(e) => error!("{}", e),
217 pub async fn is_mod_or_admin(
220 community_id: CommunityId,
221 ) -> Result<(), LemmyError> {
222 let is_mod_or_admin = blocking(pool, move |conn| {
223 CommunityView::is_mod_or_admin(conn, person_id, community_id)
226 if !is_mod_or_admin {
227 return Err(ApiError::err("not_a_mod_or_admin").into());
232 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
233 if !local_user_view.person.admin {
234 return Err(ApiError::err("not_an_admin").into());
239 /// A helper method for showing the bot account
240 pub fn user_show_bot_accounts(local_user_view: &Option<LocalUserView>) -> bool {
241 match local_user_view {
242 Some(uv) => uv.to_owned().local_user.show_bot_accounts,
247 /// A helper method for showing nsfw
248 pub fn user_show_nsfw(local_user_view: &Option<LocalUserView>) -> bool {
249 match &local_user_view {
250 Some(uv) => uv.local_user.show_nsfw,
255 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
256 blocking(pool, move |conn| Post::read(conn, post_id))
258 .map_err(|_| ApiError::err("couldnt_find_post").into())
261 pub async fn get_local_user_view_from_jwt(
264 ) -> Result<LocalUserView, LemmyError> {
265 let claims = Claims::decode(&jwt)
266 .map_err(|_| ApiError::err("not_logged_in"))?
268 let local_user_id = LocalUserId(claims.sub);
269 let local_user_view =
270 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
271 // Check for a site ban
272 if local_user_view.person.banned {
273 return Err(ApiError::err("site_ban").into());
276 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
281 /// Checks if user's token was issued before user's password reset.
282 pub fn check_validator_time(
283 validator_time: &chrono::NaiveDateTime,
285 ) -> Result<(), LemmyError> {
286 let user_validation_time = validator_time.timestamp();
287 if user_validation_time > claims.iat {
288 Err(ApiError::err("not_logged_in").into())
294 pub async fn get_local_user_view_from_jwt_opt(
295 jwt: &Option<String>,
297 ) -> Result<Option<LocalUserView>, LemmyError> {
299 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
304 pub async fn get_local_user_settings_view_from_jwt(
307 ) -> Result<LocalUserSettingsView, LemmyError> {
308 let claims = Claims::decode(&jwt)
309 .map_err(|_| ApiError::err("not_logged_in"))?
311 let local_user_id = LocalUserId(claims.sub);
312 let local_user_view = blocking(pool, move |conn| {
313 LocalUserSettingsView::read(conn, local_user_id)
316 // Check for a site ban
317 if local_user_view.person.banned {
318 return Err(ApiError::err("site_ban").into());
321 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
326 pub async fn get_local_user_settings_view_from_jwt_opt(
327 jwt: &Option<String>,
329 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
331 Some(jwt) => Ok(Some(
332 get_local_user_settings_view_from_jwt(jwt, pool).await?,
338 pub async fn check_community_ban(
340 community_id: CommunityId,
342 ) -> Result<(), LemmyError> {
344 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
345 if blocking(pool, is_banned).await? {
346 Err(ApiError::err("community_ban").into())
352 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
354 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
355 if !site.enable_downvotes {
356 return Err(ApiError::err("downvotes_disabled").into());
362 /// Returns a list of communities that the user moderates
363 /// or if a community_id is supplied validates the user is a moderator
364 /// of that community and returns the community id in a vec
366 /// * `person_id` - the person id of the moderator
367 /// * `community_id` - optional community id to check for moderator privileges
368 /// * `pool` - the diesel db pool
369 pub async fn collect_moderated_communities(
371 community_id: Option<CommunityId>,
373 ) -> Result<Vec<CommunityId>, LemmyError> {
374 if let Some(community_id) = community_id {
375 // if the user provides a community_id, just check for mod/admin privileges
376 is_mod_or_admin(pool, person_id, community_id).await?;
377 Ok(vec![community_id])
379 let ids = blocking(pool, move |conn: &'_ _| {
380 CommunityModerator::get_person_moderated_communities(conn, person_id)
387 pub async fn build_federated_instances(
389 ) -> Result<Option<FederatedInstances>, LemmyError> {
390 if Settings::get().federation().enabled {
391 let distinct_communities = blocking(pool, move |conn| {
392 Community::distinct_federated_communities(conn)
396 let allowed = Settings::get().get_allowed_instances();
397 let blocked = Settings::get().get_blocked_instances();
399 let mut linked = distinct_communities
401 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
402 .collect::<Result<Vec<String>, LemmyError>>()?;
404 if let Some(allowed) = allowed.as_ref() {
405 linked.extend_from_slice(allowed);
408 if let Some(blocked) = blocked.as_ref() {
409 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
412 // Sort and remove dupes
413 linked.sort_unstable();
416 Ok(Some(FederatedInstances {
426 /// Checks the password length
427 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
429 Err(ApiError::err("invalid_password").into())
435 /// Checks the site description length
436 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
437 if description.len() > 150 {
438 Err(ApiError::err("site_description_length_overflow").into())