]> Untitled Git - lemmy.git/blob - server/lemmy_utils/src/utils.rs
87aad574a15b481cb0cace9b3299b8349dced250
[lemmy.git] / server / lemmy_utils / src / utils.rs
1 use crate::{settings::Settings, APIError};
2 use actix_web::dev::ConnectionInfo;
3 use chrono::{DateTime, FixedOffset, Local, NaiveDateTime};
4 use itertools::Itertools;
5 use rand::{distributions::Alphanumeric, thread_rng, Rng};
6 use regex::{Regex, RegexBuilder};
7
8 lazy_static! {
9 static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
10 static ref SLUR_REGEX: Regex = RegexBuilder::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|\bn(i|1)g(\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)?|\btr(a|@)nn?(y|ies?)|ladyboy(s?)|\b(b|re|r)tard(ed)?s?)").case_insensitive(true).build().unwrap();
11 static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
12 // TODO keep this old one, it didn't work with port well tho
13 // static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)").unwrap();
14 static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").unwrap();
15 static ref VALID_USERNAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,20}$").unwrap();
16 static ref VALID_COMMUNITY_NAME_REGEX: Regex = Regex::new(r"^[a-z0-9_]{3,20}$").unwrap();
17 static ref VALID_POST_TITLE_REGEX: Regex = Regex::new(r".*\S.*").unwrap();
18 }
19
20 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
21   NaiveDateTime::from_timestamp(time, 0)
22 }
23
24 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
25   let now = Local::now();
26   DateTime::<FixedOffset>::from_utc(datetime, *now.offset())
27 }
28
29 pub fn remove_slurs(test: &str) -> String {
30   SLUR_REGEX.replace_all(test, "*removed*").to_string()
31 }
32
33 pub(crate) fn slur_check(test: &str) -> Result<(), Vec<&str>> {
34   let mut matches: Vec<&str> = SLUR_REGEX.find_iter(test).map(|mat| mat.as_str()).collect();
35
36   // Unique
37   matches.sort_unstable();
38   matches.dedup();
39
40   if matches.is_empty() {
41     Ok(())
42   } else {
43     Err(matches)
44   }
45 }
46
47 pub fn check_slurs(text: &str) -> Result<(), APIError> {
48   if let Err(slurs) = slur_check(text) {
49     Err(APIError::err(&slurs_vec_to_str(slurs)))
50   } else {
51     Ok(())
52   }
53 }
54
55 pub fn check_slurs_opt(text: &Option<String>) -> Result<(), APIError> {
56   match text {
57     Some(t) => check_slurs(t),
58     None => Ok(()),
59   }
60 }
61
62 pub(crate) fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
63   let start = "No slurs - ";
64   let combined = &slurs.join(", ");
65   [start, combined].concat()
66 }
67
68 pub fn generate_random_string() -> String {
69   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
70 }
71
72 pub fn markdown_to_html(text: &str) -> String {
73   comrak::markdown_to_html(text, &comrak::ComrakOptions::default())
74 }
75
76 // TODO nothing is done with community / group webfingers yet, so just ignore those for now
77 #[derive(Clone, PartialEq, Eq, Hash)]
78 pub struct MentionData {
79   pub name: String,
80   pub domain: String,
81 }
82
83 impl MentionData {
84   pub fn is_local(&self) -> bool {
85     Settings::get().hostname.eq(&self.domain)
86   }
87   pub fn full_name(&self) -> String {
88     format!("@{}@{}", &self.name, &self.domain)
89   }
90 }
91
92 pub fn scrape_text_for_mentions(text: &str) -> Vec<MentionData> {
93   let mut out: Vec<MentionData> = Vec::new();
94   for caps in MENTIONS_REGEX.captures_iter(text) {
95     out.push(MentionData {
96       name: caps["name"].to_string(),
97       domain: caps["domain"].to_string(),
98     });
99   }
100   out.into_iter().unique().collect()
101 }
102
103 pub fn is_valid_username(name: &str) -> bool {
104   VALID_USERNAME_REGEX.is_match(name)
105 }
106
107 // Can't do a regex here, reverse lookarounds not supported
108 pub fn is_valid_preferred_username(preferred_username: &str) -> bool {
109   !preferred_username.starts_with('@')
110     && preferred_username.len() >= 3
111     && preferred_username.len() <= 20
112 }
113
114 pub fn is_valid_community_name(name: &str) -> bool {
115   VALID_COMMUNITY_NAME_REGEX.is_match(name)
116 }
117
118 pub fn is_valid_post_title(title: &str) -> bool {
119   VALID_POST_TITLE_REGEX.is_match(title)
120 }
121
122 pub fn get_ip(conn_info: &ConnectionInfo) -> String {
123   conn_info
124     .realip_remote_addr()
125     .unwrap_or("127.0.0.1:12345")
126     .split(':')
127     .next()
128     .unwrap_or("127.0.0.1")
129     .to_string()
130 }