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