]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Merge branch 'master' into use-attohttpc
[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 rate_limit;
31 pub mod routes;
32 pub mod schema;
33 pub mod settings;
34 pub mod version;
35 pub mod websocket;
36
37 use actix_web::dev::ConnectionInfo;
38 use chrono::{DateTime, NaiveDateTime, Utc};
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 use crate::settings::Settings;
52
53 pub type ConnectionId = usize;
54 pub type PostId = i32;
55 pub type CommunityId = i32;
56 pub type UserId = i32;
57 pub type IPAddr = String;
58
59 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
60   DateTime::<Utc>::from_utc(ndt, Utc)
61 }
62
63 pub fn naive_now() -> NaiveDateTime {
64   chrono::prelude::Utc::now().naive_utc()
65 }
66
67 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
68   NaiveDateTime::from_timestamp(time, 0)
69 }
70
71 pub fn is_email_regex(test: &str) -> bool {
72   EMAIL_REGEX.is_match(test)
73 }
74
75 pub fn is_image_content_type(test: &str) -> Result<(), failure::Error> {
76   if attohttpc::get(test)
77     .send()?
78     .headers()
79     .get("Content-Type")
80     .ok_or_else(|| format_err!("No Content-Type header"))?
81     .to_str()?
82     .starts_with("image/")
83   {
84     Ok(())
85   } else {
86     Err(format_err!("Not an image type."))
87   }
88 }
89
90 pub fn remove_slurs(test: &str) -> String {
91   SLUR_REGEX.replace_all(test, "*removed*").to_string()
92 }
93
94 pub fn slur_check(test: &str) -> Result<(), Vec<&str>> {
95   let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
96
97   // Unique
98   matches.sort_unstable();
99   matches.dedup();
100
101   if matches.is_empty() {
102     Ok(())
103   } else {
104     Err(matches)
105   }
106 }
107
108 pub fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
109   let start = "No slurs - ";
110   let combined = &slurs.join(", ");
111   [start, combined].concat()
112 }
113
114 pub fn extract_usernames(test: &str) -> Vec<&str> {
115   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
116     .find_iter(test)
117     .map(|mat| mat.as_str())
118     .collect();
119
120   // Unique
121   matches.sort_unstable();
122   matches.dedup();
123
124   // Remove /u/
125   matches.iter().map(|t| &t[3..]).collect()
126 }
127
128 pub fn generate_random_string() -> String {
129   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
130 }
131
132 pub fn send_email(
133   subject: &str,
134   to_email: &str,
135   to_username: &str,
136   html: &str,
137 ) -> Result<(), String> {
138   let email_config = Settings::get().email.ok_or("no_email_setup")?;
139
140   let email = Email::builder()
141     .to((to_email, to_username))
142     .from(email_config.smtp_from_address.to_owned())
143     .subject(subject)
144     .html(html)
145     .build()
146     .unwrap();
147
148   let mailer = if email_config.use_tls {
149     SmtpClient::new_simple(&email_config.smtp_server).unwrap()
150   } else {
151     SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
152   }
153   .hello_name(ClientId::Domain(Settings::get().hostname))
154   .smtp_utf8(true)
155   .authentication_mechanism(Mechanism::Plain)
156   .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
157   let mailer = if let (Some(login), Some(password)) =
158     (&email_config.smtp_login, &email_config.smtp_password)
159   {
160     mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
161   } else {
162     mailer
163   };
164
165   let mut transport = mailer.transport();
166   let result = transport.send(email.into());
167   transport.close();
168
169   match result {
170     Ok(_) => Ok(()),
171     Err(e) => Err(e.to_string()),
172   }
173 }
174
175 #[derive(Deserialize, Debug)]
176 pub struct IframelyResponse {
177   title: Option<String>,
178   description: Option<String>,
179   thumbnail_url: Option<String>,
180   html: Option<String>,
181 }
182
183 pub fn fetch_iframely(url: &str) -> Result<IframelyResponse, failure::Error> {
184   let fetch_url = format!("http://iframely/oembed?url={}", url);
185   let text: String = attohttpc::get(&fetch_url).send()?.text()?;
186   let res: IframelyResponse = serde_json::from_str(&text)?;
187   Ok(res)
188 }
189
190 #[derive(Deserialize, Debug)]
191 pub struct PictshareResponse {
192   status: String,
193   url: String,
194 }
195
196 pub fn fetch_pictshare(image_url: &str) -> Result<PictshareResponse, failure::Error> {
197   is_image_content_type(image_url)?;
198
199   let fetch_url = format!(
200     "http://pictshare/api/geturl.php?url={}",
201     utf8_percent_encode(image_url, NON_ALPHANUMERIC)
202   );
203   let text = attohttpc::get(&fetch_url).send()?.text()?;
204   let res: PictshareResponse = serde_json::from_str(&text)?;
205   Ok(res)
206 }
207
208 fn fetch_iframely_and_pictshare_data(
209   url: Option<String>,
210 ) -> (
211   Option<String>,
212   Option<String>,
213   Option<String>,
214   Option<String>,
215 ) {
216   match &url {
217     Some(url) => {
218       // Fetch iframely data
219       let (iframely_title, iframely_description, iframely_thumbnail_url, iframely_html) =
220         match fetch_iframely(url) {
221           Ok(res) => (res.title, res.description, res.thumbnail_url, res.html),
222           Err(e) => {
223             error!("iframely err: {}", e);
224             (None, None, None, None)
225           }
226         };
227
228       // Fetch pictshare thumbnail
229       let pictshare_thumbnail = match iframely_thumbnail_url {
230         Some(iframely_thumbnail_url) => match fetch_pictshare(&iframely_thumbnail_url) {
231           Ok(res) => Some(res.url),
232           Err(e) => {
233             error!("pictshare err: {}", e);
234             None
235           }
236         },
237         // Try to generate a small thumbnail if iframely is not supported
238         None => match fetch_pictshare(&url) {
239           Ok(res) => Some(res.url),
240           Err(e) => {
241             error!("pictshare err: {}", e);
242             None
243           }
244         },
245       };
246
247       (
248         iframely_title,
249         iframely_description,
250         iframely_html,
251         pictshare_thumbnail,
252       )
253     }
254     None => (None, None, None, None),
255   }
256 }
257
258 pub fn markdown_to_html(text: &str) -> String {
259   comrak::markdown_to_html(text, &comrak::ComrakOptions::default())
260 }
261
262 pub fn get_ip(conn_info: &ConnectionInfo) -> String {
263   conn_info
264     .remote()
265     .unwrap_or("127.0.0.1:12345")
266     .split(':')
267     .next()
268     .unwrap_or("127.0.0.1")
269     .to_string()
270 }
271
272 pub fn is_valid_username(name: &str) -> bool {
273   VALID_USERNAME_REGEX.is_match(name)
274 }
275
276 #[cfg(test)]
277 mod tests {
278   use crate::{
279     extract_usernames, is_email_regex, is_image_content_type, is_valid_username, remove_slurs,
280     slur_check, slurs_vec_to_str,
281   };
282
283   #[test]
284   fn test_image() {
285     assert!(is_image_content_type("https://1734811051.rsc.cdn77.org/data/images/full/365645/as-virus-kills-navajos-in-their-homes-tribal-women-provide-lifeline.jpg?w=600?w=650").is_ok());
286     assert!(is_image_content_type(
287       "https://twitter.com/BenjaminNorton/status/1259922424272957440?s=20"
288     )
289     .is_err());
290   }
291
292   #[test]
293   fn test_email() {
294     assert!(is_email_regex("gush@gmail.com"));
295     assert!(!is_email_regex("nada_neutho"));
296   }
297
298   #[test]
299   fn test_valid_register_username() {
300     assert!(is_valid_username("Hello_98"));
301     assert!(is_valid_username("ten"));
302     assert!(!is_valid_username("Hello-98"));
303     assert!(!is_valid_username("a"));
304     assert!(!is_valid_username(""));
305   }
306
307   #[test]
308   fn test_slur_filter() {
309     let test =
310       "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
311     let slur_free = "No slurs here";
312     assert_eq!(
313       remove_slurs(&test),
314       "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
315         .to_string()
316     );
317
318     let has_slurs_vec = vec![
319       "Niggerz",
320       "coons",
321       "dindu",
322       "ladyboy",
323       "retardeds",
324       "tranny",
325     ];
326     let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
327
328     assert_eq!(slur_check(test), Err(has_slurs_vec));
329     assert_eq!(slur_check(slur_free), Ok(()));
330     if let Err(slur_vec) = slur_check(test) {
331       assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
332     }
333   }
334
335   #[test]
336   fn test_extract_usernames() {
337     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");
338     let expected = vec!["another", "testme"];
339     assert_eq!(usernames, expected);
340   }
341
342   // These helped with testing
343   // #[test]
344   // fn test_iframely() {
345   //   let res = fetch_iframely("https://www.redspark.nu/?p=15341");
346   //   assert!(res.is_ok());
347   // }
348
349   // #[test]
350   // fn test_pictshare() {
351   //   let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
352   //   assert!(res.is_ok());
353   //   let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
354   //   assert!(res_other.is_err());
355   // }
356
357   // #[test]
358   // fn test_send_email() {
359   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
360   //   assert!(result.is_ok());
361   // }
362 }
363
364 lazy_static! {
365   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
366   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();
367   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
368   static ref VALID_USERNAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,20}$").unwrap();
369 }