]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
ca544bd49aed0375014a991ec160dbed6c244157
[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
13 #[cfg(test)]
14 mod test;
15 pub mod utils;
16 pub mod version;
17
18 use crate::settings::structs::Settings;
19 use http::StatusCode;
20 use regex::Regex;
21 use std::fmt;
22 use thiserror::Error;
23
24 pub type ConnectionId = usize;
25
26 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
27 pub struct IpAddr(pub String);
28
29 impl fmt::Display for IpAddr {
30   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31     write!(f, "{}", self.0)
32   }
33 }
34
35 #[macro_export]
36 macro_rules! location_info {
37   () => {
38     format!(
39       "None value at {}:{}, column {}",
40       file!(),
41       line!(),
42       column!()
43     )
44   };
45 }
46
47 #[derive(Debug, Error)]
48 #[error("{{\"error\":\"{message}\"}}")]
49 pub struct ApiError {
50   pub message: String,
51 }
52
53 impl ApiError {
54   pub fn err(msg: &str) -> Self {
55     ApiError {
56       message: msg.to_string(),
57     }
58   }
59 }
60
61 #[derive(Debug)]
62 pub struct LemmyError {
63   pub inner: anyhow::Error,
64 }
65
66 impl<T> From<T> for LemmyError
67 where
68   T: Into<anyhow::Error>,
69 {
70   fn from(t: T) -> Self {
71     LemmyError { inner: t.into() }
72   }
73 }
74
75 impl std::fmt::Display for LemmyError {
76   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
77     self.inner.fmt(f)
78   }
79 }
80
81 impl actix_web::error::ResponseError for LemmyError {
82   fn status_code(&self) -> StatusCode {
83     match self.inner.downcast_ref::<diesel::result::Error>() {
84       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
85       _ => StatusCode::INTERNAL_SERVER_ERROR,
86     }
87   }
88 }
89
90 lazy_static! {
91   pub static ref WEBFINGER_COMMUNITY_REGEX: Regex = Regex::new(&format!(
92     "^group:([a-z0-9_]{{3,}})@{}$",
93     Settings::get().hostname()
94   ))
95   .expect("compile webfinger regex");
96   pub static ref WEBFINGER_USERNAME_REGEX: Regex = Regex::new(&format!(
97     "^acct:([a-z0-9_]{{3,}})@{}$",
98     Settings::get().hostname()
99   ))
100   .expect("compile webfinger regex");
101 }