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