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