]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Merge branch 'master' into dev
[lemmy.git] / server / src / lib.rs
1 #[macro_use]
2 pub extern crate diesel;
3 pub extern crate dotenv;
4 pub extern crate chrono;
5 pub extern crate serde;
6 pub extern crate serde_json;
7 pub extern crate actix;
8 pub extern crate actix_web;
9 pub extern crate rand;
10 pub extern crate strum;
11 pub extern crate jsonwebtoken;
12 pub extern crate bcrypt;
13 pub extern crate regex;
14 #[macro_use] pub extern crate strum_macros;
15 #[macro_use] pub extern crate lazy_static;
16 #[macro_use] extern crate failure;
17
18 pub mod schema;
19 pub mod apub;
20 pub mod actions;
21 pub mod websocket_server;
22
23 use diesel::*;
24 use diesel::pg::PgConnection;
25 use diesel::result::Error;
26 use dotenv::dotenv;
27 use std::env;
28 use regex::Regex;
29 use serde::{Deserialize, Serialize};
30 use chrono::{DateTime, NaiveDateTime, Utc};
31
32 pub trait Crud<T> {
33   fn create(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
34   fn read(conn: &PgConnection, id: i32) -> Result<Self, Error> where Self: Sized;  
35   fn update(conn: &PgConnection, id: i32, form: &T) -> Result<Self, Error> where Self: Sized;  
36   fn delete(conn: &PgConnection, id: i32) -> Result<usize, Error> where Self: Sized;
37 }
38
39 pub trait Followable<T> {
40   fn follow(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
41   fn ignore(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
42 }
43
44 pub trait Joinable<T> {
45   fn join(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
46   fn leave(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
47 }
48
49 pub trait Likeable<T> {
50   fn read(conn: &PgConnection, id: i32) -> Result<Vec<Self>, Error> where Self: Sized;
51   fn like(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
52   fn remove(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
53 }
54
55 pub trait Bannable<T> {
56   fn ban(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
57   fn unban(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
58 }
59
60 pub trait Saveable<T> {
61   fn save(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
62   fn unsave(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
63 }
64
65 pub trait Readable<T> {
66   fn mark_as_read(conn: &PgConnection, form: &T) -> Result<Self, Error> where Self: Sized;
67   fn mark_as_unread(conn: &PgConnection, form: &T) -> Result<usize, Error> where Self: Sized;
68 }
69
70 pub fn establish_connection() -> PgConnection {
71   let db_url = Settings::get().db_url;
72   PgConnection::establish(&db_url)
73     .expect(&format!("Error connecting to {}", db_url))
74 }
75
76 pub struct Settings {
77   db_url: String,
78   hostname: String,
79   jwt_secret: String,
80 }
81
82 impl Settings {
83   fn get() -> Self {
84     dotenv().ok();
85     Settings {
86       db_url: env::var("DATABASE_URL")
87         .expect("DATABASE_URL must be set"),
88         hostname: env::var("HOSTNAME").unwrap_or("rrr".to_string()),
89         jwt_secret: env::var("JWT_SECRET").unwrap_or("changeme".to_string()),
90     }
91   }
92   fn api_endpoint(&self) -> String {
93     format!("{}/api/v1", self.hostname)
94   }
95 }
96
97 #[derive(EnumString,ToString,Debug, Serialize, Deserialize)]
98 pub enum SortType {
99   Hot, New, TopDay, TopWeek, TopMonth, TopYear, TopAll
100 }
101
102 #[derive(EnumString,ToString,Debug, Serialize, Deserialize)]
103 pub enum SearchType {
104   Both, Comments, Posts
105 }
106
107 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
108   DateTime::<Utc>::from_utc(ndt, Utc)
109 }
110
111 pub fn naive_now() -> NaiveDateTime {
112   chrono::prelude::Utc::now().naive_utc()
113 }
114
115 pub fn naive_from_unix(time: i64)  ->  NaiveDateTime {
116   NaiveDateTime::from_timestamp(time, 0)
117 }
118
119 pub fn is_email_regex(test: &str) -> bool {
120   EMAIL_REGEX.is_match(test)
121 }
122
123 pub fn remove_slurs(test: &str) -> String {
124   SLUR_REGEX.replace_all(test, "*removed*").to_string()
125 }
126
127 pub fn has_slurs(test: &str) -> bool {
128   SLUR_REGEX.is_match(test)
129 }
130
131 pub fn fuzzy_search(q: &str) -> String {
132   let replaced = q.replace(" ", "%");
133   format!("%{}%", replaced)
134 }
135
136 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
137     let page = page.unwrap_or(1);
138     let limit = limit.unwrap_or(10);
139     let offset = limit * (page - 1);
140     (limit, offset)
141 }
142
143 #[cfg(test)]
144 mod tests {
145   use {Settings, is_email_regex, remove_slurs, has_slurs, fuzzy_search};
146   #[test]
147   fn test_api() {
148     assert_eq!(Settings::get().api_endpoint(), "rrr/api/v1");
149   }
150
151   #[test] fn test_email() {
152     assert!(is_email_regex("gush@gmail.com"));
153     assert!(!is_email_regex("nada_neutho"));
154   } 
155
156   #[test] fn test_slur_filter() {
157     let test = "coons test dindu ladyboy tranny. This is a bunch of other safe text.".to_string();
158     let slur_free = "No slurs here";
159     assert_eq!(remove_slurs(&test), "*removed* test *removed* *removed* *removed*. This is a bunch of other safe text.".to_string());
160     assert!(has_slurs(&test));
161     assert!(!has_slurs(slur_free));
162   } 
163
164   #[test] fn test_fuzzy_search() {
165     let test = "This is a fuzzy search";
166     assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
167   }
168 }
169
170
171
172 lazy_static! {
173   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
174   static ref SLUR_REGEX: Regex = Regex::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|\bnig(\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?))").unwrap();
175 }
176