use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct UploadId(String);
impl UploadId {
#[must_use]
pub fn new() -> Self {
Self::from_uuid(Uuid::now_v7())
}
#[must_use]
pub fn from_uuid(value: Uuid) -> Self {
Self(format!("wyu_{value}"))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_uuid(&self) -> Result<Uuid, UploadIdParseError> {
parse_uuid_body(&self.0)
}
}
impl Default for UploadId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for UploadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for UploadId {
type Err = UploadIdParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
parse_uuid_body(value)?;
Ok(Self(value.to_owned()))
}
}
impl<'de> Deserialize<'de> for UploadId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::from_str(&value).map_err(serde::de::Error::custom)
}
}
fn parse_uuid_body(value: &str) -> Result<Uuid, UploadIdParseError> {
let Some(body) = value.strip_prefix("wyu_") else {
return Err(UploadIdParseError::MissingPrefix);
};
let uuid = Uuid::parse_str(body).map_err(|_| UploadIdParseError::InvalidUuid)?;
if uuid.get_version_num() != 7 {
return Err(UploadIdParseError::InvalidUuid);
}
Ok(uuid)
}
#[derive(Debug, thiserror::Error)]
pub enum UploadIdParseError {
#[error("upload id must start with wyu_")]
MissingPrefix,
#[error("upload id body must be a valid UUIDv7")]
InvalidUuid,
}