1 use actix_web::{web, web::Data};
2 use lemmy_db_queries::{
4 community::{CommunityModerator_, Community_},
6 user::UserSafeSettings_,
11 use lemmy_db_schema::source::{
12 community::{Community, CommunityModerator},
15 user::{UserSafeSettings, User_},
17 use lemmy_db_views_actor::{
18 community_user_ban_view::CommunityUserBanView,
19 community_view::CommunityView,
21 use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*, websocket::*};
22 use lemmy_utils::{claims::Claims, settings::Settings, ApiError, ConnectionId, LemmyError};
23 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
24 use serde::Deserialize;
25 use std::process::Command;
36 #[async_trait::async_trait(?Send)]
38 type Response: serde::ser::Serialize + Send;
42 context: &Data<LemmyContext>,
43 websocket_id: Option<ConnectionId>,
44 ) -> Result<Self::Response, LemmyError>;
47 pub(crate) async fn is_mod_or_admin(
51 ) -> Result<(), LemmyError> {
52 let is_mod_or_admin = blocking(pool, move |conn| {
53 CommunityView::is_mod_or_admin(conn, user_id, community_id)
57 return Err(ApiError::err("not_a_mod_or_admin").into());
61 pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
62 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
64 return Err(ApiError::err("not_an_admin").into());
69 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
70 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
72 Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
76 pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
77 let claims = match Claims::decode(&jwt) {
78 Ok(claims) => claims.claims,
79 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
81 let user_id = claims.id;
82 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
83 // Check for a site ban
85 return Err(ApiError::err("site_ban").into());
90 pub(crate) async fn get_user_from_jwt_opt(
93 ) -> Result<Option<User_>, LemmyError> {
95 Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
100 pub(crate) async fn get_user_safe_settings_from_jwt(
103 ) -> Result<UserSafeSettings, 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 user_id = claims.id;
109 let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
110 // Check for a site ban
112 return Err(ApiError::err("site_ban").into());
117 pub(crate) async fn get_user_safe_settings_from_jwt_opt(
118 jwt: &Option<String>,
120 ) -> Result<Option<UserSafeSettings>, LemmyError> {
122 Some(jwt) => Ok(Some(get_user_safe_settings_from_jwt(jwt, pool).await?)),
127 pub(crate) async fn check_community_ban(
131 ) -> Result<(), LemmyError> {
132 let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
133 if blocking(pool, is_banned).await? {
134 Err(ApiError::err("community_ban").into())
140 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
142 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
143 if !site.enable_downvotes {
144 return Err(ApiError::err("downvotes_disabled").into());
150 /// Returns a list of communities that the user moderates
151 /// or if a community_id is supplied validates the user is a moderator
152 /// of that community and returns the community id in a vec
154 /// * `user_id` - the user id of the moderator
155 /// * `community_id` - optional community id to check for moderator privileges
156 /// * `pool` - the diesel db pool
157 pub(crate) async fn collect_moderated_communities(
159 community_id: Option<i32>,
161 ) -> Result<Vec<i32>, LemmyError> {
162 if let Some(community_id) = community_id {
163 // if the user provides a community_id, just check for mod/admin privileges
164 is_mod_or_admin(pool, user_id, community_id).await?;
165 Ok(vec![community_id])
167 let ids = blocking(pool, move |conn: &'_ _| {
168 CommunityModerator::get_user_moderated_communities(conn, user_id)
175 pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
176 if let Some(Some(item)) = &item {
177 if Url::parse(item).is_err() {
178 return Err(ApiError::err("invalid_url").into());
184 pub(crate) async fn build_federated_instances(
186 ) -> Result<Option<FederatedInstances>, LemmyError> {
187 if Settings::get().federation.enabled {
188 let distinct_communities = blocking(pool, move |conn| {
189 Community::distinct_federated_communities(conn)
193 let allowed = Settings::get().get_allowed_instances();
194 let blocked = Settings::get().get_blocked_instances();
196 let mut linked = distinct_communities
198 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
199 .collect::<Result<Vec<String>, LemmyError>>()?;
201 linked.extend_from_slice(&allowed);
202 linked.retain(|a| !blocked.contains(a) && !a.eq("") && !a.eq(&Settings::get().hostname));
204 // Sort and remove dupes
205 linked.sort_unstable();
208 Ok(Some(FederatedInstances {
218 pub async fn match_websocket_operation(
219 context: LemmyContext,
223 ) -> Result<String, LemmyError> {
226 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
227 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
228 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
229 UserOperation::GetUserDetails => {
230 do_websocket_operation::<GetUserDetails>(context, id, op, data).await
232 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
233 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
234 UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
235 UserOperation::GetUserMentions => {
236 do_websocket_operation::<GetUserMentions>(context, id, op, data).await
238 UserOperation::MarkUserMentionAsRead => {
239 do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
241 UserOperation::MarkAllAsRead => {
242 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
244 UserOperation::DeleteAccount => {
245 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
247 UserOperation::PasswordReset => {
248 do_websocket_operation::<PasswordReset>(context, id, op, data).await
250 UserOperation::PasswordChange => {
251 do_websocket_operation::<PasswordChange>(context, id, op, data).await
253 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
254 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
255 UserOperation::CommunityJoin => {
256 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
258 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
259 UserOperation::SaveUserSettings => {
260 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
262 UserOperation::GetReportCount => {
263 do_websocket_operation::<GetReportCount>(context, id, op, data).await
266 // Private Message ops
267 UserOperation::CreatePrivateMessage => {
268 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
270 UserOperation::EditPrivateMessage => {
271 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
273 UserOperation::DeletePrivateMessage => {
274 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
276 UserOperation::MarkPrivateMessageAsRead => {
277 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
279 UserOperation::GetPrivateMessages => {
280 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
284 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
285 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
286 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
287 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
288 UserOperation::GetSiteConfig => {
289 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
291 UserOperation::SaveSiteConfig => {
292 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
294 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
295 UserOperation::TransferCommunity => {
296 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
298 UserOperation::TransferSite => {
299 do_websocket_operation::<TransferSite>(context, id, op, data).await
301 UserOperation::ListCategories => {
302 do_websocket_operation::<ListCategories>(context, id, op, data).await
306 UserOperation::GetCommunity => {
307 do_websocket_operation::<GetCommunity>(context, id, op, data).await
309 UserOperation::ListCommunities => {
310 do_websocket_operation::<ListCommunities>(context, id, op, data).await
312 UserOperation::CreateCommunity => {
313 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
315 UserOperation::EditCommunity => {
316 do_websocket_operation::<EditCommunity>(context, id, op, data).await
318 UserOperation::DeleteCommunity => {
319 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
321 UserOperation::RemoveCommunity => {
322 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
324 UserOperation::FollowCommunity => {
325 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
327 UserOperation::GetFollowedCommunities => {
328 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
330 UserOperation::BanFromCommunity => {
331 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
333 UserOperation::AddModToCommunity => {
334 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
338 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
339 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
340 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
341 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
342 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
343 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
344 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
345 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
346 UserOperation::CreatePostLike => {
347 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
349 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
350 UserOperation::CreatePostReport => {
351 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
353 UserOperation::ListPostReports => {
354 do_websocket_operation::<ListPostReports>(context, id, op, data).await
356 UserOperation::ResolvePostReport => {
357 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
361 UserOperation::CreateComment => {
362 do_websocket_operation::<CreateComment>(context, id, op, data).await
364 UserOperation::EditComment => {
365 do_websocket_operation::<EditComment>(context, id, op, data).await
367 UserOperation::DeleteComment => {
368 do_websocket_operation::<DeleteComment>(context, id, op, data).await
370 UserOperation::RemoveComment => {
371 do_websocket_operation::<RemoveComment>(context, id, op, data).await
373 UserOperation::MarkCommentAsRead => {
374 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
376 UserOperation::SaveComment => {
377 do_websocket_operation::<SaveComment>(context, id, op, data).await
379 UserOperation::GetComments => {
380 do_websocket_operation::<GetComments>(context, id, op, data).await
382 UserOperation::CreateCommentLike => {
383 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
385 UserOperation::CreateCommentReport => {
386 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
388 UserOperation::ListCommentReports => {
389 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
391 UserOperation::ResolveCommentReport => {
392 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
397 async fn do_websocket_operation<'a, 'b, Data>(
398 context: LemmyContext,
402 ) -> Result<String, LemmyError>
404 for<'de> Data: Deserialize<'de> + 'a,
407 let parsed_data: Data = serde_json::from_str(&data)?;
408 let res = parsed_data
409 .perform(&web::Data::new(context), Some(id))
411 serialize_websocket_message(&op, &res)
414 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
415 let mut built_text = String::new();
417 // Building proper speech text for espeak
418 for mut c in captcha.chars() {
419 let new_str = if c.is_alphabetic() {
420 if c.is_lowercase() {
421 c.make_ascii_uppercase();
422 format!("lower case {} ... ", c)
424 c.make_ascii_uppercase();
425 format!("capital {} ... ", c)
431 built_text.push_str(&new_str);
434 espeak_wav_base64(&built_text)
437 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
438 // Make a temp file path
439 let uuid = uuid::Uuid::new_v4().to_string();
440 let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
442 // Write the wav file
443 Command::new("espeak")
449 // Read the wav file bytes
450 let bytes = std::fs::read(&file_path)?;
453 std::fs::remove_file(file_path)?;
456 let base64 = base64::encode(bytes);
463 use crate::captcha_espeak_wav_base64;
467 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())