]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Halfway done with email, not fully working yet.
[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 rand;
17 pub extern crate regex;
18 pub extern crate serde;
19 pub extern crate serde_json;
20 pub extern crate strum;
21 pub extern crate lettre;
22 pub extern crate lettre_email;
23
24 pub mod api;
25 pub mod apub;
26 pub mod db;
27 pub mod schema;
28 pub mod websocket;
29
30 use chrono::{DateTime, NaiveDateTime, Utc};
31 use dotenv::dotenv;
32 use regex::Regex;
33 use std::env;
34 use rand::{thread_rng, Rng};
35 use rand::distributions::Alphanumeric;
36 use lettre::{SmtpClient, Transport};
37 use lettre_email::{Email};
38 use lettre::smtp::authentication::{Credentials, Mechanism};
39 use lettre::smtp::extension::ClientId;
40 use lettre::smtp::ConnectionReuseParameters;
41
42 pub struct Settings {
43   db_url: String,
44   hostname: String,
45   jwt_secret: String,
46   rate_limit_message: i32,
47   rate_limit_message_per_second: i32,
48   rate_limit_post: i32,
49   rate_limit_post_per_second: i32,
50   rate_limit_register: i32,
51   rate_limit_register_per_second: i32,
52   email_config: Option<EmailConfig>,
53 }
54
55 pub struct EmailConfig {
56   smtp_server: String,
57   smtp_login: String,
58   smtp_password: String,
59   smtp_from_address: String,
60 }
61
62 impl Settings {
63   fn get() -> Self {
64     dotenv().ok();
65     
66     let email_config = if env::var("SMTP_SERVER").is_ok() {
67       Some(EmailConfig {
68         smtp_server: env::var("SMTP_SERVER").expect("SMTP_SERVER must be set"),
69         smtp_login: env::var("SMTP_LOGIN").expect("SMTP_LOGIN must be set"),
70         smtp_password: env::var("SMTP_PASSWORD").expect("SMTP_PASSWORD must be set"),
71         smtp_from_address: env::var("SMTP_FROM_ADDRESS").expect("SMTP_FROM_ADDRESS must be set")
72       })
73     } else {
74       None
75     };
76
77     Settings {
78       db_url: env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
79       hostname: env::var("HOSTNAME").unwrap_or("rrr".to_string()),
80       jwt_secret: env::var("JWT_SECRET").unwrap_or("changeme".to_string()),
81       rate_limit_message: env::var("RATE_LIMIT_MESSAGE")
82         .unwrap_or("30".to_string())
83         .parse()
84         .unwrap(),
85       rate_limit_message_per_second: env::var("RATE_LIMIT_MESSAGE_PER_SECOND")
86         .unwrap_or("60".to_string())
87         .parse()
88         .unwrap(),
89       rate_limit_post: env::var("RATE_LIMIT_POST")
90         .unwrap_or("3".to_string())
91         .parse()
92         .unwrap(),
93       rate_limit_post_per_second: env::var("RATE_LIMIT_POST_PER_SECOND")
94         .unwrap_or("600".to_string())
95         .parse()
96         .unwrap(),
97       rate_limit_register: env::var("RATE_LIMIT_REGISTER")
98         .unwrap_or("1".to_string())
99         .parse()
100         .unwrap(),
101       rate_limit_register_per_second: env::var("RATE_LIMIT_REGISTER_PER_SECOND")
102         .unwrap_or("3600".to_string())
103         .parse()
104         .unwrap(),
105         email_config: email_config,
106     }
107   }
108   fn api_endpoint(&self) -> String {
109     format!("{}/api/v1", self.hostname)
110   }
111 }
112
113 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
114   DateTime::<Utc>::from_utc(ndt, Utc)
115 }
116
117 pub fn naive_now() -> NaiveDateTime {
118   chrono::prelude::Utc::now().naive_utc()
119 }
120
121 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
122   NaiveDateTime::from_timestamp(time, 0)
123 }
124
125 pub fn is_email_regex(test: &str) -> bool {
126   EMAIL_REGEX.is_match(test)
127 }
128
129 pub fn remove_slurs(test: &str) -> String {
130   SLUR_REGEX.replace_all(test, "*removed*").to_string()
131 }
132
133 pub fn has_slurs(test: &str) -> bool {
134   SLUR_REGEX.is_match(test)
135 }
136
137 pub fn extract_usernames(test: &str) -> Vec<&str> {
138   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
139     .find_iter(test)
140     .map(|mat| mat.as_str())
141     .collect();
142
143   // Unique
144   matches.sort_unstable();
145   matches.dedup();
146
147   // Remove /u/
148   matches.iter().map(|t| &t[3..]).collect()
149 }
150
151 pub fn generate_random_string() -> String {
152   thread_rng()
153     .sample_iter(&Alphanumeric)
154     .take(30)
155     .collect()
156 }
157
158 pub fn send_email(subject: &str, to_email: &str, to_username: &str, html: &str) -> Result<(), String> {
159
160   let email_config = Settings::get().email_config.ok_or("no_email_setup")?;
161
162   let email = Email::builder()
163     // .to((to_email, username))
164     .to((to_email, to_username))
165     .from((email_config.smtp_login.to_owned(), email_config.smtp_from_address))
166     .subject(subject)
167     .html(html)
168     .build()
169     .unwrap();
170
171     let mut mailer = SmtpClient::new_simple(&email_config.smtp_server).unwrap()
172       .hello_name(ClientId::Domain("localhost".to_string()))
173       .credentials(Credentials::new(
174           email_config.smtp_login.to_owned(), 
175           email_config.smtp_password.to_owned()))
176       .smtp_utf8(true)
177       .authentication_mechanism(Mechanism::Plain)
178       .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)
179       .transport();
180
181   let result = mailer.send(email.into());
182
183   match result {
184     Ok(_) => Ok(()),
185     Err(_) => Err("no_email_setup".to_string()),
186   }
187 }
188
189 #[cfg(test)]
190 mod tests {
191   use crate::{extract_usernames, has_slurs, is_email_regex, remove_slurs, Settings};
192   #[test]
193   fn test_api() {
194     assert_eq!(Settings::get().api_endpoint(), "rrr/api/v1");
195   }
196
197   #[test]
198   fn test_email() {
199     assert!(is_email_regex("gush@gmail.com"));
200     assert!(!is_email_regex("nada_neutho"));
201   }
202
203   #[test]
204   fn test_slur_filter() {
205     let test =
206       "coons test dindu ladyboy tranny retardeds. This is a bunch of other safe text.".to_string();
207     let slur_free = "No slurs here";
208     assert_eq!(
209       remove_slurs(&test),
210       "*removed* test *removed* *removed* *removed* *removed*. This is a bunch of other safe text."
211         .to_string()
212     );
213     assert!(has_slurs(&test));
214     assert!(!has_slurs(slur_free));
215   }
216
217   #[test]
218   fn test_extract_usernames() {
219     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");
220     let expected = vec!["another", "testme"];
221     assert_eq!(usernames, expected);
222   }
223
224   // #[test]
225   // fn test_send_email() {
226   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
227   //   assert!(result.is_ok());
228   // }
229 }
230
231 lazy_static! {
232   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
233   static ref SLUR_REGEX: Regex = Regex::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|nig(\b|g?(a|er)?s?)\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?)").unwrap();
234   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
235 }