1 use crate::claims::Claims;
2 use actix_web::{web, web::Data};
5 community::{Community, CommunityModerator},
10 views::community::community_user_ban_view::CommunityUserBanView,
14 use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*};
15 use lemmy_utils::{settings::Settings, APIError, ConnectionId, LemmyError};
16 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
17 use serde::Deserialize;
18 use std::process::Command;
29 #[async_trait::async_trait(?Send)]
31 type Response: serde::ser::Serialize + Send;
35 context: &Data<LemmyContext>,
36 websocket_id: Option<ConnectionId>,
37 ) -> Result<Self::Response, LemmyError>;
40 pub(crate) async fn is_mod_or_admin(
44 ) -> Result<(), LemmyError> {
45 let is_mod_or_admin = blocking(pool, move |conn| {
46 Community::is_mod_or_admin(conn, user_id, community_id)
50 return Err(APIError::err("not_a_mod_or_admin").into());
54 pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
55 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
57 return Err(APIError::err("not_an_admin").into());
62 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
63 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
65 Err(_e) => Err(APIError::err("couldnt_find_post").into()),
69 pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
70 let claims = match Claims::decode(&jwt) {
71 Ok(claims) => claims.claims,
72 Err(_e) => return Err(APIError::err("not_logged_in").into()),
74 let user_id = claims.id;
75 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
76 // Check for a site ban
78 return Err(APIError::err("site_ban").into());
83 pub(crate) async fn get_user_from_jwt_opt(
86 ) -> Result<Option<User_>, LemmyError> {
88 Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
93 pub(crate) async fn check_community_ban(
97 ) -> Result<(), LemmyError> {
98 let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
99 if blocking(pool, is_banned).await? {
100 Err(APIError::err("community_ban").into())
106 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
108 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
109 if !site.enable_downvotes {
110 return Err(APIError::err("downvotes_disabled").into());
116 /// Returns a list of communities that the user moderates
117 /// or if a community_id is supplied validates the user is a moderator
118 /// of that community and returns the community id in a vec
120 /// * `user_id` - the user id of the moderator
121 /// * `community_id` - optional community id to check for moderator privileges
122 /// * `pool` - the diesel db pool
123 pub(crate) async fn collect_moderated_communities(
125 community_id: Option<i32>,
127 ) -> Result<Vec<i32>, LemmyError> {
128 if let Some(community_id) = community_id {
129 // if the user provides a community_id, just check for mod/admin privileges
130 is_mod_or_admin(pool, user_id, community_id).await?;
131 Ok(vec![community_id])
133 let ids = blocking(pool, move |conn: &'_ _| {
134 CommunityModerator::get_user_moderated_communities(conn, user_id)
141 pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
142 if let Some(Some(item)) = &item {
143 if Url::parse(item).is_err() {
144 return Err(APIError::err("invalid_url").into());
150 pub(crate) async fn linked_instances(pool: &DbPool) -> Result<Vec<String>, LemmyError> {
151 let mut instances: Vec<String> = Vec::new();
153 if Settings::get().federation.enabled {
154 let distinct_communities = blocking(pool, move |conn| {
155 Community::distinct_federated_communities(conn)
159 instances = distinct_communities
161 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
162 .collect::<Result<Vec<String>, LemmyError>>()?;
164 instances.append(&mut Settings::get().get_allowed_instances());
165 instances.retain(|a| {
166 !Settings::get().get_blocked_instances().contains(a)
168 && !a.eq(&Settings::get().hostname)
171 // Sort and remove dupes
172 instances.sort_unstable();
179 pub async fn match_websocket_operation(
180 context: LemmyContext,
184 ) -> Result<String, LemmyError> {
187 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
188 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
189 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
190 UserOperation::GetUserDetails => {
191 do_websocket_operation::<GetUserDetails>(context, id, op, data).await
193 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
194 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
195 UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
196 UserOperation::GetUserMentions => {
197 do_websocket_operation::<GetUserMentions>(context, id, op, data).await
199 UserOperation::MarkUserMentionAsRead => {
200 do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
202 UserOperation::MarkAllAsRead => {
203 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
205 UserOperation::DeleteAccount => {
206 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
208 UserOperation::PasswordReset => {
209 do_websocket_operation::<PasswordReset>(context, id, op, data).await
211 UserOperation::PasswordChange => {
212 do_websocket_operation::<PasswordChange>(context, id, op, data).await
214 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
215 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
216 UserOperation::CommunityJoin => {
217 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
219 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
220 UserOperation::SaveUserSettings => {
221 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
223 UserOperation::GetReportCount => {
224 do_websocket_operation::<GetReportCount>(context, id, op, data).await
227 // Private Message ops
228 UserOperation::CreatePrivateMessage => {
229 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
231 UserOperation::EditPrivateMessage => {
232 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
234 UserOperation::DeletePrivateMessage => {
235 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
237 UserOperation::MarkPrivateMessageAsRead => {
238 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
240 UserOperation::GetPrivateMessages => {
241 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
245 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
246 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
247 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
248 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
249 UserOperation::GetSiteConfig => {
250 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
252 UserOperation::SaveSiteConfig => {
253 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
255 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
256 UserOperation::TransferCommunity => {
257 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
259 UserOperation::TransferSite => {
260 do_websocket_operation::<TransferSite>(context, id, op, data).await
262 UserOperation::ListCategories => {
263 do_websocket_operation::<ListCategories>(context, id, op, data).await
267 UserOperation::GetCommunity => {
268 do_websocket_operation::<GetCommunity>(context, id, op, data).await
270 UserOperation::ListCommunities => {
271 do_websocket_operation::<ListCommunities>(context, id, op, data).await
273 UserOperation::CreateCommunity => {
274 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
276 UserOperation::EditCommunity => {
277 do_websocket_operation::<EditCommunity>(context, id, op, data).await
279 UserOperation::DeleteCommunity => {
280 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
282 UserOperation::RemoveCommunity => {
283 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
285 UserOperation::FollowCommunity => {
286 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
288 UserOperation::GetFollowedCommunities => {
289 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
291 UserOperation::BanFromCommunity => {
292 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
294 UserOperation::AddModToCommunity => {
295 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
299 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
300 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
301 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
302 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
303 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
304 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
305 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
306 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
307 UserOperation::CreatePostLike => {
308 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
310 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
311 UserOperation::CreatePostReport => {
312 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
314 UserOperation::ListPostReports => {
315 do_websocket_operation::<ListPostReports>(context, id, op, data).await
317 UserOperation::ResolvePostReport => {
318 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
322 UserOperation::CreateComment => {
323 do_websocket_operation::<CreateComment>(context, id, op, data).await
325 UserOperation::EditComment => {
326 do_websocket_operation::<EditComment>(context, id, op, data).await
328 UserOperation::DeleteComment => {
329 do_websocket_operation::<DeleteComment>(context, id, op, data).await
331 UserOperation::RemoveComment => {
332 do_websocket_operation::<RemoveComment>(context, id, op, data).await
334 UserOperation::MarkCommentAsRead => {
335 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
337 UserOperation::SaveComment => {
338 do_websocket_operation::<SaveComment>(context, id, op, data).await
340 UserOperation::GetComments => {
341 do_websocket_operation::<GetComments>(context, id, op, data).await
343 UserOperation::CreateCommentLike => {
344 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
346 UserOperation::CreateCommentReport => {
347 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
349 UserOperation::ListCommentReports => {
350 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
352 UserOperation::ResolveCommentReport => {
353 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
358 async fn do_websocket_operation<'a, 'b, Data>(
359 context: LemmyContext,
363 ) -> Result<String, LemmyError>
365 for<'de> Data: Deserialize<'de> + 'a,
368 let parsed_data: Data = serde_json::from_str(&data)?;
369 let res = parsed_data
370 .perform(&web::Data::new(context), Some(id))
372 serialize_websocket_message(&op, &res)
375 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
376 let mut built_text = String::new();
378 // Building proper speech text for espeak
379 for mut c in captcha.chars() {
380 let new_str = if c.is_alphabetic() {
381 if c.is_lowercase() {
382 c.make_ascii_uppercase();
383 format!("lower case {} ... ", c)
385 c.make_ascii_uppercase();
386 format!("capital {} ... ", c)
392 built_text.push_str(&new_str);
395 espeak_wav_base64(&built_text)
398 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
399 // Make a temp file path
400 let uuid = uuid::Uuid::new_v4().to_string();
401 let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
403 // Write the wav file
404 Command::new("espeak")
410 // Read the wav file bytes
411 let bytes = std::fs::read(&file_path)?;
414 std::fs::remove_file(file_path)?;
417 let base64 = base64::encode(bytes);
424 use crate::captcha_espeak_wav_base64;
428 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())