]> Untitled Git - lemmy.git/blob - server/src/lib.rs
32c374390e8bc37769cdbaa30ec2e0d5136393e4
[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 extern crate log;
20 pub extern crate openssl;
21 pub extern crate rand;
22 pub extern crate regex;
23 pub extern crate rss;
24 pub extern crate serde;
25 pub extern crate serde_json;
26 pub extern crate sha2;
27 pub extern crate strum;
28
29 pub mod api;
30 pub mod apub;
31 pub mod db;
32 pub mod rate_limit;
33 pub mod routes;
34 pub mod schema;
35 pub mod settings;
36 pub mod version;
37 pub mod websocket;
38
39 use crate::settings::Settings;
40 use actix_web::dev::ConnectionInfo;
41 use chrono::{DateTime, FixedOffset, Local, NaiveDateTime, Utc};
42 use isahc::prelude::*;
43 use itertools::Itertools;
44 use lettre::{
45   smtp::{
46     authentication::{Credentials, Mechanism},
47     extension::ClientId,
48     ConnectionReuseParameters,
49   },
50   ClientSecurity,
51   SmtpClient,
52   Transport,
53 };
54 use lettre_email::Email;
55 use log::error;
56 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
57 use rand::{distributions::Alphanumeric, thread_rng, Rng};
58 use regex::{Regex, RegexBuilder};
59 use serde::Deserialize;
60
61 pub type ConnectionId = usize;
62 pub type PostId = i32;
63 pub type CommunityId = i32;
64 pub type UserId = i32;
65 pub type IPAddr = String;
66
67 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
68   DateTime::<Utc>::from_utc(ndt, Utc)
69 }
70
71 pub fn naive_now() -> NaiveDateTime {
72   chrono::prelude::Utc::now().naive_utc()
73 }
74
75 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
76   NaiveDateTime::from_timestamp(time, 0)
77 }
78
79 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
80   let now = Local::now();
81   DateTime::<FixedOffset>::from_utc(datetime, *now.offset())
82 }
83
84 pub fn is_email_regex(test: &str) -> bool {
85   EMAIL_REGEX.is_match(test)
86 }
87
88 pub fn is_image_content_type(test: &str) -> Result<(), failure::Error> {
89   if isahc::get(test)?
90     .headers()
91     .get("Content-Type")
92     .ok_or_else(|| format_err!("No Content-Type header"))?
93     .to_str()?
94     .starts_with("image/")
95   {
96     Ok(())
97   } else {
98     Err(format_err!("Not an image type."))
99   }
100 }
101
102 pub fn remove_slurs(test: &str) -> String {
103   SLUR_REGEX.replace_all(test, "*removed*").to_string()
104 }
105
106 pub fn slur_check(test: &str) -> Result<(), Vec<&str>> {
107   let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
108
109   // Unique
110   matches.sort_unstable();
111   matches.dedup();
112
113   if matches.is_empty() {
114     Ok(())
115   } else {
116     Err(matches)
117   }
118 }
119
120 pub fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
121   let start = "No slurs - ";
122   let combined = &slurs.join(", ");
123   [start, combined].concat()
124 }
125
126 pub fn generate_random_string() -> String {
127   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
128 }
129
130 pub fn send_email(
131   subject: &str,
132   to_email: &str,
133   to_username: &str,
134   html: &str,
135 ) -> Result<(), String> {
136   let email_config = Settings::get().email.ok_or("no_email_setup")?;
137
138   let email = Email::builder()
139     .to((to_email, to_username))
140     .from(email_config.smtp_from_address.to_owned())
141     .subject(subject)
142     .html(html)
143     .build()
144     .unwrap();
145
146   let mailer = if email_config.use_tls {
147     SmtpClient::new_simple(&email_config.smtp_server).unwrap()
148   } else {
149     SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
150   }
151   .hello_name(ClientId::Domain(Settings::get().hostname))
152   .smtp_utf8(true)
153   .authentication_mechanism(Mechanism::Plain)
154   .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
155   let mailer = if let (Some(login), Some(password)) =
156     (&email_config.smtp_login, &email_config.smtp_password)
157   {
158     mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
159   } else {
160     mailer
161   };
162
163   let mut transport = mailer.transport();
164   let result = transport.send(email.into());
165   transport.close();
166
167   match result {
168     Ok(_) => Ok(()),
169     Err(e) => Err(e.to_string()),
170   }
171 }
172
173 #[derive(Deserialize, Debug)]
174 pub struct IframelyResponse {
175   title: Option<String>,
176   description: Option<String>,
177   thumbnail_url: Option<String>,
178   html: Option<String>,
179 }
180
181 pub fn fetch_iframely(url: &str) -> Result<IframelyResponse, failure::Error> {
182   let fetch_url = format!("http://iframely/oembed?url={}", url);
183   let text = isahc::get(&fetch_url)?.text()?;
184   let res: IframelyResponse = serde_json::from_str(&text)?;
185   Ok(res)
186 }
187
188 #[derive(Deserialize, Debug)]
189 pub struct PictshareResponse {
190   status: String,
191   url: String,
192 }
193
194 pub fn fetch_pictshare(image_url: &str) -> Result<PictshareResponse, failure::Error> {
195   is_image_content_type(image_url)?;
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 // TODO nothing is done with community / group webfingers yet, so just ignore those for now
271 #[derive(Clone, PartialEq, Eq, Hash)]
272 pub struct MentionData {
273   pub name: String,
274   pub domain: String,
275 }
276
277 impl MentionData {
278   pub fn is_local(&self) -> bool {
279     Settings::get().hostname.eq(&self.domain)
280   }
281   pub fn full_name(&self) -> String {
282     format!("@{}@{}", &self.name, &self.domain)
283   }
284 }
285
286 pub fn scrape_text_for_mentions(text: &str) -> Vec<MentionData> {
287   let mut out: Vec<MentionData> = Vec::new();
288   for caps in WEBFINGER_USER_REGEX.captures_iter(text) {
289     out.push(MentionData {
290       name: caps["name"].to_string(),
291       domain: caps["domain"].to_string(),
292     });
293   }
294   out.into_iter().unique().collect()
295 }
296
297 pub fn is_valid_username(name: &str) -> bool {
298   VALID_USERNAME_REGEX.is_match(name)
299 }
300
301 #[cfg(test)]
302 mod tests {
303   use crate::{
304     is_email_regex,
305     is_image_content_type,
306     is_valid_username,
307     remove_slurs,
308     scrape_text_for_mentions,
309     slur_check,
310     slurs_vec_to_str,
311   };
312
313   #[test]
314   fn test_mentions_regex() {
315     let text = "Just read a great blog post by [@tedu@honk.teduangst.com](/u/test). And another by !test_community@fish.teduangst.com . Another [@lemmy@lemmy_alpha:8540](/u/fish)";
316     let mentions = scrape_text_for_mentions(text);
317
318     assert_eq!(mentions[0].name, "tedu".to_string());
319     assert_eq!(mentions[0].domain, "honk.teduangst.com".to_string());
320     assert_eq!(mentions[1].domain, "lemmy_alpha:8540".to_string());
321   }
322
323   #[test]
324   fn test_image() {
325     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());
326     assert!(is_image_content_type(
327       "https://twitter.com/BenjaminNorton/status/1259922424272957440?s=20"
328     )
329     .is_err());
330   }
331
332   #[test]
333   fn test_email() {
334     assert!(is_email_regex("gush@gmail.com"));
335     assert!(!is_email_regex("nada_neutho"));
336   }
337
338   #[test]
339   fn test_valid_register_username() {
340     assert!(is_valid_username("Hello_98"));
341     assert!(is_valid_username("ten"));
342     assert!(!is_valid_username("Hello-98"));
343     assert!(!is_valid_username("a"));
344     assert!(!is_valid_username(""));
345   }
346
347   #[test]
348   fn test_slur_filter() {
349     let test =
350       "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
351     let slur_free = "No slurs here";
352     assert_eq!(
353       remove_slurs(&test),
354       "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
355         .to_string()
356     );
357
358     let has_slurs_vec = vec![
359       "Niggerz",
360       "coons",
361       "dindu",
362       "ladyboy",
363       "retardeds",
364       "tranny",
365     ];
366     let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
367
368     assert_eq!(slur_check(test), Err(has_slurs_vec));
369     assert_eq!(slur_check(slur_free), Ok(()));
370     if let Err(slur_vec) = slur_check(test) {
371       assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
372     }
373   }
374
375   // These helped with testing
376   // #[test]
377   // fn test_iframely() {
378   //   let res = fetch_iframely("https://www.redspark.nu/?p=15341");
379   //   assert!(res.is_ok());
380   // }
381
382   // #[test]
383   // fn test_pictshare() {
384   //   let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
385   //   assert!(res.is_ok());
386   //   let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
387   //   assert!(res_other.is_err());
388   // }
389
390   // #[test]
391   // fn test_send_email() {
392   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
393   //   assert!(result.is_ok());
394   // }
395 }
396
397 lazy_static! {
398   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
399   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();
400   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
401   // TODO keep this old one, it didn't work with port well tho
402   // static ref WEBFINGER_USER_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)").unwrap();
403   static ref WEBFINGER_USER_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").unwrap();
404   static ref VALID_USERNAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,20}$").unwrap();
405 }