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