use hotaru::{object, Value};
use super::Server;
#[derive(Debug, Clone)]
pub struct User {
pub id: UserID,
username: String,
email: String,
is_active: bool,
is_verified: bool,
cached_at: u64,
}
impl User {
pub fn new(
id: UserID,
username: String,
email: String,
is_active: bool,
is_verified: bool,
) -> Self {
Self {
id,
username,
email,
is_active,
is_verified,
cached_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
}
}
pub fn get_uid(&self) -> usize {
self.id.uid
}
pub fn get_server(&self) -> &Server {
&self.id.server
}
pub fn get_user_id(&self) -> &UserID {
&self.id
}
pub fn get_username(&self) -> &str {
&self.username
}
pub fn get_email(&self) -> &str {
&self.email
}
pub fn is_active(&self) -> bool {
self.is_active
}
pub fn is_verified(&self) -> bool {
self.is_verified
}
pub fn cache_age(&self) -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
- self.cached_at
}
pub fn set_cached_time(mut self, time: Option<u64>) -> Self {
if let Some(time) = time {
self.cached_at = time
};
self
}
pub fn guest(server: impl Into<Server>) -> Self {
Self::new(
UserID::new(0, server.into()),
"Guest".into(),
"guest@example.com".into(),
false,
false,
)
}
}
impl From<Value> for User {
fn from(value: Value) -> Self {
let base = User::new(
UserID::new(value.get("uid").integer() as usize, value.get("server").string().into()),
value.get("username").string(),
value.get("email").string(),
value.get("is_active").boolean(),
value.get("is_verified").boolean(),
);
let with_time = value
.try_get("cached_time")
.ok()
.map(|v| v.integer() as u64);
base.set_cached_time(with_time)
}
}
impl Into<Value> for User {
fn into(self) -> Value {
object!({
uid: self.id.uid,
server: self.id.server.to_string(),
username: self.username,
email: self.email,
is_active: self.is_active,
is_verified: self.is_verified,
cached_time: self.cached_at,
})
}
}
impl Into<String> for User {
fn into(self) -> String {
let v: Value = self.into();
v.into_json()
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct UserID {
pub uid: usize,
pub server: Server,
}
impl UserID {
pub fn new(uid: usize, server: Server) -> Self {
Self { uid, server }
}
pub fn from_str(s: &str) -> Option<Self> {
let mut parts = s.splitn(2, '@');
let raw_id = parts.next()?.parse().ok()?;
let host = parts.next()?.to_string();
Some(Self::new(raw_id, host.into()))
}
pub fn is_guest(&self) -> bool {
self.uid == 0
}
}
impl std::fmt::Display for UserID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.uid, self.server)
}
}
impl From<User> for UserID {
fn from(auth_user: User) -> Self {
UserID::new(auth_user.get_uid(), auth_user.get_server().clone())
}
}