mirror of https://github.com/LemmyNet/lemmy
Split lemmy_utils into multiple files (#96)
Update dependencies Move send_local_notifs into lemmy_api_structs (ref #1115) Split lemmy_utils into multiple files Co-authored-by: Felix Ableitner <me@nutomic.com> Reviewed-on: https://yerbamate.dev/LemmyNet/lemmy/pulls/96pull/1138/head
parent
762c1347ed
commit
1870dc8cd9
@ -1,7 +1,159 @@
|
||||
extern crate serde;
|
||||
extern crate log;
|
||||
extern crate diesel;
|
||||
extern crate actix_web;
|
||||
|
||||
pub mod comment;
|
||||
pub mod community;
|
||||
pub mod post;
|
||||
pub mod site;
|
||||
pub mod user;
|
||||
|
||||
use lemmy_db::comment::Comment;
|
||||
use lemmy_db::user::User_;
|
||||
use lemmy_db::post::Post;
|
||||
use lemmy_db::user_mention::{UserMentionForm, UserMention};
|
||||
use log::error;
|
||||
use lemmy_db::{Crud, DbPool};
|
||||
use lemmy_utils::utils::MentionData;
|
||||
use lemmy_utils::settings::Settings;
|
||||
use lemmy_utils::email::send_email;
|
||||
use diesel::PgConnection;
|
||||
use lemmy_utils::LemmyError;
|
||||
|
||||
pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
|
||||
where
|
||||
F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let pool = pool.clone();
|
||||
let res = actix_web::web::block(move || {
|
||||
let conn = pool.get()?;
|
||||
let res = (f)(&conn);
|
||||
Ok(res) as Result<_, LemmyError>
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub async fn send_local_notifs(
|
||||
mentions: Vec<MentionData>,
|
||||
comment: Comment,
|
||||
user: &User_,
|
||||
post: Post,
|
||||
pool: &DbPool,
|
||||
do_send_email: bool,
|
||||
) -> Result<Vec<i32>, LemmyError> {
|
||||
let user2 = user.clone();
|
||||
let ids = blocking(pool, move |conn| {
|
||||
do_send_local_notifs(conn, &mentions, &comment, &user2, &post, do_send_email)
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn do_send_local_notifs(
|
||||
conn: &PgConnection,
|
||||
mentions: &[MentionData],
|
||||
comment: &Comment,
|
||||
user: &User_,
|
||||
post: &Post,
|
||||
do_send_email: bool,
|
||||
) -> Vec<i32> {
|
||||
let mut recipient_ids = Vec::new();
|
||||
let hostname = &format!("https://{}", Settings::get().hostname);
|
||||
|
||||
// Send the local mentions
|
||||
for mention in mentions
|
||||
.iter()
|
||||
.filter(|m| m.is_local() && m.name.ne(&user.name))
|
||||
.collect::<Vec<&MentionData>>()
|
||||
{
|
||||
if let Ok(mention_user) = User_::read_from_name(&conn, &mention.name) {
|
||||
// TODO
|
||||
// At some point, make it so you can't tag the parent creator either
|
||||
// This can cause two notifications, one for reply and the other for mention
|
||||
recipient_ids.push(mention_user.id);
|
||||
|
||||
let user_mention_form = UserMentionForm {
|
||||
recipient_id: mention_user.id,
|
||||
comment_id: comment.id,
|
||||
read: None,
|
||||
};
|
||||
|
||||
// Allow this to fail softly, since comment edits might re-update or replace it
|
||||
// Let the uniqueness handle this fail
|
||||
match UserMention::create(&conn, &user_mention_form) {
|
||||
Ok(_mention) => (),
|
||||
Err(_e) => error!("{}", &_e),
|
||||
};
|
||||
|
||||
// Send an email to those users that have notifications on
|
||||
if do_send_email && mention_user.send_notifications_to_email {
|
||||
if let Some(mention_email) = mention_user.email {
|
||||
let subject = &format!("{} - Mentioned by {}", Settings::get().hostname, user.name,);
|
||||
let html = &format!(
|
||||
"<h1>User Mention</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
|
||||
user.name, comment.content, hostname
|
||||
);
|
||||
match send_email(subject, &mention_email, &mention_user.name, html) {
|
||||
Ok(_o) => _o,
|
||||
Err(e) => error!("{}", e),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send notifs to the parent commenter / poster
|
||||
match comment.parent_id {
|
||||
Some(parent_id) => {
|
||||
if let Ok(parent_comment) = Comment::read(&conn, parent_id) {
|
||||
if parent_comment.creator_id != user.id {
|
||||
if let Ok(parent_user) = User_::read(&conn, parent_comment.creator_id) {
|
||||
recipient_ids.push(parent_user.id);
|
||||
|
||||
if do_send_email && parent_user.send_notifications_to_email {
|
||||
if let Some(comment_reply_email) = parent_user.email {
|
||||
let subject = &format!("{} - Reply from {}", Settings::get().hostname, user.name,);
|
||||
let html = &format!(
|
||||
"<h1>Comment Reply</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
|
||||
user.name, comment.content, hostname
|
||||
);
|
||||
match send_email(subject, &comment_reply_email, &parent_user.name, html) {
|
||||
Ok(_o) => _o,
|
||||
Err(e) => error!("{}", e),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Its a post
|
||||
None => {
|
||||
if post.creator_id != user.id {
|
||||
if let Ok(parent_user) = User_::read(&conn, post.creator_id) {
|
||||
recipient_ids.push(parent_user.id);
|
||||
|
||||
if do_send_email && parent_user.send_notifications_to_email {
|
||||
if let Some(post_reply_email) = parent_user.email {
|
||||
let subject = &format!("{} - Reply from {}", Settings::get().hostname, user.name,);
|
||||
let html = &format!(
|
||||
"<h1>Post Reply</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
|
||||
user.name, comment.content, hostname
|
||||
);
|
||||
match send_email(subject, &post_reply_email, &parent_user.name, html) {
|
||||
Ok(_o) => _o,
|
||||
Err(e) => error!("{}", e),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
recipient_ids
|
||||
}
|
||||
|
@ -0,0 +1,64 @@
|
||||
use crate::settings::Settings;
|
||||
use openssl::{pkey::PKey, rsa::Rsa};
|
||||
use std::io::{Error, ErrorKind};
|
||||
use url::Url;
|
||||
|
||||
pub struct Keypair {
|
||||
pub private_key: String,
|
||||
pub public_key: String,
|
||||
}
|
||||
|
||||
/// Generate the asymmetric keypair for ActivityPub HTTP signatures.
|
||||
pub fn generate_actor_keypair() -> Result<Keypair, Error> {
|
||||
let rsa = Rsa::generate(2048)?;
|
||||
let pkey = PKey::from_rsa(rsa)?;
|
||||
let public_key = pkey.public_key_to_pem()?;
|
||||
let private_key = pkey.private_key_to_pem_pkcs8()?;
|
||||
let key_to_string = |key| match String::from_utf8(key) {
|
||||
Ok(s) => Ok(s),
|
||||
Err(e) => Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
format!("Failed converting key to string: {}", e),
|
||||
)),
|
||||
};
|
||||
Ok(Keypair {
|
||||
private_key: key_to_string(private_key)?,
|
||||
public_key: key_to_string(public_key)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub enum EndpointType {
|
||||
Community,
|
||||
User,
|
||||
Post,
|
||||
Comment,
|
||||
PrivateMessage,
|
||||
}
|
||||
|
||||
pub fn get_apub_protocol_string() -> &'static str {
|
||||
if Settings::get().federation.tls_enabled {
|
||||
"https"
|
||||
} else {
|
||||
"http"
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates the ActivityPub ID for a given object type and ID.
|
||||
pub fn make_apub_endpoint(endpoint_type: EndpointType, name: &str) -> Url {
|
||||
let point = match endpoint_type {
|
||||
EndpointType::Community => "c",
|
||||
EndpointType::User => "u",
|
||||
EndpointType::Post => "post",
|
||||
EndpointType::Comment => "comment",
|
||||
EndpointType::PrivateMessage => "private_message",
|
||||
};
|
||||
|
||||
Url::parse(&format!(
|
||||
"{}://{}/{}/{}",
|
||||
get_apub_protocol_string(),
|
||||
Settings::get().hostname,
|
||||
point,
|
||||
name
|
||||
))
|
||||
.unwrap()
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
use crate::settings::Settings;
|
||||
use lettre::{
|
||||
smtp::{
|
||||
authentication::{Credentials, Mechanism},
|
||||
extension::ClientId,
|
||||
ConnectionReuseParameters,
|
||||
},
|
||||
ClientSecurity,
|
||||
SmtpClient,
|
||||
Transport,
|
||||
};
|
||||
use lettre_email::Email;
|
||||
|
||||
pub fn send_email(
|
||||
subject: &str,
|
||||
to_email: &str,
|
||||
to_username: &str,
|
||||
html: &str,
|
||||
) -> Result<(), String> {
|
||||
let email_config = Settings::get().email.ok_or("no_email_setup")?;
|
||||
|
||||
let email = Email::builder()
|
||||
.to((to_email, to_username))
|
||||
.from(email_config.smtp_from_address.to_owned())
|
||||
.subject(subject)
|
||||
.html(html)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let mailer = if email_config.use_tls {
|
||||
SmtpClient::new_simple(&email_config.smtp_server).unwrap()
|
||||
} else {
|
||||
SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
|
||||
}
|
||||
.hello_name(ClientId::Domain(Settings::get().hostname))
|
||||
.smtp_utf8(true)
|
||||
.authentication_mechanism(Mechanism::Plain)
|
||||
.connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
|
||||
let mailer = if let (Some(login), Some(password)) =
|
||||
(&email_config.smtp_login, &email_config.smtp_password)
|
||||
{
|
||||
mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
|
||||
} else {
|
||||
mailer
|
||||
};
|
||||
|
||||
let mut transport = mailer.transport();
|
||||
let result = transport.send(email.into());
|
||||
transport.close();
|
||||
|
||||
match result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
use crate::utils::{
|
||||
is_valid_community_name,
|
||||
is_valid_post_title,
|
||||
is_valid_preferred_username,
|
||||
is_valid_username,
|
||||
remove_slurs,
|
||||
scrape_text_for_mentions,
|
||||
slur_check,
|
||||
slurs_vec_to_str,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_mentions_regex() {
|
||||
let text = "Just read a great blog post by [@tedu@honk.teduangst.com](/u/test). And another by !test_community@fish.teduangst.com . Another [@lemmy@lemmy-alpha:8540](/u/fish)";
|
||||
let mentions = scrape_text_for_mentions(text);
|
||||
|
||||
assert_eq!(mentions[0].name, "tedu".to_string());
|
||||
assert_eq!(mentions[0].domain, "honk.teduangst.com".to_string());
|
||||
assert_eq!(mentions[1].domain, "lemmy-alpha:8540".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_register_username() {
|
||||
assert!(is_valid_username("Hello_98"));
|
||||
assert!(is_valid_username("ten"));
|
||||
assert!(!is_valid_username("Hello-98"));
|
||||
assert!(!is_valid_username("a"));
|
||||
assert!(!is_valid_username(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_preferred_username() {
|
||||
assert!(is_valid_preferred_username("hello @there"));
|
||||
assert!(!is_valid_preferred_username("@hello there"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_community_name() {
|
||||
assert!(is_valid_community_name("example"));
|
||||
assert!(is_valid_community_name("example_community"));
|
||||
assert!(!is_valid_community_name("Example"));
|
||||
assert!(!is_valid_community_name("Ex"));
|
||||
assert!(!is_valid_community_name(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_post_title() {
|
||||
assert!(is_valid_post_title("Post Title"));
|
||||
assert!(is_valid_post_title(" POST TITLE 😃😃😃😃😃"));
|
||||
assert!(!is_valid_post_title("\n \n \n \n ")); // tabs/spaces/newlines
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slur_filter() {
|
||||
let test =
|
||||
"coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
|
||||
let slur_free = "No slurs here";
|
||||
assert_eq!(
|
||||
remove_slurs(&test),
|
||||
"*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
|
||||
.to_string()
|
||||
);
|
||||
|
||||
let has_slurs_vec = vec![
|
||||
"Niggerz",
|
||||
"coons",
|
||||
"dindu",
|
||||
"ladyboy",
|
||||
"retardeds",
|
||||
"tranny",
|
||||
];
|
||||
let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
|
||||
|
||||
assert_eq!(slur_check(test), Err(has_slurs_vec));
|
||||
assert_eq!(slur_check(slur_free), Ok(()));
|
||||
if let Err(slur_vec) = slur_check(test) {
|
||||
assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
|
||||
}
|
||||
}
|
||||
|
||||
// These helped with testing
|
||||
// #[test]
|
||||
// fn test_send_email() {
|
||||
// let result = send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
|
||||
// assert!(result.is_ok());
|
||||
// }
|
Loading…
Reference in New Issue