]> Untitled Git - lemmy.git/blob - crates/utils/src/utils.rs
97384fc2f19d0076706209bf4ce3e5b40b213901
[lemmy.git] / crates / utils / src / utils.rs
1 use crate::{ApiError, IpAddr};
2 use actix_web::dev::ConnectionInfo;
3 use chrono::{DateTime, FixedOffset, NaiveDateTime};
4 use itertools::Itertools;
5 use rand::{distributions::Alphanumeric, thread_rng, Rng};
6 use regex::Regex;
7 use url::Url;
8
9 lazy_static! {
10   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").expect("compile regex");
11
12   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").expect("compile regex");
13   // TODO keep this old one, it didn't work with port well tho
14   // static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)").expect("compile regex");
15   static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").expect("compile regex");
16   static ref VALID_ACTOR_NAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,}$").expect("compile regex");
17   static ref VALID_POST_TITLE_REGEX: Regex = Regex::new(r".*\S.*").expect("compile regex");
18   static ref VALID_MATRIX_ID_REGEX: Regex = Regex::new(r"^@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").expect("compile regex");
19   // taken from https://en.wikipedia.org/wiki/UTM_parameters
20   static ref CLEAN_URL_PARAMS_REGEX: Regex = Regex::new(r"^utm_source|utm_medium|utm_campaign|utm_term|utm_content|gclid|gclsrc|dclid|fbclid$").expect("compile regex");
21 }
22
23 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
24   NaiveDateTime::from_timestamp(time, 0)
25 }
26
27 pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
28   DateTime::<FixedOffset>::from_utc(datetime, FixedOffset::east(0))
29 }
30
31 pub fn remove_slurs(test: &str, slur_regex: &Regex) -> String {
32   slur_regex.replace_all(test, "*removed*").to_string()
33 }
34
35 pub(crate) fn slur_check<'a>(test: &'a str, slur_regex: &'a Regex) -> Result<(), Vec<&'a str>> {
36   let mut matches: Vec<&str> = slur_regex.find_iter(test).map(|mat| mat.as_str()).collect();
37
38   // Unique
39   matches.sort_unstable();
40   matches.dedup();
41
42   if matches.is_empty() {
43     Ok(())
44   } else {
45     Err(matches)
46   }
47 }
48
49 pub fn check_slurs(text: &str, slur_regex: &Regex) -> Result<(), ApiError> {
50   if let Err(slurs) = slur_check(text, slur_regex) {
51     Err(ApiError::err(&slurs_vec_to_str(slurs)))
52   } else {
53     Ok(())
54   }
55 }
56
57 pub fn check_slurs_opt(text: &Option<String>, slur_regex: &Regex) -> Result<(), ApiError> {
58   match text {
59     Some(t) => check_slurs(t, slur_regex),
60     None => Ok(()),
61   }
62 }
63
64 pub(crate) fn slurs_vec_to_str(slurs: Vec<&str>) -> String {
65   let start = "No slurs - ";
66   let combined = &slurs.join(", ");
67   [start, combined].concat()
68 }
69
70 pub fn generate_random_string() -> String {
71   thread_rng()
72     .sample_iter(&Alphanumeric)
73     .map(char::from)
74     .take(30)
75     .collect()
76 }
77
78 pub fn markdown_to_html(text: &str) -> String {
79   comrak::markdown_to_html(text, &comrak::ComrakOptions::default())
80 }
81
82 // TODO nothing is done with community / group webfingers yet, so just ignore those for now
83 #[derive(Clone, PartialEq, Eq, Hash)]
84 pub struct MentionData {
85   pub name: String,
86   pub domain: String,
87 }
88
89 impl MentionData {
90   pub fn is_local(&self, hostname: &str) -> bool {
91     hostname.eq(&self.domain)
92   }
93   pub fn full_name(&self) -> String {
94     format!("@{}@{}", &self.name, &self.domain)
95   }
96 }
97
98 pub fn scrape_text_for_mentions(text: &str) -> Vec<MentionData> {
99   let mut out: Vec<MentionData> = Vec::new();
100   for caps in MENTIONS_REGEX.captures_iter(text) {
101     out.push(MentionData {
102       name: caps["name"].to_string(),
103       domain: caps["domain"].to_string(),
104     });
105   }
106   out.into_iter().unique().collect()
107 }
108
109 pub fn is_valid_actor_name(name: &str, actor_name_max_length: usize) -> bool {
110   name.chars().count() <= actor_name_max_length && VALID_ACTOR_NAME_REGEX.is_match(name)
111 }
112
113 // Can't do a regex here, reverse lookarounds not supported
114 pub fn is_valid_display_name(name: &str, actor_name_max_length: usize) -> bool {
115   !name.starts_with('@')
116     && !name.starts_with('\u{200b}')
117     && name.chars().count() >= 3
118     && name.chars().count() <= actor_name_max_length
119 }
120
121 pub fn is_valid_matrix_id(matrix_id: &str) -> bool {
122   VALID_MATRIX_ID_REGEX.is_match(matrix_id)
123 }
124
125 pub fn is_valid_post_title(title: &str) -> bool {
126   VALID_POST_TITLE_REGEX.is_match(title)
127 }
128
129 pub fn get_ip(conn_info: &ConnectionInfo) -> IpAddr {
130   IpAddr(
131     conn_info
132       .realip_remote_addr()
133       .unwrap_or("127.0.0.1:12345")
134       .split(':')
135       .next()
136       .unwrap_or("127.0.0.1")
137       .to_string(),
138   )
139 }
140
141 pub fn clean_url_params(mut url: Url) -> Url {
142   if url.query().is_some() {
143     let new_query = url
144       .query_pairs()
145       .filter(|q| !CLEAN_URL_PARAMS_REGEX.is_match(&q.0))
146       .map(|q| format!("{}={}", q.0, q.1))
147       .join("&");
148     url.set_query(Some(&new_query));
149   }
150   url
151 }
152
153 #[cfg(test)]
154 mod tests {
155   use crate::utils::clean_url_params;
156   use url::Url;
157
158   #[test]
159   fn test_clean_url_params() {
160     let url = Url::parse("https://example.com/path/123?utm_content=buffercf3b2&utm_medium=social&username=randomuser&id=123").unwrap();
161     let cleaned = clean_url_params(url);
162     let expected = Url::parse("https://example.com/path/123?username=randomuser&id=123").unwrap();
163     assert_eq!(expected.to_string(), cleaned.to_string());
164
165     let url = Url::parse("https://example.com/path/123").unwrap();
166     let cleaned = clean_url_params(url.clone());
167     assert_eq!(url.to_string(), cleaned.to_string());
168   }
169 }