]> Untitled Git - lemmy.git/blob - server/src/lib.rs
updated to activitystreams 0.4.0-alpha.3
[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, FixedOffset, Local, NaiveDateTime};
36 use lettre::smtp::authentication::{Credentials, Mechanism};
37 use lettre::smtp::extension::ClientId;
38 use lettre::smtp::ConnectionReuseParameters;
39 use lettre::{ClientSecurity, 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 naive_now() -> NaiveDateTime {
46   chrono::prelude::Utc::now().naive_utc()
47 }
48
49 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
50   NaiveDateTime::from_timestamp(time, 0)
51 }
52
53 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
54   let now = Local::now();
55   DateTime::<FixedOffset>::from_utc(datetime, *now.offset())
56 }
57
58 pub fn is_email_regex(test: &str) -> bool {
59   EMAIL_REGEX.is_match(test)
60 }
61
62 pub fn remove_slurs(test: &str) -> String {
63   SLUR_REGEX.replace_all(test, "*removed*").to_string()
64 }
65
66 pub fn slur_check(test: &str) -> Result<(), Vec<&str>> {
67   let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
68
69   // Unique
70   matches.sort_unstable();
71   matches.dedup();
72
73   if matches.is_empty() {
74     Ok(())
75   } else {
76     Err(matches)
77   }
78 }
79
80 pub fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
81   let start = "No slurs - ";
82   let combined = &slurs.join(", ");
83   [start, combined].concat()
84 }
85
86 pub fn extract_usernames(test: &str) -> Vec<&str> {
87   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
88     .find_iter(test)
89     .map(|mat| mat.as_str())
90     .collect();
91
92   // Unique
93   matches.sort_unstable();
94   matches.dedup();
95
96   // Remove /u/
97   matches.iter().map(|t| &t[3..]).collect()
98 }
99
100 pub fn generate_random_string() -> String {
101   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
102 }
103
104 pub fn send_email(
105   subject: &str,
106   to_email: &str,
107   to_username: &str,
108   html: &str,
109 ) -> Result<(), String> {
110   let email_config = Settings::get().email.as_ref().ok_or("no_email_setup")?;
111
112   let email = Email::builder()
113     .to((to_email, to_username))
114     .from(email_config.smtp_from_address.to_owned())
115     .subject(subject)
116     .html(html)
117     .build()
118     .unwrap();
119
120   let mailer = if email_config.use_tls {
121     SmtpClient::new_simple(&email_config.smtp_server).unwrap()
122   } else {
123     SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
124   }
125   .hello_name(ClientId::Domain(Settings::get().hostname.to_owned()))
126   .smtp_utf8(true)
127   .authentication_mechanism(Mechanism::Plain)
128   .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
129   let mailer = if let (Some(login), Some(password)) =
130     (&email_config.smtp_login, &email_config.smtp_password)
131   {
132     mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
133   } else {
134     mailer
135   };
136
137   let mut transport = mailer.transport();
138   let result = transport.send(email.into());
139   transport.close();
140
141   match result {
142     Ok(_) => Ok(()),
143     Err(e) => Err(e.to_string()),
144   }
145 }
146
147 #[cfg(test)]
148 mod tests {
149   use crate::{extract_usernames, is_email_regex, remove_slurs, slur_check, slurs_vec_to_str};
150
151   #[test]
152   fn test_email() {
153     assert!(is_email_regex("gush@gmail.com"));
154     assert!(!is_email_regex("nada_neutho"));
155   }
156
157   #[test]
158   fn test_slur_filter() {
159     let test =
160       "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
161     let slur_free = "No slurs here";
162     assert_eq!(
163       remove_slurs(&test),
164       "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
165         .to_string()
166     );
167
168     let has_slurs_vec = vec![
169       "Niggerz",
170       "coons",
171       "dindu",
172       "ladyboy",
173       "retardeds",
174       "tranny",
175     ];
176     let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
177
178     assert_eq!(slur_check(test), Err(has_slurs_vec));
179     assert_eq!(slur_check(slur_free), Ok(()));
180     if let Err(slur_vec) = slur_check(test) {
181       assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
182     }
183   }
184
185   #[test]
186   fn test_extract_usernames() {
187     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");
188     let expected = vec!["another", "testme"];
189     assert_eq!(usernames, expected);
190   }
191
192   // #[test]
193   // fn test_send_email() {
194   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
195   //   assert!(result.is_ok());
196   // }
197 }
198
199 lazy_static! {
200   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
201   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();
202   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
203 }