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