]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Adding a search page
[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 #[derive(EnumString,ToString,Debug, Serialize, Deserialize)]
101 pub enum SearchType {
102   Both, Comments, Posts
103 }
104
105 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
106   DateTime::<Utc>::from_utc(ndt, Utc)
107 }
108
109 pub fn naive_now() -> NaiveDateTime {
110   chrono::prelude::Utc::now().naive_utc()
111 }
112
113 pub fn naive_from_unix(time: i64)  ->  NaiveDateTime {
114   NaiveDateTime::from_timestamp(time, 0)
115 }
116
117 pub fn is_email_regex(test: &str) -> bool {
118   EMAIL_REGEX.is_match(test)
119 }
120
121 pub fn remove_slurs(test: &str) -> String {
122   SLUR_REGEX.replace_all(test, "*removed*").to_string()
123 }
124
125 pub fn has_slurs(test: &str) -> bool {
126   SLUR_REGEX.is_match(test)
127 }
128
129 pub fn fuzzy_search(q: &str) -> String {
130   let replaced = q.replace(" ", "%");
131   format!("%{}%", replaced)
132 }
133
134 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
135     let page = page.unwrap_or(1);
136     let limit = limit.unwrap_or(10);
137     let offset = limit * (page - 1);
138     (limit, offset)
139 }
140
141 #[cfg(test)]
142 mod tests {
143   use {Settings, is_email_regex, remove_slurs, has_slurs, fuzzy_search};
144   #[test]
145   fn test_api() {
146     assert_eq!(Settings::get().api_endpoint(), "http://0.0.0.0/api/v1");
147   }
148
149   #[test] fn test_email() {
150     assert!(is_email_regex("gush@gmail.com"));
151     assert!(!is_email_regex("nada_neutho"));
152   } 
153
154   #[test] fn test_slur_filter() {
155     let test = "coons test dindu ladyboy tranny. This is a bunch of other safe text.".to_string();
156     let slur_free = "No slurs here";
157     assert_eq!(remove_slurs(&test), "*removed* test *removed* *removed* *removed*. This is a bunch of other safe text.".to_string());
158     assert!(has_slurs(&test));
159     assert!(!has_slurs(slur_free));
160   } 
161
162   #[test] fn test_fuzzy_search() {
163     let test = "This is a fuzzy search";
164     assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
165   }
166 }
167
168
169
170 lazy_static! {
171   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
172   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();
173 }
174