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