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