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;
20 pub extern crate openssl;
21 pub extern crate rand;
22 pub extern crate regex;
24 pub extern crate serde;
25 pub extern crate serde_json;
26 pub extern crate sha2;
27 pub extern crate strum;
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;
46 authentication::{Credentials, Mechanism},
48 ConnectionReuseParameters,
54 use lettre_email::Email;
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;
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;
67 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
68 DateTime::<Utc>::from_utc(ndt, Utc)
71 pub fn naive_now() -> NaiveDateTime {
72 chrono::prelude::Utc::now().naive_utc()
75 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
76 NaiveDateTime::from_timestamp(time, 0)
79 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
80 let now = Local::now();
81 DateTime::<FixedOffset>::from_utc(datetime, *now.offset())
84 pub fn is_email_regex(test: &str) -> bool {
85 EMAIL_REGEX.is_match(test)
88 pub fn is_image_content_type(test: &str) -> Result<(), failure::Error> {
92 .ok_or_else(|| format_err!("No Content-Type header"))?
94 .starts_with("image/")
98 Err(format_err!("Not an image type."))
102 pub fn remove_slurs(test: &str) -> String {
103 SLUR_REGEX.replace_all(test, "*removed*").to_string()
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();
110 matches.sort_unstable();
113 if matches.is_empty() {
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()
126 pub fn generate_random_string() -> String {
127 thread_rng().sample_iter(&Alphanumeric).take(30).collect()
135 ) -> Result<(), String> {
136 let email_config = Settings::get().email.ok_or("no_email_setup")?;
138 let email = Email::builder()
139 .to((to_email, to_username))
140 .from(email_config.smtp_from_address.to_owned())
146 let mailer = if email_config.use_tls {
147 SmtpClient::new_simple(&email_config.smtp_server).unwrap()
149 SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
151 .hello_name(ClientId::Domain(Settings::get().hostname))
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)
158 mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
163 let mut transport = mailer.transport();
164 let result = transport.send(email.into());
169 Err(e) => Err(e.to_string()),
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>,
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)?;
188 #[derive(Deserialize, Debug)]
189 pub struct PictshareResponse {
194 pub fn fetch_pictshare(image_url: &str) -> Result<PictshareResponse, failure::Error> {
195 is_image_content_type(image_url)?;
197 let fetch_url = format!(
198 "http://pictshare/api/geturl.php?url={}",
199 utf8_percent_encode(image_url, NON_ALPHANUMERIC)
201 let text = isahc::get(&fetch_url)?.text()?;
202 let res: PictshareResponse = serde_json::from_str(&text)?;
206 fn fetch_iframely_and_pictshare_data(
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),
221 error!("iframely err: {}", e);
222 (None, None, None, None)
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),
231 error!("pictshare err: {}", e);
235 // Try to generate a small thumbnail if iframely is not supported
236 None => match fetch_pictshare(&url) {
237 Ok(res) => Some(res.url),
239 error!("pictshare err: {}", e);
247 iframely_description,
252 None => (None, None, None, None),
256 pub fn markdown_to_html(text: &str) -> String {
257 comrak::markdown_to_html(text, &comrak::ComrakOptions::default())
260 pub fn get_ip(conn_info: &ConnectionInfo) -> String {
263 .unwrap_or("127.0.0.1:12345")
266 .unwrap_or("127.0.0.1")
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 {
278 pub fn is_local(&self) -> bool {
279 Settings::get().hostname.eq(&self.domain)
281 pub fn full_name(&self) -> String {
282 format!("@{}@{}", &self.name, &self.domain)
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(),
294 out.into_iter().unique().collect()
297 pub fn is_valid_username(name: &str) -> bool {
298 VALID_USERNAME_REGEX.is_match(name)
305 is_image_content_type,
308 scrape_text_for_mentions,
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);
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());
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"
334 assert!(is_email_regex("gush@gmail.com"));
335 assert!(!is_email_regex("nada_neutho"));
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(""));
348 fn test_slur_filter() {
350 "coons test dindu ladyboy tranny retardeds. Capitalized Niggerz. This is a bunch of other safe text.";
351 let slur_free = "No slurs here";
354 "*removed* test *removed* *removed* *removed* *removed*. Capitalized *removed*. This is a bunch of other safe text."
358 let has_slurs_vec = vec![
366 let has_slurs_err_str = "No slurs - Niggerz, coons, dindu, ladyboy, retardeds, tranny";
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);
375 // These helped with testing
377 // fn test_iframely() {
378 // let res = fetch_iframely("https://www.redspark.nu/?p=15341");
379 // assert!(res.is_ok());
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());
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());
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();