1 use crate::claims::Claims;
2 use actix_web::{web, web::Data};
3 use lemmy_db_queries::{
5 community::{CommunityModerator_, Community_},
7 user::UserSafeSettings_,
12 use lemmy_db_schema::source::{
13 community::{Community, CommunityModerator},
16 user::{UserSafeSettings, User_},
18 use lemmy_db_views_actor::{
19 community_user_ban_view::CommunityUserBanView,
20 community_view::CommunityView,
22 use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*, websocket::*};
23 use lemmy_utils::{settings::Settings, APIError, ConnectionId, LemmyError};
24 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
25 use serde::Deserialize;
26 use std::process::Command;
38 #[async_trait::async_trait(?Send)]
40 type Response: serde::ser::Serialize + Send;
44 context: &Data<LemmyContext>,
45 websocket_id: Option<ConnectionId>,
46 ) -> Result<Self::Response, LemmyError>;
49 pub(crate) async fn is_mod_or_admin(
53 ) -> Result<(), LemmyError> {
54 let is_mod_or_admin = blocking(pool, move |conn| {
55 CommunityView::is_mod_or_admin(conn, user_id, community_id)
59 return Err(APIError::err("not_a_mod_or_admin").into());
63 pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
64 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
66 return Err(APIError::err("not_an_admin").into());
71 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
72 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
74 Err(_e) => Err(APIError::err("couldnt_find_post").into()),
78 pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
79 let claims = match Claims::decode(&jwt) {
80 Ok(claims) => claims.claims,
81 Err(_e) => return Err(APIError::err("not_logged_in").into()),
83 let user_id = claims.id;
84 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
85 // Check for a site ban
87 return Err(APIError::err("site_ban").into());
92 pub(crate) async fn get_user_from_jwt_opt(
95 ) -> Result<Option<User_>, LemmyError> {
97 Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
102 pub(crate) async fn get_user_safe_settings_from_jwt(
105 ) -> Result<UserSafeSettings, LemmyError> {
106 let claims = match Claims::decode(&jwt) {
107 Ok(claims) => claims.claims,
108 Err(_e) => return Err(APIError::err("not_logged_in").into()),
110 let user_id = claims.id;
111 let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
112 // Check for a site ban
114 return Err(APIError::err("site_ban").into());
119 pub(crate) async fn get_user_safe_settings_from_jwt_opt(
120 jwt: &Option<String>,
122 ) -> Result<Option<UserSafeSettings>, LemmyError> {
124 Some(jwt) => Ok(Some(get_user_safe_settings_from_jwt(jwt, pool).await?)),
129 pub(crate) async fn check_community_ban(
133 ) -> Result<(), LemmyError> {
134 let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
135 if blocking(pool, is_banned).await? {
136 Err(APIError::err("community_ban").into())
142 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
144 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
145 if !site.enable_downvotes {
146 return Err(APIError::err("downvotes_disabled").into());
152 /// Returns a list of communities that the user moderates
153 /// or if a community_id is supplied validates the user is a moderator
154 /// of that community and returns the community id in a vec
156 /// * `user_id` - the user id of the moderator
157 /// * `community_id` - optional community id to check for moderator privileges
158 /// * `pool` - the diesel db pool
159 pub(crate) async fn collect_moderated_communities(
161 community_id: Option<i32>,
163 ) -> Result<Vec<i32>, LemmyError> {
164 if let Some(community_id) = community_id {
165 // if the user provides a community_id, just check for mod/admin privileges
166 is_mod_or_admin(pool, user_id, community_id).await?;
167 Ok(vec![community_id])
169 let ids = blocking(pool, move |conn: &'_ _| {
170 CommunityModerator::get_user_moderated_communities(conn, user_id)
177 pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
178 if let Some(Some(item)) = &item {
179 if Url::parse(item).is_err() {
180 return Err(APIError::err("invalid_url").into());
186 pub(crate) async fn linked_instances(pool: &DbPool) -> Result<Vec<String>, LemmyError> {
187 let mut instances: Vec<String> = Vec::new();
189 if Settings::get().federation.enabled {
190 let distinct_communities = blocking(pool, move |conn| {
191 Community::distinct_federated_communities(conn)
195 instances = distinct_communities
197 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
198 .collect::<Result<Vec<String>, LemmyError>>()?;
200 instances.append(&mut Settings::get().get_allowed_instances());
201 instances.retain(|a| {
202 !Settings::get().get_blocked_instances().contains(a)
204 && !a.eq(&Settings::get().hostname)
207 // Sort and remove dupes
208 instances.sort_unstable();
215 pub async fn match_websocket_operation(
216 context: LemmyContext,
220 ) -> Result<String, LemmyError> {
223 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
224 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
225 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
226 UserOperation::GetUserDetails => {
227 do_websocket_operation::<GetUserDetails>(context, id, op, data).await
229 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
230 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
231 UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
232 UserOperation::GetUserMentions => {
233 do_websocket_operation::<GetUserMentions>(context, id, op, data).await
235 UserOperation::MarkUserMentionAsRead => {
236 do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
238 UserOperation::MarkAllAsRead => {
239 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
241 UserOperation::DeleteAccount => {
242 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
244 UserOperation::PasswordReset => {
245 do_websocket_operation::<PasswordReset>(context, id, op, data).await
247 UserOperation::PasswordChange => {
248 do_websocket_operation::<PasswordChange>(context, id, op, data).await
250 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
251 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
252 UserOperation::CommunityJoin => {
253 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
255 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
256 UserOperation::SaveUserSettings => {
257 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
259 UserOperation::GetReportCount => {
260 do_websocket_operation::<GetReportCount>(context, id, op, data).await
263 // Private Message ops
264 UserOperation::CreatePrivateMessage => {
265 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
267 UserOperation::EditPrivateMessage => {
268 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
270 UserOperation::DeletePrivateMessage => {
271 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
273 UserOperation::MarkPrivateMessageAsRead => {
274 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
276 UserOperation::GetPrivateMessages => {
277 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
281 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
282 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
283 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
284 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
285 UserOperation::GetSiteConfig => {
286 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
288 UserOperation::SaveSiteConfig => {
289 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
291 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
292 UserOperation::TransferCommunity => {
293 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
295 UserOperation::TransferSite => {
296 do_websocket_operation::<TransferSite>(context, id, op, data).await
298 UserOperation::ListCategories => {
299 do_websocket_operation::<ListCategories>(context, id, op, data).await
303 UserOperation::GetCommunity => {
304 do_websocket_operation::<GetCommunity>(context, id, op, data).await
306 UserOperation::ListCommunities => {
307 do_websocket_operation::<ListCommunities>(context, id, op, data).await
309 UserOperation::CreateCommunity => {
310 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
312 UserOperation::EditCommunity => {
313 do_websocket_operation::<EditCommunity>(context, id, op, data).await
315 UserOperation::DeleteCommunity => {
316 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
318 UserOperation::RemoveCommunity => {
319 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
321 UserOperation::FollowCommunity => {
322 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
324 UserOperation::GetFollowedCommunities => {
325 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
327 UserOperation::BanFromCommunity => {
328 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
330 UserOperation::AddModToCommunity => {
331 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
335 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
336 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
337 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
338 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
339 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
340 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
341 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
342 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
343 UserOperation::CreatePostLike => {
344 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
346 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
347 UserOperation::CreatePostReport => {
348 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
350 UserOperation::ListPostReports => {
351 do_websocket_operation::<ListPostReports>(context, id, op, data).await
353 UserOperation::ResolvePostReport => {
354 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
358 UserOperation::CreateComment => {
359 do_websocket_operation::<CreateComment>(context, id, op, data).await
361 UserOperation::EditComment => {
362 do_websocket_operation::<EditComment>(context, id, op, data).await
364 UserOperation::DeleteComment => {
365 do_websocket_operation::<DeleteComment>(context, id, op, data).await
367 UserOperation::RemoveComment => {
368 do_websocket_operation::<RemoveComment>(context, id, op, data).await
370 UserOperation::MarkCommentAsRead => {
371 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
373 UserOperation::SaveComment => {
374 do_websocket_operation::<SaveComment>(context, id, op, data).await
376 UserOperation::GetComments => {
377 do_websocket_operation::<GetComments>(context, id, op, data).await
379 UserOperation::CreateCommentLike => {
380 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
382 UserOperation::CreateCommentReport => {
383 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
385 UserOperation::ListCommentReports => {
386 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
388 UserOperation::ResolveCommentReport => {
389 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
394 async fn do_websocket_operation<'a, 'b, Data>(
395 context: LemmyContext,
399 ) -> Result<String, LemmyError>
401 for<'de> Data: Deserialize<'de> + 'a,
404 let parsed_data: Data = serde_json::from_str(&data)?;
405 let res = parsed_data
406 .perform(&web::Data::new(context), Some(id))
408 serialize_websocket_message(&op, &res)
411 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
412 let mut built_text = String::new();
414 // Building proper speech text for espeak
415 for mut c in captcha.chars() {
416 let new_str = if c.is_alphabetic() {
417 if c.is_lowercase() {
418 c.make_ascii_uppercase();
419 format!("lower case {} ... ", c)
421 c.make_ascii_uppercase();
422 format!("capital {} ... ", c)
428 built_text.push_str(&new_str);
431 espeak_wav_base64(&built_text)
434 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
435 // Make a temp file path
436 let uuid = uuid::Uuid::new_v4().to_string();
437 let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
439 // Write the wav file
440 Command::new("espeak")
446 // Read the wav file bytes
447 let bytes = std::fs::read(&file_path)?;
450 std::fs::remove_file(file_path)?;
453 let base64 = base64::encode(bytes);
460 use crate::captcha_espeak_wav_base64;
464 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())