1 use crate::{captcha_as_wav_base64, Perform};
2 use actix_web::web::Data;
3 use captcha::{gen, Difficulty};
5 use lemmy_api_common::person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse};
6 use lemmy_db_schema::utils::naive_now;
7 use lemmy_utils::{ConnectionId, LemmyError};
8 use lemmy_websocket::{messages::CaptchaItem, LemmyContext};
10 #[async_trait::async_trait(?Send)]
11 impl Perform for GetCaptcha {
12 type Response = GetCaptchaResponse;
14 #[tracing::instrument(skip(context, _websocket_id))]
17 context: &Data<LemmyContext>,
18 _websocket_id: Option<ConnectionId>,
19 ) -> Result<Self::Response, LemmyError> {
20 let captcha_settings = context.settings().captcha;
22 if !captcha_settings.enabled {
23 return Ok(GetCaptchaResponse { ok: None });
26 let captcha = gen(match captcha_settings.difficulty.as_str() {
27 "easy" => Difficulty::Easy,
28 "hard" => Difficulty::Hard,
29 _ => Difficulty::Medium,
32 let answer = captcha.chars_as_string();
34 let png = captcha.as_base64().expect("failed to generate captcha");
36 let uuid = uuid::Uuid::new_v4().to_string();
38 let wav = captcha_as_wav_base64(&captcha);
40 let captcha_item = CaptchaItem {
42 uuid: uuid.to_owned(),
43 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
46 // Stores the captcha item on the queue
47 context.chat_server().do_send(captcha_item);
49 Ok(GetCaptchaResponse {
50 ok: Some(CaptchaResponse { png, wav, uuid }),