1 use actix_web::{web, web::Data};
2 use lemmy_api_structs::{
11 use lemmy_db_queries::{
13 community::{CommunityModerator_, Community_},
15 local_user::LocalUserSettings_,
16 local_user::LocalUser_,
21 use lemmy_db_schema::source::{
22 community::{Community, CommunityModerator},
25 person::{Person, PersonSafe},
26 local_user::LocalUserSettings,
27 local_user::LocalUser,
29 use lemmy_db_views_actor::{
30 community_person_ban_view::CommunityPersonBanView,
31 community_view::CommunityView,
33 use lemmy_db_views::local_user_view::{LocalUserView, LocalUserSettingsView};
36 settings::structs::Settings,
41 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
42 use serde::Deserialize;
43 use std::process::Command;
54 #[async_trait::async_trait(?Send)]
56 type Response: serde::ser::Serialize + Send;
60 context: &Data<LemmyContext>,
61 websocket_id: Option<ConnectionId>,
62 ) -> Result<Self::Response, LemmyError>;
65 pub(crate) async fn is_mod_or_admin(
69 ) -> Result<(), LemmyError> {
70 let is_mod_or_admin = blocking(pool, move |conn| {
71 CommunityView::is_mod_or_admin(conn, person_id, community_id)
75 return Err(ApiError::err("not_a_mod_or_admin").into());
80 // TODO this probably isn't necessary anymore
81 // pub async fn is_admin(pool: &DbPool, person_id: i32) -> Result<(), LemmyError> {
82 // let user = blocking(pool, move |conn| LocalUser::read(conn, person_id)).await??;
84 // return Err(ApiError::err("not_an_admin").into());
89 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
90 if !local_user_view.local_user.admin {
91 return Err(ApiError::err("not_an_admin").into());
96 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
97 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
99 Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
103 pub(crate) async fn get_local_user_view_from_jwt(jwt: &str, pool: &DbPool) -> Result<LocalUserView, LemmyError> {
104 let claims = match Claims::decode(&jwt) {
105 Ok(claims) => claims.claims,
106 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
108 let person_id = claims.id;
109 let local_user_view = blocking(pool, move |conn| LocalUserView::read(conn, person_id)).await??;
110 // Check for a site ban
111 if local_user_view.person.banned {
112 return Err(ApiError::err("site_ban").into());
117 pub(crate) async fn get_local_user_view_from_jwt_opt(
118 jwt: &Option<String>,
120 ) -> Result<Option<LocalUserView>, LemmyError> {
122 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
127 pub(crate) async fn get_local_user_settings_view_from_jwt(jwt: &str, pool: &DbPool) -> Result<LocalUserSettingsView, LemmyError> {
128 let claims = match Claims::decode(&jwt) {
129 Ok(claims) => claims.claims,
130 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
132 let person_id = claims.id;
133 let local_user_view = blocking(pool, move |conn| LocalUserSettingsView::read(conn, person_id)).await??;
134 // Check for a site ban
135 if local_user_view.person.banned {
136 return Err(ApiError::err("site_ban").into());
141 pub(crate) async fn get_local_user_settings_view_from_jwt_opt(
142 jwt: &Option<String>,
144 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
146 Some(jwt) => Ok(Some(get_local_user_settings_view_from_jwt(jwt, pool).await?)),
151 pub(crate) async fn check_community_ban(
155 ) -> Result<(), LemmyError> {
156 let is_banned = move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
157 if blocking(pool, is_banned).await? {
158 Err(ApiError::err("community_ban").into())
164 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
166 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
167 if !site.enable_downvotes {
168 return Err(ApiError::err("downvotes_disabled").into());
174 /// Returns a list of communities that the user moderates
175 /// or if a community_id is supplied validates the user is a moderator
176 /// of that community and returns the community id in a vec
178 /// * `user_id` - the user id of the moderator
179 /// * `community_id` - optional community id to check for moderator privileges
180 /// * `pool` - the diesel db pool
181 pub(crate) async fn collect_moderated_communities(
183 community_id: Option<i32>,
185 ) -> Result<Vec<i32>, LemmyError> {
186 if let Some(community_id) = community_id {
187 // if the user provides a community_id, just check for mod/admin privileges
188 is_mod_or_admin(pool, user_id, community_id).await?;
189 Ok(vec![community_id])
191 let ids = blocking(pool, move |conn: &'_ _| {
192 CommunityModerator::get_person_moderated_communities(conn, user_id)
199 pub(crate) async fn build_federated_instances(
201 ) -> Result<Option<FederatedInstances>, LemmyError> {
202 if Settings::get().federation().enabled {
203 let distinct_communities = blocking(pool, move |conn| {
204 Community::distinct_federated_communities(conn)
208 let allowed = Settings::get().get_allowed_instances();
209 let blocked = Settings::get().get_blocked_instances();
211 let mut linked = distinct_communities
213 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
214 .collect::<Result<Vec<String>, LemmyError>>()?;
216 if let Some(allowed) = allowed.as_ref() {
217 linked.extend_from_slice(allowed);
220 if let Some(blocked) = blocked.as_ref() {
221 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
224 // Sort and remove dupes
225 linked.sort_unstable();
228 Ok(Some(FederatedInstances {
238 pub async fn match_websocket_operation(
239 context: LemmyContext,
243 ) -> Result<String, LemmyError> {
246 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
247 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
248 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
249 UserOperation::GetPersonDetails => {
250 do_websocket_operation::<GetPersonDetails>(context, id, op, data).await
252 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
253 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
254 UserOperation::BanPerson => do_websocket_operation::<BanPerson>(context, id, op, data).await,
255 UserOperation::GetPersonMentions => {
256 do_websocket_operation::<GetPersonMentions>(context, id, op, data).await
258 UserOperation::MarkPersonMentionAsRead => {
259 do_websocket_operation::<MarkPersonMentionAsRead>(context, id, op, data).await
261 UserOperation::MarkAllAsRead => {
262 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
264 UserOperation::DeleteAccount => {
265 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
267 UserOperation::PasswordReset => {
268 do_websocket_operation::<PasswordReset>(context, id, op, data).await
270 UserOperation::PasswordChange => {
271 do_websocket_operation::<PasswordChange>(context, id, op, data).await
273 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
274 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
275 UserOperation::CommunityJoin => {
276 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
278 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
279 UserOperation::SaveUserSettings => {
280 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
282 UserOperation::GetReportCount => {
283 do_websocket_operation::<GetReportCount>(context, id, op, data).await
286 // Private Message ops
287 UserOperation::CreatePrivateMessage => {
288 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
290 UserOperation::EditPrivateMessage => {
291 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
293 UserOperation::DeletePrivateMessage => {
294 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
296 UserOperation::MarkPrivateMessageAsRead => {
297 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
299 UserOperation::GetPrivateMessages => {
300 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
304 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
305 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
306 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
307 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
308 UserOperation::GetSiteConfig => {
309 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
311 UserOperation::SaveSiteConfig => {
312 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
314 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
315 UserOperation::TransferCommunity => {
316 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
318 UserOperation::TransferSite => {
319 do_websocket_operation::<TransferSite>(context, id, op, data).await
323 UserOperation::GetCommunity => {
324 do_websocket_operation::<GetCommunity>(context, id, op, data).await
326 UserOperation::ListCommunities => {
327 do_websocket_operation::<ListCommunities>(context, id, op, data).await
329 UserOperation::CreateCommunity => {
330 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
332 UserOperation::EditCommunity => {
333 do_websocket_operation::<EditCommunity>(context, id, op, data).await
335 UserOperation::DeleteCommunity => {
336 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
338 UserOperation::RemoveCommunity => {
339 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
341 UserOperation::FollowCommunity => {
342 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
344 UserOperation::GetFollowedCommunities => {
345 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
347 UserOperation::BanFromCommunity => {
348 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
350 UserOperation::AddModToCommunity => {
351 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
355 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
356 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
357 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
358 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
359 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
360 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
361 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
362 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
363 UserOperation::CreatePostLike => {
364 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
366 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
367 UserOperation::CreatePostReport => {
368 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
370 UserOperation::ListPostReports => {
371 do_websocket_operation::<ListPostReports>(context, id, op, data).await
373 UserOperation::ResolvePostReport => {
374 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
378 UserOperation::CreateComment => {
379 do_websocket_operation::<CreateComment>(context, id, op, data).await
381 UserOperation::EditComment => {
382 do_websocket_operation::<EditComment>(context, id, op, data).await
384 UserOperation::DeleteComment => {
385 do_websocket_operation::<DeleteComment>(context, id, op, data).await
387 UserOperation::RemoveComment => {
388 do_websocket_operation::<RemoveComment>(context, id, op, data).await
390 UserOperation::MarkCommentAsRead => {
391 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
393 UserOperation::SaveComment => {
394 do_websocket_operation::<SaveComment>(context, id, op, data).await
396 UserOperation::GetComments => {
397 do_websocket_operation::<GetComments>(context, id, op, data).await
399 UserOperation::CreateCommentLike => {
400 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
402 UserOperation::CreateCommentReport => {
403 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
405 UserOperation::ListCommentReports => {
406 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
408 UserOperation::ResolveCommentReport => {
409 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
414 async fn do_websocket_operation<'a, 'b, Data>(
415 context: LemmyContext,
419 ) -> Result<String, LemmyError>
421 for<'de> Data: Deserialize<'de> + 'a,
424 let parsed_data: Data = serde_json::from_str(&data)?;
425 let res = parsed_data
426 .perform(&web::Data::new(context), Some(id))
428 serialize_websocket_message(&op, &res)
431 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
432 let mut built_text = String::new();
434 // Building proper speech text for espeak
435 for mut c in captcha.chars() {
436 let new_str = if c.is_alphabetic() {
437 if c.is_lowercase() {
438 c.make_ascii_uppercase();
439 format!("lower case {} ... ", c)
441 c.make_ascii_uppercase();
442 format!("capital {} ... ", c)
448 built_text.push_str(&new_str);
451 espeak_wav_base64(&built_text)
454 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
455 // Make a temp file path
456 let uuid = uuid::Uuid::new_v4().to_string();
457 let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
459 // Write the wav file
460 Command::new("espeak")
466 // Read the wav file bytes
467 let bytes = std::fs::read(&file_path)?;
470 std::fs::remove_file(file_path)?;
473 let base64 = base64::encode(bytes);
478 /// Checks the password length
479 pub(crate) fn password_length_check(pass: &str) -> Result<(), LemmyError> {
481 Err(ApiError::err("invalid_password").into())
489 use crate::captcha_espeak_wav_base64;
493 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())