]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Merge branch 'master' into master
[lemmy.git] / server / src / lib.rs
1 #![recursion_limit = "512"]
2 #[macro_use]
3 pub extern crate strum_macros;
4 #[macro_use]
5 pub extern crate lazy_static;
6 #[macro_use]
7 pub extern crate failure;
8 #[macro_use]
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 rand;
17 pub extern crate regex;
18 pub extern crate serde;
19 pub extern crate serde_json;
20 pub extern crate strum;
21
22 pub mod api;
23 pub mod apub;
24 pub mod db;
25 pub mod schema;
26 pub mod websocket;
27
28 use chrono::{DateTime, NaiveDateTime, Utc};
29 use dotenv::dotenv;
30 use regex::Regex;
31 use std::env;
32
33 pub struct Settings {
34   db_url: String,
35   hostname: String,
36   jwt_secret: String,
37   rate_limit_message: i32,
38   rate_limit_message_per_second: i32,
39   rate_limit_post: i32,
40   rate_limit_post_per_second: i32,
41   rate_limit_register: i32,
42   rate_limit_register_per_second: i32,
43 }
44
45 impl Settings {
46   fn get() -> Self {
47     dotenv().ok();
48     Settings {
49       db_url: env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
50       hostname: env::var("HOSTNAME").unwrap_or("rrr".to_string()),
51       jwt_secret: env::var("JWT_SECRET").unwrap_or("changeme".to_string()),
52       rate_limit_message: env::var("RATE_LIMIT_MESSAGE")
53         .unwrap_or("30".to_string())
54         .parse()
55         .unwrap(),
56       rate_limit_message_per_second: env::var("RATE_LIMIT_MESSAGE_PER_SECOND")
57         .unwrap_or("60".to_string())
58         .parse()
59         .unwrap(),
60       rate_limit_post: env::var("RATE_LIMIT_POST")
61         .unwrap_or("3".to_string())
62         .parse()
63         .unwrap(),
64       rate_limit_post_per_second: env::var("RATE_LIMIT_POST_PER_SECOND")
65         .unwrap_or("600".to_string())
66         .parse()
67         .unwrap(),
68       rate_limit_register: env::var("RATE_LIMIT_REGISTER")
69         .unwrap_or("1".to_string())
70         .parse()
71         .unwrap(),
72       rate_limit_register_per_second: env::var("RATE_LIMIT_REGISTER_PER_SECOND")
73         .unwrap_or("3600".to_string())
74         .parse()
75         .unwrap(),
76     }
77   }
78   fn api_endpoint(&self) -> String {
79     format!("{}/api/v1", self.hostname)
80   }
81 }
82
83 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
84   DateTime::<Utc>::from_utc(ndt, Utc)
85 }
86
87 pub fn naive_now() -> NaiveDateTime {
88   chrono::prelude::Utc::now().naive_utc()
89 }
90
91 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
92   NaiveDateTime::from_timestamp(time, 0)
93 }
94
95 pub fn is_email_regex(test: &str) -> bool {
96   EMAIL_REGEX.is_match(test)
97 }
98
99 pub fn remove_slurs(test: &str) -> String {
100   SLUR_REGEX.replace_all(test, "*removed*").to_string()
101 }
102
103 pub fn has_slurs(test: &str) -> bool {
104   SLUR_REGEX.is_match(test)
105 }
106
107 pub fn extract_usernames(test: &str) -> Vec<&str> {
108   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
109     .find_iter(test)
110     .map(|mat| mat.as_str())
111     .collect();
112
113   // Unique
114   matches.sort_unstable();
115   matches.dedup();
116
117   // Remove /u/
118   matches.iter().map(|t| &t[3..]).collect()
119 }
120
121 #[cfg(test)]
122 mod tests {
123   use crate::{extract_usernames, has_slurs, is_email_regex, remove_slurs, Settings};
124   #[test]
125   fn test_api() {
126     assert_eq!(Settings::get().api_endpoint(), "rrr/api/v1");
127   }
128
129   #[test]
130   fn test_email() {
131     assert!(is_email_regex("gush@gmail.com"));
132     assert!(!is_email_regex("nada_neutho"));
133   }
134
135   #[test]
136   fn test_slur_filter() {
137     let test =
138       "coons test dindu ladyboy tranny retardeds. This is a bunch of other safe text.".to_string();
139     let slur_free = "No slurs here";
140     assert_eq!(
141       remove_slurs(&test),
142       "*removed* test *removed* *removed* *removed* *removed*. This is a bunch of other safe text."
143         .to_string()
144     );
145     assert!(has_slurs(&test));
146     assert!(!has_slurs(slur_free));
147   }
148
149   #[test]
150   fn test_extract_usernames() {
151     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");
152     let expected = vec!["another", "testme"];
153     assert_eq!(usernames, expected);
154   }
155 }
156
157 lazy_static! {
158   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
159   static ref SLUR_REGEX: Regex = Regex::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|nig(\b|g?(a|er)?s?)\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?)").unwrap();
160   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
161 }