use crate::models::crates::get_crate_with_permissions;
use axum::{body::Full, extract, response::IntoResponse, Json};
use bytes::Bytes;
use chartered_db::{
crates::Crate,
users::{User, UserCratePermissionValue as Permission},
ConnectionPool,
};
use chartered_types::cargo::CrateVersion;
use chrono::TimeZone;
use serde::Serialize;
use std::sync::Arc;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Failed to query database")]
Database(#[from] chartered_db::Error),
#[error("{0}")]
CrateFetch(#[from] crate::models::crates::CrateFetchError),
}
impl Error {
pub fn status_code(&self) -> axum::http::StatusCode {
use axum::http::StatusCode;
match self {
Self::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::CrateFetch(e) => e.status_code(),
}
}
}
define_error_response!(Error);
pub async fn handle(
extract::Path((_session_key, name)): extract::Path<(String, String)>,
extract::Extension(db): extract::Extension<ConnectionPool>,
extract::Extension(user): extract::Extension<Arc<User>>,
) -> Result<axum::http::Response<Full<Bytes>>, Error> {
let crate_ = get_crate_with_permissions(db.clone(), user, name, &[Permission::VISIBLE]).await?;
let versions = crate_.clone().versions_with_uploader(db).await?;
Ok(Json(Response {
info: crate_.as_ref().into(),
versions: versions
.into_iter()
.map(|(v, user)| ResponseVersion {
size: v.size,
created_at: chrono::Utc.from_local_datetime(&v.created_at).unwrap(),
inner: v.into_cargo_format(&crate_),
uploader: user.username,
})
.collect(),
})
.into_response())
}
#[derive(Serialize)]
pub struct Response<'a> {
#[serde(flatten)]
info: ResponseInfo<'a>,
versions: Vec<ResponseVersion<'a>>,
}
#[derive(Serialize)]
pub struct ResponseVersion<'a> {
#[serde(flatten)]
inner: CrateVersion<'a>,
size: i32,
created_at: chrono::DateTime<chrono::Utc>,
uploader: String,
}
#[derive(Serialize)]
pub struct ResponseInfo<'a> {
name: &'a str,
readme: Option<&'a str>,
description: Option<&'a str>,
repository: Option<&'a str>,
homepage: Option<&'a str>,
documentation: Option<&'a str>,
}
impl<'a> From<&'a Crate> for ResponseInfo<'a> {
fn from(crate_: &'a Crate) -> Self {
Self {
name: &crate_.name,
readme: crate_.readme.as_deref(),
description: crate_.description.as_deref(),
repository: crate_.repository.as_deref(),
homepage: crate_.homepage.as_deref(),
documentation: crate_.documentation.as_deref(),
}
}
}