1 use actix_web::{web, web::Data};
2 use lemmy_api_structs::{
11 use lemmy_db_queries::{
13 community::{CommunityModerator_, Community_},
15 user::UserSafeSettings_,
20 use lemmy_db_schema::source::{
21 community::{Community, CommunityModerator},
24 user::{UserSafeSettings, User_},
26 use lemmy_db_views_actor::{
27 community_user_ban_view::CommunityUserBanView,
28 community_view::CommunityView,
32 settings::structs::Settings,
37 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
38 use serde::Deserialize;
39 use std::process::Command;
50 #[async_trait::async_trait(?Send)]
52 type Response: serde::ser::Serialize + Send;
56 context: &Data<LemmyContext>,
57 websocket_id: Option<ConnectionId>,
58 ) -> Result<Self::Response, LemmyError>;
61 pub(crate) async fn is_mod_or_admin(
65 ) -> Result<(), LemmyError> {
66 let is_mod_or_admin = blocking(pool, move |conn| {
67 CommunityView::is_mod_or_admin(conn, user_id, community_id)
71 return Err(ApiError::err("not_a_mod_or_admin").into());
75 pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
76 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
78 return Err(ApiError::err("not_an_admin").into());
83 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
84 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
86 Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
90 pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
91 let claims = match Claims::decode(&jwt) {
92 Ok(claims) => claims.claims,
93 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
95 let user_id = claims.id;
96 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
97 // Check for a site ban
99 return Err(ApiError::err("site_ban").into());
104 pub(crate) async fn get_user_from_jwt_opt(
105 jwt: &Option<String>,
107 ) -> Result<Option<User_>, LemmyError> {
109 Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
114 pub(crate) async fn get_user_safe_settings_from_jwt(
117 ) -> Result<UserSafeSettings, LemmyError> {
118 let claims = match Claims::decode(&jwt) {
119 Ok(claims) => claims.claims,
120 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
122 let user_id = claims.id;
123 let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
124 // Check for a site ban
126 return Err(ApiError::err("site_ban").into());
131 pub(crate) async fn get_user_safe_settings_from_jwt_opt(
132 jwt: &Option<String>,
134 ) -> Result<Option<UserSafeSettings>, LemmyError> {
136 Some(jwt) => Ok(Some(get_user_safe_settings_from_jwt(jwt, pool).await?)),
141 pub(crate) async fn check_community_ban(
145 ) -> Result<(), LemmyError> {
146 let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
147 if blocking(pool, is_banned).await? {
148 Err(ApiError::err("community_ban").into())
154 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
156 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
157 if !site.enable_downvotes {
158 return Err(ApiError::err("downvotes_disabled").into());
164 /// Returns a list of communities that the user moderates
165 /// or if a community_id is supplied validates the user is a moderator
166 /// of that community and returns the community id in a vec
168 /// * `user_id` - the user id of the moderator
169 /// * `community_id` - optional community id to check for moderator privileges
170 /// * `pool` - the diesel db pool
171 pub(crate) async fn collect_moderated_communities(
173 community_id: Option<i32>,
175 ) -> Result<Vec<i32>, LemmyError> {
176 if let Some(community_id) = community_id {
177 // if the user provides a community_id, just check for mod/admin privileges
178 is_mod_or_admin(pool, user_id, community_id).await?;
179 Ok(vec![community_id])
181 let ids = blocking(pool, move |conn: &'_ _| {
182 CommunityModerator::get_user_moderated_communities(conn, user_id)
189 pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
190 if let Some(Some(item)) = &item {
191 if Url::parse(item).is_err() {
192 return Err(ApiError::err("invalid_url").into());
198 pub(crate) async fn build_federated_instances(
200 ) -> Result<Option<FederatedInstances>, LemmyError> {
201 if Settings::get().federation().enabled {
202 let distinct_communities = blocking(pool, move |conn| {
203 Community::distinct_federated_communities(conn)
207 let allowed = Settings::get().get_allowed_instances();
208 let blocked = Settings::get().get_blocked_instances();
210 let mut linked = distinct_communities
212 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
213 .collect::<Result<Vec<String>, LemmyError>>()?;
215 if let Some(allowed) = allowed.as_ref() {
216 linked.extend_from_slice(allowed);
219 if let Some(blocked) = blocked.as_ref() {
220 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
223 // Sort and remove dupes
224 linked.sort_unstable();
227 Ok(Some(FederatedInstances {
237 pub async fn match_websocket_operation(
238 context: LemmyContext,
242 ) -> Result<String, LemmyError> {
245 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
246 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
247 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
248 UserOperation::GetUserDetails => {
249 do_websocket_operation::<GetUserDetails>(context, id, op, data).await
251 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
252 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
253 UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
254 UserOperation::GetUserMentions => {
255 do_websocket_operation::<GetUserMentions>(context, id, op, data).await
257 UserOperation::MarkUserMentionAsRead => {
258 do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
260 UserOperation::MarkAllAsRead => {
261 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
263 UserOperation::DeleteAccount => {
264 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
266 UserOperation::PasswordReset => {
267 do_websocket_operation::<PasswordReset>(context, id, op, data).await
269 UserOperation::PasswordChange => {
270 do_websocket_operation::<PasswordChange>(context, id, op, data).await
272 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
273 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
274 UserOperation::CommunityJoin => {
275 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
277 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
278 UserOperation::SaveUserSettings => {
279 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
281 UserOperation::GetReportCount => {
282 do_websocket_operation::<GetReportCount>(context, id, op, data).await
285 // Private Message ops
286 UserOperation::CreatePrivateMessage => {
287 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
289 UserOperation::EditPrivateMessage => {
290 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
292 UserOperation::DeletePrivateMessage => {
293 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
295 UserOperation::MarkPrivateMessageAsRead => {
296 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
298 UserOperation::GetPrivateMessages => {
299 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
303 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
304 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
305 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
306 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
307 UserOperation::GetSiteConfig => {
308 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
310 UserOperation::SaveSiteConfig => {
311 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
313 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
314 UserOperation::TransferCommunity => {
315 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
317 UserOperation::TransferSite => {
318 do_websocket_operation::<TransferSite>(context, id, op, data).await
322 UserOperation::GetCommunity => {
323 do_websocket_operation::<GetCommunity>(context, id, op, data).await
325 UserOperation::ListCommunities => {
326 do_websocket_operation::<ListCommunities>(context, id, op, data).await
328 UserOperation::CreateCommunity => {
329 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
331 UserOperation::EditCommunity => {
332 do_websocket_operation::<EditCommunity>(context, id, op, data).await
334 UserOperation::DeleteCommunity => {
335 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
337 UserOperation::RemoveCommunity => {
338 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
340 UserOperation::FollowCommunity => {
341 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
343 UserOperation::GetFollowedCommunities => {
344 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
346 UserOperation::BanFromCommunity => {
347 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
349 UserOperation::AddModToCommunity => {
350 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
354 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
355 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
356 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
357 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
358 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
359 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
360 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
361 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
362 UserOperation::CreatePostLike => {
363 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
365 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
366 UserOperation::CreatePostReport => {
367 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
369 UserOperation::ListPostReports => {
370 do_websocket_operation::<ListPostReports>(context, id, op, data).await
372 UserOperation::ResolvePostReport => {
373 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
377 UserOperation::CreateComment => {
378 do_websocket_operation::<CreateComment>(context, id, op, data).await
380 UserOperation::EditComment => {
381 do_websocket_operation::<EditComment>(context, id, op, data).await
383 UserOperation::DeleteComment => {
384 do_websocket_operation::<DeleteComment>(context, id, op, data).await
386 UserOperation::RemoveComment => {
387 do_websocket_operation::<RemoveComment>(context, id, op, data).await
389 UserOperation::MarkCommentAsRead => {
390 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
392 UserOperation::SaveComment => {
393 do_websocket_operation::<SaveComment>(context, id, op, data).await
395 UserOperation::GetComments => {
396 do_websocket_operation::<GetComments>(context, id, op, data).await
398 UserOperation::CreateCommentLike => {
399 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
401 UserOperation::CreateCommentReport => {
402 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
404 UserOperation::ListCommentReports => {
405 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
407 UserOperation::ResolveCommentReport => {
408 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
413 async fn do_websocket_operation<'a, 'b, Data>(
414 context: LemmyContext,
418 ) -> Result<String, LemmyError>
420 for<'de> Data: Deserialize<'de> + 'a,
423 let parsed_data: Data = serde_json::from_str(&data)?;
424 let res = parsed_data
425 .perform(&web::Data::new(context), Some(id))
427 serialize_websocket_message(&op, &res)
430 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
431 let mut built_text = String::new();
433 // Building proper speech text for espeak
434 for mut c in captcha.chars() {
435 let new_str = if c.is_alphabetic() {
436 if c.is_lowercase() {
437 c.make_ascii_uppercase();
438 format!("lower case {} ... ", c)
440 c.make_ascii_uppercase();
441 format!("capital {} ... ", c)
447 built_text.push_str(&new_str);
450 espeak_wav_base64(&built_text)
453 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
454 // Make a temp file path
455 let uuid = uuid::Uuid::new_v4().to_string();
456 let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
458 // Write the wav file
459 Command::new("espeak")
465 // Read the wav file bytes
466 let bytes = std::fs::read(&file_path)?;
469 std::fs::remove_file(file_path)?;
472 let base64 = base64::encode(bytes);
479 use crate::captcha_espeak_wav_base64;
483 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())