1 #![recursion_limit = "512"]
3 pub extern crate strum_macros;
5 pub extern crate lazy_static;
7 pub extern crate failure;
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;
22 pub extern crate serde;
23 pub extern crate serde_json;
24 pub extern crate sha2;
25 pub extern crate strum;
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;
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;
51 use crate::settings::Settings;
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;
59 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
60 DateTime::<Utc>::from_utc(ndt, Utc)
63 pub fn naive_now() -> NaiveDateTime {
64 chrono::prelude::Utc::now().naive_utc()
67 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
68 NaiveDateTime::from_timestamp(time, 0)
71 pub fn is_email_regex(test: &str) -> bool {
72 EMAIL_REGEX.is_match(test)
75 pub fn is_image_content_type(test: &str) -> Result<(), failure::Error> {
76 if attohttpc::get(test)
80 .ok_or_else(|| format_err!("No Content-Type header"))?
82 .starts_with("image/")
86 Err(format_err!("Not an image type."))
90 pub fn remove_slurs(test: &str) -> String {
91 SLUR_REGEX.replace_all(test, "*removed*").to_string()
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();
98 matches.sort_unstable();
101 if matches.is_empty() {
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()
114 pub fn extract_usernames(test: &str) -> Vec<&str> {
115 let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
117 .map(|mat| mat.as_str())
121 matches.sort_unstable();
125 matches.iter().map(|t| &t[3..]).collect()
128 pub fn generate_random_string() -> String {
129 thread_rng().sample_iter(&Alphanumeric).take(30).collect()
137 ) -> Result<(), String> {
138 let email_config = Settings::get().email.ok_or("no_email_setup")?;
140 let email = Email::builder()
141 .to((to_email, to_username))
142 .from(email_config.smtp_from_address.to_owned())
148 let mailer = if email_config.use_tls {
149 SmtpClient::new_simple(&email_config.smtp_server).unwrap()
151 SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
153 .hello_name(ClientId::Domain(Settings::get().hostname))
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)
160 mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
165 let mut transport = mailer.transport();
166 let result = transport.send(email.into());
171 Err(e) => Err(e.to_string()),
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>,
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)?;
190 #[derive(Deserialize, Debug, Clone)]
191 pub struct PictrsResponse {
192 files: Vec<PictrsFile>,
196 #[derive(Deserialize, Debug, Clone)]
197 pub struct PictrsFile {
199 delete_token: String,
202 pub fn fetch_pictrs(image_url: &str) -> Result<PictrsResponse, failure::Error> {
203 is_image_content_type(image_url)?;
205 let fetch_url = format!(
206 "http://pictrs:8080/image/download?url={}",
207 utf8_percent_encode(image_url, NON_ALPHANUMERIC) // TODO this might not be needed
209 let text = attohttpc::get(&fetch_url).send()?.text()?;
210 let res: PictrsResponse = serde_json::from_str(&text)?;
214 Err(format_err!("{}", &res.msg))
218 fn fetch_iframely_and_pictrs_data(
228 // Fetch iframely data
229 let (iframely_title, iframely_description, iframely_thumbnail_url, iframely_html) =
230 match fetch_iframely(url) {
231 Ok(res) => (res.title, res.description, res.thumbnail_url, res.html),
233 error!("iframely err: {}", e);
234 (None, None, None, None)
238 // Fetch pictrs thumbnail
239 let pictrs_thumbnail = match iframely_thumbnail_url {
240 Some(iframely_thumbnail_url) => match fetch_pictrs(&iframely_thumbnail_url) {
241 Ok(res) => Some(res.files[0].file.to_owned()),
243 error!("pictrs err: {}", e);
247 // Try to generate a small thumbnail if iframely is not supported
248 None => match fetch_pictrs(&url) {
249 Ok(res) => Some(res.files[0].file.to_owned()),
251 error!("pictrs err: {}", e);
259 iframely_description,
264 None => (None, None, None, None),
268 pub fn markdown_to_html(text: &str) -> String {
269 comrak::markdown_to_html(text, &comrak::ComrakOptions::default())
272 pub fn get_ip(conn_info: &ConnectionInfo) -> String {
275 .unwrap_or("127.0.0.1:12345")
278 .unwrap_or("127.0.0.1")
282 pub fn is_valid_username(name: &str) -> bool {
283 VALID_USERNAME_REGEX.is_match(name)
286 pub fn is_valid_community_name(name: &str) -> bool {
287 VALID_COMMUNITY_NAME_REGEX.is_match(name)
293 extract_usernames, is_email_regex, is_image_content_type, is_valid_community_name,
294 is_valid_username, remove_slurs, slur_check, slurs_vec_to_str,
299 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());
300 assert!(is_image_content_type(
301 "https://twitter.com/BenjaminNorton/status/1259922424272957440?s=20"
308 assert!(is_email_regex("gush@gmail.com"));
309 assert!(!is_email_regex("nada_neutho"));
313 fn test_valid_register_username() {
314 assert!(is_valid_username("Hello_98"));
315 assert!(is_valid_username("ten"));
316 assert!(!is_valid_username("Hello-98"));
317 assert!(!is_valid_username("a"));
318 assert!(!is_valid_username(""));
322 fn test_valid_community_name() {
323 assert!(is_valid_community_name("example"));
324 assert!(is_valid_community_name("example_community"));
325 assert!(!is_valid_community_name("Example"));
326 assert!(!is_valid_community_name("Ex"));
327 assert!(!is_valid_community_name(""));
331 fn test_slur_filter() {
333 "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
334 let slur_free = "No slurs here";
337 "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
341 let has_slurs_vec = vec![
349 let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
351 assert_eq!(slur_check(test), Err(has_slurs_vec));
352 assert_eq!(slur_check(slur_free), Ok(()));
353 if let Err(slur_vec) = slur_check(test) {
354 assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
359 fn test_extract_usernames() {
360 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");
361 let expected = vec!["another", "testme"];
362 assert_eq!(usernames, expected);
365 // These helped with testing
367 // fn test_iframely() {
368 // let res = fetch_iframely("https://www.redspark.nu/?p=15341");
369 // assert!(res.is_ok());
373 // fn test_pictshare() {
374 // let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
375 // assert!(res.is_ok());
376 // let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
377 // assert!(res_other.is_err());
381 // fn test_send_email() {
382 // let result = send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
383 // assert!(result.is_ok());
388 static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
389 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();
390 static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
391 static ref VALID_USERNAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,20}$").unwrap();
392 static ref VALID_COMMUNITY_NAME_REGEX: Regex = Regex::new(r"^[a-z0-9_]{3,20}$").unwrap();