2024-03-16 03:30:04 +01:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
2024-03-20 05:44:50 +01:00
|
|
|
use sea_orm::DatabaseConnection;
|
2024-03-16 03:30:04 +01:00
|
|
|
|
2024-03-20 08:56:35 +01:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Context(Arc<ContextInner>);
|
|
|
|
struct ContextInner {
|
|
|
|
db: DatabaseConnection,
|
|
|
|
domain: String,
|
|
|
|
}
|
2024-03-20 09:19:31 +01:00
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
#[macro_export]
|
|
|
|
macro_rules! url {
|
|
|
|
($ctx:expr, $($args: tt)*) => {
|
|
|
|
format!("{}{}", $ctx.base(), format!($($args)*))
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-03-20 08:56:35 +01:00
|
|
|
impl Context {
|
|
|
|
pub fn new(db: DatabaseConnection, mut domain: String) -> Self {
|
|
|
|
if !domain.starts_with("http") {
|
|
|
|
domain = format!("https://{domain}");
|
|
|
|
}
|
|
|
|
if domain.ends_with('/') {
|
|
|
|
domain.replace_range(domain.len()-1.., "");
|
|
|
|
}
|
|
|
|
Context(Arc::new(ContextInner { db, domain }))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn db(&self) -> &DatabaseConnection {
|
|
|
|
&self.0.db
|
|
|
|
}
|
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
pub fn base(&self) -> &str {
|
|
|
|
&self.0.domain
|
|
|
|
}
|
|
|
|
|
2024-03-20 08:56:35 +01:00
|
|
|
pub fn uri(&self, entity: &str, id: String) -> String {
|
|
|
|
if id.starts_with("http") { id } else {
|
|
|
|
format!("{}/{}/{}", self.0.domain, entity, id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
// TODO maybe redo these with enums? idk
|
|
|
|
|
|
|
|
/// get full user id uri
|
|
|
|
pub fn uid(&self, id: String) -> String {
|
2024-03-20 09:19:31 +01:00
|
|
|
self.uri("users", id)
|
|
|
|
}
|
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
/// get full object id uri
|
|
|
|
pub fn oid(&self, id: String) -> String {
|
2024-03-20 09:19:31 +01:00
|
|
|
self.uri("objects", id)
|
|
|
|
}
|
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
/// get full activity id uri
|
|
|
|
pub fn aid(&self, id: String) -> String {
|
2024-03-20 09:19:31 +01:00
|
|
|
self.uri("activities", id)
|
|
|
|
}
|
|
|
|
|
2024-03-20 09:42:25 +01:00
|
|
|
/// get bare uri, usually an uuid but unspecified
|
2024-03-20 08:56:35 +01:00
|
|
|
pub fn id(&self, id: String) -> String {
|
|
|
|
if id.starts_with(&self.0.domain) {
|
2024-03-20 11:00:21 +01:00
|
|
|
id.split('/').last().unwrap_or("").to_string()
|
2024-03-20 08:56:35 +01:00
|
|
|
} else {
|
|
|
|
id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|