]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
Move routes into separate crate to speed up compilation
[lemmy.git] / crates / utils / src / lib.rs
1 #[macro_use]
2 extern crate lazy_static;
3 #[macro_use]
4 extern crate strum_macros;
5
6 pub mod apub;
7 pub mod claims;
8 pub mod email;
9 pub mod rate_limit;
10 pub mod request;
11 pub mod settings;
12 #[cfg(test)]
13 mod test;
14 pub mod utils;
15 pub mod version;
16
17 use crate::settings::Settings;
18 use http::StatusCode;
19 use regex::Regex;
20 use thiserror::Error;
21
22 pub type ConnectionId = usize;
23 pub type PostId = i32;
24 pub type CommunityId = i32;
25 pub type UserId = i32;
26 pub type IPAddr = String;
27
28 #[macro_export]
29 macro_rules! location_info {
30   () => {
31     format!(
32       "None value at {}:{}, column {}",
33       file!(),
34       line!(),
35       column!()
36     )
37   };
38 }
39
40 #[derive(Debug, Error)]
41 #[error("{{\"error\":\"{message}\"}}")]
42 pub struct APIError {
43   pub message: String,
44 }
45
46 impl APIError {
47   pub fn err(msg: &str) -> Self {
48     APIError {
49       message: msg.to_string(),
50     }
51   }
52 }
53
54 #[derive(Debug)]
55 pub struct LemmyError {
56   pub inner: anyhow::Error,
57 }
58
59 impl<T> From<T> for LemmyError
60 where
61   T: Into<anyhow::Error>,
62 {
63   fn from(t: T) -> Self {
64     LemmyError { inner: t.into() }
65   }
66 }
67
68 impl std::fmt::Display for LemmyError {
69   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
70     self.inner.fmt(f)
71   }
72 }
73
74 impl actix_web::error::ResponseError for LemmyError {
75   fn status_code(&self) -> StatusCode {
76     match self.inner.downcast_ref::<diesel::result::Error>() {
77       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
78       _ => StatusCode::INTERNAL_SERVER_ERROR,
79     }
80   }
81 }
82
83 lazy_static! {
84   pub static ref WEBFINGER_COMMUNITY_REGEX: Regex = Regex::new(&format!(
85     "^group:([a-z0-9_]{{3, 20}})@{}$",
86     Settings::get().hostname
87   ))
88   .unwrap();
89   pub static ref WEBFINGER_USER_REGEX: Regex = Regex::new(&format!(
90     "^acct:([a-z0-9_]{{3, 20}})@{}$",
91     Settings::get().hostname
92   ))
93   .unwrap();
94 }