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