]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Implement config (fixes #351)
[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 settings;
32 pub mod version;
33 pub mod websocket;
34
35 use crate::settings::Settings;
36 use chrono::{DateTime, NaiveDateTime, Utc};
37 use lettre::smtp::authentication::{Credentials, Mechanism};
38 use lettre::smtp::extension::ClientId;
39 use lettre::smtp::ConnectionReuseParameters;
40 use lettre::{SmtpClient, Transport};
41 use lettre_email::Email;
42 use rand::distributions::Alphanumeric;
43 use rand::{thread_rng, Rng};
44 use regex::Regex;
45
46 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
47   DateTime::<Utc>::from_utc(ndt, Utc)
48 }
49
50 pub fn naive_now() -> NaiveDateTime {
51   chrono::prelude::Utc::now().naive_utc()
52 }
53
54 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
55   NaiveDateTime::from_timestamp(time, 0)
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 has_slurs(test: &str) -> bool {
67   SLUR_REGEX.is_match(test)
68 }
69
70 pub fn extract_usernames(test: &str) -> Vec<&str> {
71   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
72     .find_iter(test)
73     .map(|mat| mat.as_str())
74     .collect();
75
76   // Unique
77   matches.sort_unstable();
78   matches.dedup();
79
80   // Remove /u/
81   matches.iter().map(|t| &t[3..]).collect()
82 }
83
84 pub fn generate_random_string() -> String {
85   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
86 }
87
88 pub fn send_email(
89   subject: &str,
90   to_email: &str,
91   to_username: &str,
92   html: &str,
93 ) -> Result<(), String> {
94   let email_config = Settings::get().email.as_ref().ok_or("no_email_setup")?;
95
96   let email = Email::builder()
97     .to((to_email, to_username))
98     .from((
99       email_config.smtp_login.to_owned(),
100       email_config.smtp_from_address.to_owned(),
101     ))
102     .subject(subject)
103     .html(html)
104     .build()
105     .unwrap();
106
107   let mut mailer = SmtpClient::new_simple(&email_config.smtp_server)
108     .unwrap()
109     .hello_name(ClientId::Domain("localhost".to_string()))
110     .credentials(Credentials::new(
111       email_config.smtp_login.to_owned(),
112       email_config.smtp_password.to_owned(),
113     ))
114     .smtp_utf8(true)
115     .authentication_mechanism(Mechanism::Plain)
116     .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)
117     .transport();
118
119   let result = mailer.send(email.into());
120
121   match result {
122     Ok(_) => Ok(()),
123     Err(_) => Err("no_email_setup".to_string()),
124   }
125 }
126
127 #[cfg(test)]
128 mod tests {
129   use crate::{extract_usernames, has_slurs, is_email_regex, remove_slurs, Settings};
130
131   #[test]
132   fn test_email() {
133     assert!(is_email_regex("gush@gmail.com"));
134     assert!(!is_email_regex("nada_neutho"));
135   }
136
137   #[test]
138   fn test_slur_filter() {
139     let test =
140       "coons test dindu ladyboy tranny retardeds. This is a bunch of other safe text.".to_string();
141     let slur_free = "No slurs here";
142     assert_eq!(
143       remove_slurs(&test),
144       "*removed* test *removed* *removed* *removed* *removed*. This is a bunch of other safe text."
145         .to_string()
146     );
147     assert!(has_slurs(&test));
148     assert!(!has_slurs(slur_free));
149   }
150
151   #[test]
152   fn test_extract_usernames() {
153     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");
154     let expected = vec!["another", "testme"];
155     assert_eq!(usernames, expected);
156   }
157
158   // #[test]
159   // fn test_send_email() {
160   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
161   //   assert!(result.is_ok());
162   // }
163 }
164
165 lazy_static! {
166   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
167   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();
168   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
169 }