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