]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Move volumes into subfolder (ref #474) (#23)
[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, NaiveDateTime, Utc};
36 use chttp::prelude::*;
37 use lettre::smtp::authentication::{Credentials, Mechanism};
38 use lettre::smtp::extension::ClientId;
39 use lettre::smtp::ConnectionReuseParameters;
40 use lettre::{ClientSecurity, SmtpClient, Transport};
41 use lettre_email::Email;
42 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
43 use rand::distributions::Alphanumeric;
44 use rand::{thread_rng, Rng};
45 use regex::{Regex, RegexBuilder};
46 use serde::Deserialize;
47
48 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
49   DateTime::<Utc>::from_utc(ndt, Utc)
50 }
51
52 pub fn naive_now() -> NaiveDateTime {
53   chrono::prelude::Utc::now().naive_utc()
54 }
55
56 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
57   NaiveDateTime::from_timestamp(time, 0)
58 }
59
60 pub fn is_email_regex(test: &str) -> bool {
61   EMAIL_REGEX.is_match(test)
62 }
63
64 pub fn remove_slurs(test: &str) -> String {
65   SLUR_REGEX.replace_all(test, "*removed*").to_string()
66 }
67
68 pub fn slur_check(test: &str) -> Result<(), Vec<&str>> {
69   let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
70
71   // Unique
72   matches.sort_unstable();
73   matches.dedup();
74
75   if matches.is_empty() {
76     Ok(())
77   } else {
78     Err(matches)
79   }
80 }
81
82 pub fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
83   let start = "No slurs - ";
84   let combined = &slurs.join(", ");
85   [start, combined].concat()
86 }
87
88 pub fn extract_usernames(test: &str) -> Vec<&str> {
89   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
90     .find_iter(test)
91     .map(|mat| mat.as_str())
92     .collect();
93
94   // Unique
95   matches.sort_unstable();
96   matches.dedup();
97
98   // Remove /u/
99   matches.iter().map(|t| &t[3..]).collect()
100 }
101
102 pub fn generate_random_string() -> String {
103   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
104 }
105
106 pub fn send_email(
107   subject: &str,
108   to_email: &str,
109   to_username: &str,
110   html: &str,
111 ) -> Result<(), String> {
112   let email_config = Settings::get().email.as_ref().ok_or("no_email_setup")?;
113
114   let email = Email::builder()
115     .to((to_email, to_username))
116     .from(email_config.smtp_from_address.to_owned())
117     .subject(subject)
118     .html(html)
119     .build()
120     .unwrap();
121
122   let mailer = if email_config.use_tls {
123     SmtpClient::new_simple(&email_config.smtp_server).unwrap()
124   } else {
125     SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
126   }
127   .hello_name(ClientId::Domain(Settings::get().hostname.to_owned()))
128   .smtp_utf8(true)
129   .authentication_mechanism(Mechanism::Plain)
130   .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
131   let mailer = if let (Some(login), Some(password)) =
132     (&email_config.smtp_login, &email_config.smtp_password)
133   {
134     mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
135   } else {
136     mailer
137   };
138
139   let mut transport = mailer.transport();
140   let result = transport.send(email.into());
141   transport.close();
142
143   match result {
144     Ok(_) => Ok(()),
145     Err(e) => Err(e.to_string()),
146   }
147 }
148
149 #[derive(Deserialize, Debug)]
150 pub struct IframelyResponse {
151   title: Option<String>,
152   description: Option<String>,
153   thumbnail_url: Option<String>,
154   html: Option<String>,
155 }
156
157 pub fn fetch_iframely(url: &str) -> Result<IframelyResponse, failure::Error> {
158   let fetch_url = format!("http://iframely/oembed?url={}", url);
159   let text = chttp::get(&fetch_url)?.text()?;
160   let res: IframelyResponse = serde_json::from_str(&text)?;
161   Ok(res)
162 }
163
164 #[derive(Deserialize, Debug)]
165 pub struct PictshareResponse {
166   status: String,
167   url: String,
168 }
169
170 pub fn fetch_pictshare(image_url: &str) -> Result<PictshareResponse, failure::Error> {
171   let fetch_url = format!(
172     "http://pictshare/api/geturl.php?url={}",
173     utf8_percent_encode(image_url, NON_ALPHANUMERIC)
174   );
175   let text = chttp::get(&fetch_url)?.text()?;
176   let res: PictshareResponse = serde_json::from_str(&text)?;
177   Ok(res)
178 }
179
180 fn fetch_iframely_and_pictshare_data(
181   url: Option<String>,
182 ) -> (
183   Option<String>,
184   Option<String>,
185   Option<String>,
186   Option<String>,
187 ) {
188   // Fetch iframely data
189   let (iframely_title, iframely_description, iframely_thumbnail_url, iframely_html) = match url {
190     Some(url) => match fetch_iframely(&url) {
191       Ok(res) => (res.title, res.description, res.thumbnail_url, res.html),
192       Err(e) => {
193         eprintln!("iframely err: {}", e);
194         (None, None, None, None)
195       }
196     },
197     None => (None, None, None, None),
198   };
199
200   // Fetch pictshare thumbnail
201   let pictshare_thumbnail = match iframely_thumbnail_url {
202     Some(iframely_thumbnail_url) => match fetch_pictshare(&iframely_thumbnail_url) {
203       Ok(res) => Some(res.url),
204       Err(e) => {
205         eprintln!("pictshare err: {}", e);
206         None
207       }
208     },
209     None => None,
210   };
211
212   (
213     iframely_title,
214     iframely_description,
215     iframely_html,
216     pictshare_thumbnail,
217   )
218 }
219
220 #[cfg(test)]
221 mod tests {
222   use crate::{extract_usernames, is_email_regex, remove_slurs, slur_check, slurs_vec_to_str};
223
224   #[test]
225   fn test_email() {
226     assert!(is_email_regex("gush@gmail.com"));
227     assert!(!is_email_regex("nada_neutho"));
228   }
229
230   #[test]
231   fn test_slur_filter() {
232     let test =
233       "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
234     let slur_free = "No slurs here";
235     assert_eq!(
236       remove_slurs(&test),
237       "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
238         .to_string()
239     );
240
241     let has_slurs_vec = vec![
242       "Niggerz",
243       "coons",
244       "dindu",
245       "ladyboy",
246       "retardeds",
247       "tranny",
248     ];
249     let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
250
251     assert_eq!(slur_check(test), Err(has_slurs_vec));
252     assert_eq!(slur_check(slur_free), Ok(()));
253     if let Err(slur_vec) = slur_check(test) {
254       assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
255     }
256   }
257
258   #[test]
259   fn test_extract_usernames() {
260     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");
261     let expected = vec!["another", "testme"];
262     assert_eq!(usernames, expected);
263   }
264
265   // These helped with testing
266   // #[test]
267   // fn test_iframely() {
268   //   let res = fetch_iframely("https://www.redspark.nu/?p=15341");
269   //   assert!(res.is_ok());
270   // }
271
272   // #[test]
273   // fn test_pictshare() {
274   //   let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
275   //   assert!(res.is_ok());
276   //   let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
277   //   assert!(res_other.is_err());
278   // }
279
280   // #[test]
281   // fn test_send_email() {
282   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
283   //   assert!(result.is_ok());
284   // }
285 }
286
287 lazy_static! {
288   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
289   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();
290   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
291 }