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