]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Squashed commit of the following:
[lemmy.git] / server / src / lib.rs
1 #![recursion_limit = "512"]
2 #[macro_use]
3 pub extern crate strum_macros;
4 #[macro_use]
5 pub extern crate lazy_static;
6 #[macro_use]
7 pub extern crate failure;
8 #[macro_use]
9 pub extern crate diesel;
10 pub extern crate actix;
11 pub extern crate actix_web;
12 pub extern crate bcrypt;
13 pub extern crate chrono;
14 pub extern crate dotenv;
15 pub extern crate jsonwebtoken;
16 pub extern crate lettre;
17 pub extern crate lettre_email;
18 pub extern crate rand;
19 pub extern crate regex;
20 pub extern crate serde;
21 pub extern crate serde_json;
22 pub extern crate sha2;
23 pub extern crate strum;
24
25 pub mod api;
26 pub mod apub;
27 pub mod db;
28 pub mod routes;
29 pub mod schema;
30 pub mod settings;
31 pub mod version;
32 pub mod websocket;
33
34 use crate::settings::Settings;
35 use chrono::{DateTime, NaiveDateTime, Utc};
36 use lettre::smtp::authentication::{Credentials, Mechanism};
37 use lettre::smtp::extension::ClientId;
38 use lettre::smtp::ConnectionReuseParameters;
39 use lettre::{SmtpClient, Transport};
40 use lettre_email::Email;
41 use rand::distributions::Alphanumeric;
42 use rand::{thread_rng, Rng};
43 use regex::{Regex, RegexBuilder};
44
45 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
46   DateTime::<Utc>::from_utc(ndt, Utc)
47 }
48
49 pub fn naive_now() -> NaiveDateTime {
50   chrono::prelude::Utc::now().naive_utc()
51 }
52
53 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
54   NaiveDateTime::from_timestamp(time, 0)
55 }
56
57 pub fn is_email_regex(test: &str) -> bool {
58   EMAIL_REGEX.is_match(test)
59 }
60
61 pub fn remove_slurs(test: &str) -> String {
62   SLUR_REGEX.replace_all(test, "*removed*").to_string()
63 }
64
65 pub fn has_slurs(test: &str) -> bool {
66   SLUR_REGEX.is_match(test)
67 }
68
69 pub fn extract_usernames(test: &str) -> Vec<&str> {
70   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
71     .find_iter(test)
72     .map(|mat| mat.as_str())
73     .collect();
74
75   // Unique
76   matches.sort_unstable();
77   matches.dedup();
78
79   // Remove /u/
80   matches.iter().map(|t| &t[3..]).collect()
81 }
82
83 pub fn generate_random_string() -> String {
84   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
85 }
86
87 pub fn send_email(
88   subject: &str,
89   to_email: &str,
90   to_username: &str,
91   html: &str,
92 ) -> Result<(), String> {
93   let email_config = Settings::get().email.as_ref().ok_or("no_email_setup")?;
94
95   let email = Email::builder()
96     .to((to_email, to_username))
97     .from((
98       email_config.smtp_login.to_owned(),
99       email_config.smtp_from_address.to_owned(),
100     ))
101     .subject(subject)
102     .html(html)
103     .build()
104     .unwrap();
105
106   let mut mailer = SmtpClient::new_simple(&email_config.smtp_server)
107     .unwrap()
108     .hello_name(ClientId::Domain(Settings::get().hostname.to_owned()))
109     .credentials(Credentials::new(
110       email_config.smtp_login.to_owned(),
111       email_config.smtp_password.to_owned(),
112     ))
113     .smtp_utf8(true)
114     .authentication_mechanism(Mechanism::Plain)
115     .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)
116     .transport();
117
118   let result = mailer.send(email.into());
119
120   mailer.close();
121
122   match result {
123     Ok(_) => Ok(()),
124     Err(_) => Err("no_email_setup".to_string()),
125   }
126 }
127
128 #[cfg(test)]
129 mod tests {
130   use crate::{extract_usernames, has_slurs, is_email_regex, remove_slurs};
131
132   #[test]
133   fn test_email() {
134     assert!(is_email_regex("gush@gmail.com"));
135     assert!(!is_email_regex("nada_neutho"));
136   }
137
138   #[test]
139   fn test_slur_filter() {
140     let test =
141       "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.".to_string();
142     let slur_free = "No slurs here";
143     assert_eq!(
144       remove_slurs(&test),
145       "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
146         .to_string()
147     );
148     assert!(has_slurs(&test));
149     assert!(!has_slurs(slur_free));
150   }
151
152   #[test]
153   fn test_extract_usernames() {
154     let usernames = extract_usernames("this is a user mention for [/u/testme](/u/testme) and thats all. Oh [/u/another](/u/another) user. And the first again [/u/testme](/u/testme) okay");
155     let expected = vec!["another", "testme"];
156     assert_eq!(usernames, expected);
157   }
158
159   // #[test]
160   // fn test_send_email() {
161   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
162   //   assert!(result.is_ok());
163   // }
164 }
165
166 lazy_static! {
167   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
168   static ref SLUR_REGEX: Regex = RegexBuilder::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|nig(\b|g?(a|er)?(s|z)?)\b|dindu(s?)|mudslime?s?|kikes?|mongoloids?|towel\s*heads?|\bspi(c|k)s?\b|\bchinks?|niglets?|beaners?|\bnips?\b|\bcoons?\b|jungle\s*bunn(y|ies?)|jigg?aboo?s?|\bpakis?\b|rag\s*heads?|gooks?|cunts?|bitch(es|ing|y)?|puss(y|ies?)|twats?|feminazis?|whor(es?|ing)|\bslut(s|t?y)?|\btrann?(y|ies?)|ladyboy(s?)|\b(b|re|r)tard(ed)?s?)").case_insensitive(true).build().unwrap();
169   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
170 }