]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Cleaning up error handling on server.rs
[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 }
80
81 impl Settings {
82   fn get() -> Self {
83     dotenv().ok();
84     Settings {
85       db_url: env::var("DATABASE_URL")
86         .expect("DATABASE_URL must be set"),
87         hostname: env::var("HOSTNAME").unwrap_or("http://0.0.0.0".to_string())
88     }
89   }
90   fn api_endpoint(&self) -> String {
91     format!("{}/api/v1", self.hostname)
92   }
93 }
94
95 #[derive(EnumString,ToString,Debug, Serialize, Deserialize)]
96 pub enum SortType {
97   Hot, New, TopDay, TopWeek, TopMonth, TopYear, TopAll
98 }
99
100 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
101   DateTime::<Utc>::from_utc(ndt, Utc)
102 }
103
104 pub fn naive_now() -> NaiveDateTime {
105   chrono::prelude::Utc::now().naive_utc()
106 }
107
108 pub fn naive_from_unix(time: i64)  ->  NaiveDateTime {
109   NaiveDateTime::from_timestamp(time, 0)
110 }
111
112 pub fn is_email_regex(test: &str) -> bool {
113   EMAIL_REGEX.is_match(test)
114 }
115
116 pub fn remove_slurs(test: &str) -> String {
117   SLUR_REGEX.replace_all(test, "*removed*").to_string()
118 }
119
120 pub fn has_slurs(test: &str) -> bool {
121   SLUR_REGEX.is_match(test)
122 }
123
124 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
125     let page = page.unwrap_or(1);
126     let limit = limit.unwrap_or(10);
127     let offset = limit * (page - 1);
128     (limit, offset)
129 }
130
131 #[cfg(test)]
132 mod tests {
133   use {Settings, is_email_regex, remove_slurs, has_slurs};
134   #[test]
135   fn test_api() {
136     assert_eq!(Settings::get().api_endpoint(), "http://0.0.0.0/api/v1");
137   }
138
139   #[test] fn test_email() {
140     assert!(is_email_regex("gush@gmail.com"));
141     assert!(!is_email_regex("nada_neutho"));
142   } 
143
144   #[test] fn test_slur_filter() {
145     let test = "coons test dindu ladyboy tranny. This is a bunch of other safe text.".to_string();
146     let slur_free = "No slurs here";
147     assert_eq!(remove_slurs(&test), "*removed* test *removed* *removed* *removed*. This is a bunch of other safe text.".to_string());
148     assert!(has_slurs(&test));
149     assert!(!has_slurs(slur_free));
150   } 
151 }
152
153
154 lazy_static! {
155   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
156   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();
157 }
158