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 dotenv;
15 pub extern crate jsonwebtoken;
16 pub extern crate lettre;
17 pub extern crate lettre_email;
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;
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;
44 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
45 use rand::distributions::Alphanumeric;
46 use rand::{thread_rng, Rng};
47 use regex::{Regex, RegexBuilder};
48 use serde::Deserialize;
50 pub fn naive_now() -> NaiveDateTime {
51 chrono::prelude::Utc::now().naive_utc()
54 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
55 NaiveDateTime::from_timestamp(time, 0)
58 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
59 let now = Local::now();
60 DateTime::<FixedOffset>::from_utc(datetime, *now.offset())
63 pub fn is_email_regex(test: &str) -> bool {
64 EMAIL_REGEX.is_match(test)
67 pub fn remove_slurs(test: &str) -> String {
68 SLUR_REGEX.replace_all(test, "*removed*").to_string()
71 pub fn slur_check(test: &str) -> Result<(), Vec<&str>> {
72 let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
75 matches.sort_unstable();
78 if matches.is_empty() {
85 pub fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
86 let start = "No slurs - ";
87 let combined = &slurs.join(", ");
88 [start, combined].concat()
91 pub fn extract_usernames(test: &str) -> Vec<&str> {
92 let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
94 .map(|mat| mat.as_str())
98 matches.sort_unstable();
102 matches.iter().map(|t| &t[3..]).collect()
105 pub fn generate_random_string() -> String {
106 thread_rng().sample_iter(&Alphanumeric).take(30).collect()
114 ) -> Result<(), String> {
115 let email_config = Settings::get().email.as_ref().ok_or("no_email_setup")?;
117 let email = Email::builder()
118 .to((to_email, to_username))
119 .from(email_config.smtp_from_address.to_owned())
125 let mailer = if email_config.use_tls {
126 SmtpClient::new_simple(&email_config.smtp_server).unwrap()
128 SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
130 .hello_name(ClientId::Domain(Settings::get().hostname.to_owned()))
132 .authentication_mechanism(Mechanism::Plain)
133 .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
134 let mailer = if let (Some(login), Some(password)) =
135 (&email_config.smtp_login, &email_config.smtp_password)
137 mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
142 let mut transport = mailer.transport();
143 let result = transport.send(email.into());
148 Err(e) => Err(e.to_string()),
152 #[derive(Deserialize, Debug)]
153 pub struct IframelyResponse {
154 title: Option<String>,
155 description: Option<String>,
156 thumbnail_url: Option<String>,
157 html: Option<String>,
160 pub fn fetch_iframely(url: &str) -> Result<IframelyResponse, failure::Error> {
161 let fetch_url = format!("http://iframely/oembed?url={}", url);
162 let text = chttp::get(&fetch_url)?.text()?;
163 let res: IframelyResponse = serde_json::from_str(&text)?;
167 #[derive(Deserialize, Debug)]
168 pub struct PictshareResponse {
173 pub fn fetch_pictshare(image_url: &str) -> Result<PictshareResponse, failure::Error> {
174 let fetch_url = format!(
175 "http://pictshare/api/geturl.php?url={}",
176 utf8_percent_encode(image_url, NON_ALPHANUMERIC)
178 let text = chttp::get(&fetch_url)?.text()?;
179 let res: PictshareResponse = serde_json::from_str(&text)?;
183 fn fetch_iframely_and_pictshare_data(
191 // Fetch iframely data
192 let (iframely_title, iframely_description, iframely_thumbnail_url, iframely_html) = match url {
193 Some(url) => match fetch_iframely(&url) {
194 Ok(res) => (res.title, res.description, res.thumbnail_url, res.html),
196 error!("iframely err: {}", e);
197 (None, None, None, None)
200 None => (None, None, None, None),
203 // Fetch pictshare thumbnail
204 let pictshare_thumbnail = match iframely_thumbnail_url {
205 Some(iframely_thumbnail_url) => match fetch_pictshare(&iframely_thumbnail_url) {
206 Ok(res) => Some(res.url),
208 error!("pictshare err: {}", e);
217 iframely_description,
225 use crate::{extract_usernames, is_email_regex, remove_slurs, slur_check, slurs_vec_to_str};
229 assert!(is_email_regex("gush@gmail.com"));
230 assert!(!is_email_regex("nada_neutho"));
234 fn test_slur_filter() {
236 "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
237 let slur_free = "No slurs here";
240 "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
244 let has_slurs_vec = vec![
252 let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
254 assert_eq!(slur_check(test), Err(has_slurs_vec));
255 assert_eq!(slur_check(slur_free), Ok(()));
256 if let Err(slur_vec) = slur_check(test) {
257 assert_eq!(&slurs_vec_to_str(slur_vec), has_slurs_err_str);
262 fn test_extract_usernames() {
263 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");
264 let expected = vec!["another", "testme"];
265 assert_eq!(usernames, expected);
268 // These helped with testing
270 // fn test_iframely() {
271 // let res = fetch_iframely("https://www.redspark.nu/?p=15341");
272 // assert!(res.is_ok());
276 // fn test_pictshare() {
277 // let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
278 // assert!(res.is_ok());
279 // let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
280 // assert!(res_other.is_err());
284 // fn test_send_email() {
285 // let result = send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
286 // assert!(result.is_ok());
291 static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
292 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();
293 static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();