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.local_user.admin {
234 return Err(ApiError::err("not_an_admin").into());
239 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
240 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
241 Ok(post) => Ok(post),
242 Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
246 pub async fn get_local_user_view_from_jwt(
249 ) -> Result<LocalUserView, LemmyError> {
250 let claims = match Claims::decode(&jwt) {
251 Ok(claims) => claims.claims,
252 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
254 let local_user_id = LocalUserId(claims.sub);
255 let local_user_view =
256 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
257 // Check for a site ban
258 if local_user_view.person.banned {
259 return Err(ApiError::err("site_ban").into());
262 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
267 /// Checks if user's token was issued before user's password reset.
268 pub fn check_validator_time(
269 validator_time: &chrono::NaiveDateTime,
271 ) -> Result<(), LemmyError> {
272 let user_validation_time = validator_time.timestamp();
273 if user_validation_time > claims.iat {
274 Err(ApiError::err("not_logged_in").into())
280 pub async fn get_local_user_view_from_jwt_opt(
281 jwt: &Option<String>,
283 ) -> Result<Option<LocalUserView>, LemmyError> {
285 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
290 pub async fn get_local_user_settings_view_from_jwt(
293 ) -> Result<LocalUserSettingsView, LemmyError> {
294 let claims = match Claims::decode(&jwt) {
295 Ok(claims) => claims.claims,
296 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
298 let local_user_id = LocalUserId(claims.sub);
299 let local_user_view = blocking(pool, move |conn| {
300 LocalUserSettingsView::read(conn, local_user_id)
303 // Check for a site ban
304 if local_user_view.person.banned {
305 return Err(ApiError::err("site_ban").into());
308 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
313 pub async fn get_local_user_settings_view_from_jwt_opt(
314 jwt: &Option<String>,
316 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
318 Some(jwt) => Ok(Some(
319 get_local_user_settings_view_from_jwt(jwt, pool).await?,
325 pub async fn check_community_ban(
327 community_id: CommunityId,
329 ) -> Result<(), LemmyError> {
331 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
332 if blocking(pool, is_banned).await? {
333 Err(ApiError::err("community_ban").into())
339 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
341 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
342 if !site.enable_downvotes {
343 return Err(ApiError::err("downvotes_disabled").into());
349 /// Returns a list of communities that the user moderates
350 /// or if a community_id is supplied validates the user is a moderator
351 /// of that community and returns the community id in a vec
353 /// * `person_id` - the person id of the moderator
354 /// * `community_id` - optional community id to check for moderator privileges
355 /// * `pool` - the diesel db pool
356 pub async fn collect_moderated_communities(
358 community_id: Option<CommunityId>,
360 ) -> Result<Vec<CommunityId>, LemmyError> {
361 if let Some(community_id) = community_id {
362 // if the user provides a community_id, just check for mod/admin privileges
363 is_mod_or_admin(pool, person_id, community_id).await?;
364 Ok(vec![community_id])
366 let ids = blocking(pool, move |conn: &'_ _| {
367 CommunityModerator::get_person_moderated_communities(conn, person_id)
374 pub async fn build_federated_instances(
376 ) -> Result<Option<FederatedInstances>, LemmyError> {
377 if Settings::get().federation().enabled {
378 let distinct_communities = blocking(pool, move |conn| {
379 Community::distinct_federated_communities(conn)
383 let allowed = Settings::get().get_allowed_instances();
384 let blocked = Settings::get().get_blocked_instances();
386 let mut linked = distinct_communities
388 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
389 .collect::<Result<Vec<String>, LemmyError>>()?;
391 if let Some(allowed) = allowed.as_ref() {
392 linked.extend_from_slice(allowed);
395 if let Some(blocked) = blocked.as_ref() {
396 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
399 // Sort and remove dupes
400 linked.sort_unstable();
403 Ok(Some(FederatedInstances {
413 /// Checks the password length
414 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
416 Err(ApiError::err("invalid_password").into())