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